diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index cca07a264b89..0251fafa2b59 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -33,6 +33,9 @@ # PRLabel: %Tables /sdk/data/aztables/ @seankane-msft @jhendrixMSFT +# PRLabel: %Service Bus +/sdk/messaging/azservicebus @richardpark-msft @jhendrixMSFT + # PRLabel: %Mgmt /sdk/resourcemanager/ @ArcturusZhang @lirenhe diff --git a/eng/common/scripts/Prepare-Release.ps1 b/eng/common/scripts/Prepare-Release.ps1 index 2005347822fd..5a8940266bf5 100644 --- a/eng/common/scripts/Prepare-Release.ps1 +++ b/eng/common/scripts/Prepare-Release.ps1 @@ -109,11 +109,15 @@ else $releaseDateString = $ParsedReleaseDate.ToString("MM/dd/yyyy") $month = $ParsedReleaseDate.ToString("MMMM") -Write-Host Write-Host "Assuming release is in $month with release date $releaseDateString" -ForegroundColor Green +if (Test-Path "Function:GetExistingPackageVersions") +{ + $releasedVersions = GetExistingPackageVersions -PackageName $packageProperties.Name -GroupId $packageProperties.Group + $latestReleasedVersion = $releasedVersions[$releasedVersions.Count - 1] + Write-Host "Latest released version: ${latestReleasedVersion}" -ForegroundColor Green +} $currentProjectVersion = $packageProperties.Version - $newVersion = Read-Host -Prompt "Input the new version, or press Enter to use use current project version '$currentProjectVersion'" if (!$newVersion) diff --git a/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 b/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 index 76eff6a31e1f..02e91cc843ac 100644 --- a/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 +++ b/eng/common/scripts/stress-testing/deploy-stress-tests.ps1 @@ -76,9 +76,9 @@ function DeployStressTests( [string]$environment = 'test', [string]$repository = 'images', [boolean]$pushImages = $false, - [string]$clusterGroup = 'rg-stress-test-cluster-', + [string]$clusterGroup = 'rg-stress-cluster-test', [string]$deployId = 'local', - [string]$subscription = 'Azure SDK Test Resources' + [string]$subscription = 'Azure SDK Developer Playground' ) { if ($PSCmdlet.ParameterSetName -eq 'DoLogin') { Login $subscription $clusterGroup $pushImages diff --git a/eng/config.json b/eng/config.json index 5df7a858f2a7..b9d8b2fcc47a 100644 --- a/eng/config.json +++ b/eng/config.json @@ -1,40 +1,44 @@ { "Packages": [ { - "Name": "azidentity", - "CoverageGoal": 0.68 + "Name": "azblob", + "CoverageGoal": 0.45 + }, + { + "Name": "azcore", + "CoverageGoal": 0.85 }, { "Name": "azcosmos", "CoverageGoal": 0.40 }, { - "Name": "azcore", - "CoverageGoal": 0.85 + "Name": "azidentity", + "CoverageGoal": 0.68 }, { - "Name": "internal", - "CoverageGoal": 0.70 + "Name": "azkeys", + "CoverageGoal": 0.72 }, { - "Name": "data", - "CoverageGoal": 0.62 + "Name": "azsecrets", + "CoverageGoal": 0.76 }, { - "Name": "azblob", - "CoverageGoal": 0.45 + "Name": "azservicebus", + "CoverageGoal": 0.24 }, { - "Name": "messaging", - "CoverageGoal": 0.10 + "Name": "data", + "CoverageGoal": 0.62 }, { - "Name": "azsecrets", - "CoverageGoal": 0.76 + "Name": "eng/tools", + "CoverageGoal": 0.0 }, { - "Name": "azkeys", - "CoverageGoal": 0.72 + "Name": "internal", + "CoverageGoal": 0.70 } ] } diff --git a/generate_options.json b/eng/generate_options.json similarity index 100% rename from generate_options.json rename to eng/generate_options.json diff --git a/initScript.sh b/eng/initScript.sh similarity index 100% rename from initScript.sh rename to eng/initScript.sh diff --git a/eng/tools/generator/autorest/model/generateOptions.go b/eng/tools/generator/autorest/model/generateOptions.go index 967817cf68a5..2492bbf86ade 100644 --- a/eng/tools/generator/autorest/model/generateOptions.go +++ b/eng/tools/generator/autorest/model/generateOptions.go @@ -9,7 +9,7 @@ import ( "io/ioutil" ) -// GenerateOptions deserialize from generate_options.json file in root directory of azure-sdk-for-go +// GenerateOptions deserialize from eng/generate_options.json file in root directory of azure-sdk-for-go type GenerateOptions struct { AutorestArguments []string `json:"autorestArguments"` AdditionalOptions []string `json:"additionalOptions,omitempty"` diff --git a/eng/tools/generator/common/constants.go b/eng/tools/generator/common/constants.go index 913bad95b514..0561e6db863b 100644 --- a/eng/tools/generator/common/constants.go +++ b/eng/tools/generator/common/constants.go @@ -5,7 +5,7 @@ package common const ( // DefaultOptionPath the default path of the option file - DefaultOptionPath = "generate_options.json" + DefaultOptionPath = "eng/generate_options.json" Services = "services" ChangelogFilename = "CHANGELOG.md" diff --git a/findTestedPackages.sh b/findTestedPackages.sh deleted file mode 100644 index 2319ed12076d..000000000000 --- a/findTestedPackages.sh +++ /dev/null @@ -1 +0,0 @@ -dirname $(find | grep _test.go | grep -v vendor) | sort -u \ No newline at end of file diff --git a/sdk/azcore/CHANGELOG.md b/sdk/azcore/CHANGELOG.md index 4ada48c38297..f7b6d431cd02 100644 --- a/sdk/azcore/CHANGELOG.md +++ b/sdk/azcore/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.20.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.20.0 (2021-10-22) ### Breaking Changes @@ -18,6 +28,7 @@ * Added string typdef `arm.Endpoint` to provide a hint toward expected ARM client endpoints * `azcore.ClientOptions` contains common pipeline configuration settings * Added support for multi-tenant authorization in `arm/runtime` +* Require one second minimum when calling `PollUntilDone()` ### Bug Fixes * Fixed a potential panic when creating the default Transporter. diff --git a/sdk/azcore/arm/runtime/poller_test.go b/sdk/azcore/arm/runtime/poller_test.go index a17aaab1c638..0e2292c27bf0 100644 --- a/sdk/azcore/arm/runtime/poller_test.go +++ b/sdk/azcore/arm/runtime/poller_test.go @@ -111,7 +111,7 @@ func TestNewPollerAsync(t *testing.T) { t.Fatal(err) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err != nil { t.Fatal(err) } @@ -147,7 +147,7 @@ func TestNewPollerBody(t *testing.T) { t.Fatal(err) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err != nil { t.Fatal(err) } @@ -184,7 +184,7 @@ func TestNewPollerLoc(t *testing.T) { t.Fatal(err) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err != nil { t.Fatal(err) } @@ -215,7 +215,7 @@ func TestNewPollerInitialRetryAfter(t *testing.T) { t.Fatalf("unexpected poller type %s", pt.String()) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err != nil { t.Fatal(err) } @@ -273,7 +273,7 @@ func TestNewPollerFailedWithError(t *testing.T) { t.Fatalf("unexpected poller type %s", pt.String()) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err == nil { t.Fatal(err) } @@ -309,7 +309,7 @@ func TestNewPollerSuccessNoContent(t *testing.T) { t.Fatal(err) } var result mockType - _, err = poller.PollUntilDone(context.Background(), 10*time.Millisecond, &result) + _, err = poller.PollUntilDone(context.Background(), time.Second, &result) if err != nil { t.Fatal(err) } diff --git a/sdk/azcore/internal/pollers/poller.go b/sdk/azcore/internal/pollers/poller.go index 625989e907d1..2a4bfaecab4e 100644 --- a/sdk/azcore/internal/pollers/poller.go +++ b/sdk/azcore/internal/pollers/poller.go @@ -169,9 +169,11 @@ func (l *Poller) FinalResponse(ctx context.Context, respType interface{}) (*http // PollUntilDone will handle the entire span of the polling operation until a terminal state is reached, // then return the final HTTP response for the polling operation and unmarshal the content of the payload // into the respType interface that is provided. -// freq - the time to wait between polling intervals if the endpoint doesn't send a Retry-After header. -// A good starting value is 30 seconds. Note that some resources might benefit from a different value. +// freq - the time to wait between intervals in absence of a Retry-After header. Minimum is one second. func (l *Poller) PollUntilDone(ctx context.Context, freq time.Duration, respType interface{}) (*http.Response, error) { + if freq < time.Second { + return nil, errors.New("polling frequency minimum is one second") + } start := time.Now() logPollUntilDoneExit := func(v interface{}) { log.Writef(log.EventLRO, "END PollUntilDone() for %T: %v, total time: %s", l.lro, v, time.Since(start)) diff --git a/sdk/azcore/internal/pollers/poller_test.go b/sdk/azcore/internal/pollers/poller_test.go index 01dc426cab51..0310bc590951 100644 --- a/sdk/azcore/internal/pollers/poller_test.go +++ b/sdk/azcore/internal/pollers/poller_test.go @@ -132,6 +132,13 @@ func TestNewPoller(t *testing.T) { t.Fatal("unexpected empty resume token") } resp, err = p.PollUntilDone(context.Background(), 1*time.Millisecond, nil) + if err == nil { + t.Fatal("unexpected nil error") + } + if resp != nil { + t.Fatal("expected nil response") + } + resp, err = p.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } @@ -167,7 +174,7 @@ func TestNewPollerWithFinalGET(t *testing.T) { Shape string `json:"shape"` } var w widget - resp, err := p.PollUntilDone(context.Background(), 1*time.Millisecond, &w) + resp, err := p.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -198,7 +205,7 @@ func TestNewPollerFail1(t *testing.T) { p := NewPoller(&fakePoller{Ep: srv.URL()}, firstResp, pl, func(*http.Response) error { return errors.New("failed") }) - resp, err := p.PollUntilDone(context.Background(), 1*time.Millisecond, nil) + resp, err := p.PollUntilDone(context.Background(), time.Second, nil) if err == nil { t.Fatal("unexpected nil error") } else if s := err.Error(); s != "failed" { @@ -221,7 +228,7 @@ func TestNewPollerFail2(t *testing.T) { p := NewPoller(&fakePoller{Ep: srv.URL()}, firstResp, pl, func(*http.Response) error { return errors.New("failed") }) - resp, err := p.PollUntilDone(context.Background(), 1*time.Millisecond, nil) + resp, err := p.PollUntilDone(context.Background(), time.Second, nil) if err == nil { t.Fatal("unexpected nil error") } else if s := err.Error(); s != "failed" { @@ -244,7 +251,7 @@ func TestNewPollerError(t *testing.T) { p := NewPoller(&fakePoller{Ep: srv.URL()}, firstResp, pl, func(*http.Response) error { return errors.New("failed") }) - resp, err := p.PollUntilDone(context.Background(), 1*time.Millisecond, nil) + resp, err := p.PollUntilDone(context.Background(), time.Second, nil) if err == nil { t.Fatal("unexpected nil error") } else if s := err.Error(); s != "fatal" { diff --git a/sdk/azcore/internal/shared/constants.go b/sdk/azcore/internal/shared/constants.go index 5103d87e0053..90b368a437c8 100644 --- a/sdk/azcore/internal/shared/constants.go +++ b/sdk/azcore/internal/shared/constants.go @@ -35,5 +35,5 @@ const ( Module = "azcore" // Version is the semantic version (see http://semver.org) of this module. - Version = "v0.20.0" + Version = "v0.20.1" ) diff --git a/sdk/azcore/runtime/policy_retry.go b/sdk/azcore/runtime/policy_retry.go index 46a630801a28..3bd1c267357e 100644 --- a/sdk/azcore/runtime/policy_retry.go +++ b/sdk/azcore/runtime/policy_retry.go @@ -41,6 +41,7 @@ func setDefaults(o *policy.RetryOptions) { if o.StatusCodes == nil { o.StatusCodes = []int{ http.StatusRequestTimeout, // 408 + http.StatusTooManyRequests, // 429 http.StatusInternalServerError, // 500 http.StatusBadGateway, // 502 http.StatusServiceUnavailable, // 503 diff --git a/sdk/azcore/runtime/poller_test.go b/sdk/azcore/runtime/poller_test.go index 3ac8147fa32c..0d8340e10176 100644 --- a/sdk/azcore/runtime/poller_test.go +++ b/sdk/azcore/runtime/poller_test.go @@ -107,7 +107,7 @@ func TestLocPollerSimple(t *testing.T) { if !closed() { t.Fatal("initial response body wasn't closed") } - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, nil) + resp, err := lro.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } @@ -141,7 +141,7 @@ func TestLocPollerWithWidget(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -178,7 +178,7 @@ func TestLocPollerCancelled(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err == nil { t.Fatal("unexpected nil error") } @@ -218,7 +218,7 @@ func TestLocPollerWithError(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err == nil { t.Fatal("unexpected nil error") } @@ -282,7 +282,7 @@ func TestLocPollerWithResumeToken(t *testing.T) { if err != nil { t.Fatal(err) } - resp, err = lro.PollUntilDone(context.Background(), 5*time.Millisecond, nil) + resp, err = lro.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } @@ -295,7 +295,7 @@ func TestLocPollerWithTimeout(t *testing.T) { srv, close := mock.NewServer() srv.AppendResponse(mock.WithStatusCode(http.StatusAccepted)) srv.AppendResponse(mock.WithStatusCode(http.StatusAccepted)) - srv.AppendResponse(mock.WithSlowResponse(2 * time.Second)) + srv.AppendResponse(mock.WithSlowResponse(5 * time.Second)) defer close() firstResp := &http.Response{ @@ -314,8 +314,8 @@ func TestLocPollerWithTimeout(t *testing.T) { if !closed() { t.Fatal("initial response body wasn't closed") } - ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond) - resp, err := lro.PollUntilDone(ctx, 5*time.Millisecond, nil) + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + resp, err := lro.PollUntilDone(ctx, time.Second, nil) cancel() if err == nil { t.Fatal("unexpected nil error") @@ -357,7 +357,7 @@ func TestOpPollerSimple(t *testing.T) { if !closed() { t.Fatal("initial response body wasn't closed") } - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, nil) + resp, err := lro.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } @@ -401,7 +401,7 @@ func TestOpPollerWithWidgetPUT(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -449,7 +449,7 @@ func TestOpPollerWithWidgetPOSTLocation(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -495,7 +495,7 @@ func TestOpPollerWithWidgetPOST(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -544,7 +544,7 @@ func TestOpPollerWithWidgetResourceLocation(t *testing.T) { t.Fatal("initial response body wasn't closed") } var w widget - resp, err := lro.PollUntilDone(context.Background(), 5*time.Millisecond, &w) + resp, err := lro.PollUntilDone(context.Background(), time.Second, &w) if err != nil { t.Fatal(err) } @@ -613,7 +613,7 @@ func TestOpPollerWithResumeToken(t *testing.T) { if err != nil { t.Fatal(err) } - resp, err = lro.PollUntilDone(context.Background(), 5*time.Millisecond, nil) + resp, err = lro.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } @@ -656,7 +656,7 @@ func TestNopPoller(t *testing.T) { if resp != firstResp { t.Fatal("unexpected response") } - resp, err = lro.PollUntilDone(context.Background(), 5*time.Millisecond, nil) + resp, err = lro.PollUntilDone(context.Background(), time.Second, nil) if err != nil { t.Fatal(err) } diff --git a/sdk/azidentity/CHANGELOG.md b/sdk/azidentity/CHANGELOG.md index 600579a40419..76ece3ac0a64 100644 --- a/sdk/azidentity/CHANGELOG.md +++ b/sdk/azidentity/CHANGELOG.md @@ -2,6 +2,7 @@ ## 0.12.0 (Unreleased) ### Breaking Changes +* Raised minimum go version to 1.16 * Removed `NewAuthenticationPolicy()` from credentials. Clients should instead use azcore's `runtime.NewBearerTokenPolicy()` to construct a bearer token authorization policy. * The `AuthorityHost` field in credential options structs is now a custom type, @@ -47,12 +48,26 @@ cred, err := NewManagedIdentityCredential(opts) ``` * `DeviceCodeCredentialOptions.UserPrompt` has a new type: `func(context.Context, DeviceCodeMessage) error` +* Credential options structs now embed `azcore.ClientOptions`. In addition to changing literal initialization + syntax, this change renames `HTTPClient` fields to `Transport`. +* Renamed `LogCredential` to `EventCredential` +* `AzureCLICredential` no longer reads the environment variable `AZURE_CLI_PATH` +* `NewManagedIdentityCredential` no longer reads environment variables `AZURE_CLIENT_ID` and + `AZURE_RESOURCE_ID`. Use `ManagedIdentityCredentialOptions.ID` instead. +* Unexported `AuthenticationFailedError` and `CredentialUnavailableError` structs. In their place are two + interfaces having the same names. + +### Bugs Fixed +* `AzureCLICredential.GetToken` no longer mutates its `opts.Scopes` ### Features Added * Added connection configuration options to `DefaultAzureCredentialOptions` * `AuthenticationFailedError.RawResponse()` returns the HTTP response motivating the error, if available +### Other Changes +* `NewDefaultAzureCredential()` returns `*DefaultAzureCredential` instead of `*ChainedTokenCredential` +* Added `TenantID` field to `DefaultAzureCredentialOptions` and `AzureCLICredentialOptions` ## 0.11.0 (2021-09-08) ### Breaking Changes diff --git a/sdk/azidentity/README.md b/sdk/azidentity/README.md index d8efc11e2fab..fbac4fe430e3 100644 --- a/sdk/azidentity/README.md +++ b/sdk/azidentity/README.md @@ -79,7 +79,7 @@ The `DefaultAzureCredential` is appropriate for most scenarios where the applica You can find more examples of using various credentials in [Azure Identity Examples Wiki page](https://github.com/Azure/azure-sdk-for-go/wiki/Azure-Identity-Examples). ### Authenticating with `DefaultAzureCredential` -This example demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] module using `DefaultAzureCredential`. +This example demonstrates authenticating the `ResourcesClient` from the armresources module using `DefaultAzureCredential`. ```go // The default credential checks environment variables for configuration. @@ -95,7 +95,7 @@ client := armresources.NewResourcesClient(armcore.NewDefaultConnection(cred, nil See more how to configure the `DefaultAzureCredential` on your workstation or Azure in [Configure DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#configure-defaultazurecredential). ### Authenticating a user assigned managed identity with `DefaultAzureCredential` -This example demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] module using the `DefaultAzureCredential`, deployed to an Azure resource with a user assigned managed identity configured. +This example demonstrates authenticating the `ResourcesClient` from the armresources module using the `DefaultAzureCredential`, deployed to an Azure resource with a user assigned managed identity configured. See more about how to configure a user assigned managed identity for an Azure resource in [Enable managed identity for Azure resources](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-managed-identity-for-azure-resources). @@ -122,7 +122,7 @@ The [Managed identity authentication](https://docs.microsoft.com/azure/active-di ### Examples #### Authenticating in Azure with Managed Identity -This examples demonstrates authenticating the `ResourcesClient` from the [armresources][armresources_library] module using `ManagedIdentityCredential` in a virtual machine, app service, function app, cloud shell, or AKS environment on Azure, with system assigned, or user assigned managed identity enabled. +This examples demonstrates authenticating the `ResourcesClient` from the armresources module using `ManagedIdentityCredential` in a virtual machine, app service, function app, cloud shell, or AKS environment on Azure, with system assigned, or user assigned managed identity enabled. See more about how to configure your Azure resource for managed identity in [Enable managed identity for Azure resources](https://github.com/Azure/azure-sdk-for-go/wiki/Set-up-Your-Environment-for-Authentication#enable-managed-identity-for-azure-resources) @@ -232,7 +232,7 @@ Azure Active Directory ### Logging -This module uses the classification based logging implementation in azcore. To turn on logging set `AZURE_SDK_GO_LOGGING` to `all`. If you only want to include logs for `azidentity`, you must create you own logger and set the log classification as `LogCredential`. +This module uses the classification based logging implementation in azcore. To turn on logging set `AZURE_SDK_GO_LOGGING` to `all`. If you only want to include logs for `azidentity`, you must create you own logger and set the log classification as `EventCredential`. Credentials log basic information only, including `GetToken` success or failure and errors. These log entries do not contain authentication secrets but may contain sensitive information. To obtain more detailed logging, including request/response bodies and header values, make sure to leave the logger as default or enable the `LogRequest` and/or `LogResponse` classifications. A logger that only includes credential logs can be like the following: @@ -245,7 +245,7 @@ azlog.SetListener(func(cls LogClassification, s string) { }) // Include only azidentity credential logs -azlog.SetClassifications(azidentity.LogCredential) +azlog.SetClassifications(azidentity.EventCredential) ``` > CAUTION: logs from credentials contain sensitive information. @@ -280,7 +280,6 @@ or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. [azure_cli]: https://docs.microsoft.com/cli/azure -[armresources_library]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resources/armresources [azblob]: https://github.com/Azure/azure-sdk-for-go/tree/main/sdk ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-go%2Fsdk%2Fidentity%2Fazure-identity%2FREADME.png) diff --git a/sdk/azidentity/aad_identity_client.go b/sdk/azidentity/aad_identity_client.go index 70e156ff6ea8..e0e17874bea4 100644 --- a/sdk/azidentity/aad_identity_client.go +++ b/sdk/azidentity/aad_identity_client.go @@ -6,6 +6,7 @@ package azidentity import ( "context" "encoding/json" + "errors" "fmt" "net/http" "net/url" @@ -54,13 +55,11 @@ type aadIdentityClient struct { pipeline runtime.Pipeline } -// newAADIdentityClient creates a new instance of the aadIdentityClient with the TokenCredentialOptions -// that are passed into it along with a default pipeline. -// options: TokenCredentialOptions that can configure policies for the pipeline and the authority host that -// will be used to retrieve tokens and authenticate -func newAADIdentityClient(authorityHost string, options pipelineOptions) (*aadIdentityClient, error) { +// newAADIdentityClient creates a new instance of the aadIdentityClient +func newAADIdentityClient(authorityHost string, options *azcore.ClientOptions) (*aadIdentityClient, error) { logEnvVars() - return &aadIdentityClient{authorityHost: authorityHost, pipeline: newDefaultPipeline(options)}, nil + pl := runtime.NewPipeline(component, version, nil, nil, options) + return &aadIdentityClient{authorityHost: authorityHost, pipeline: pl}, nil } // aadAuthenticationError is used to unmarshal error responses received from Azure Active Directory @@ -86,7 +85,7 @@ func getError(resp *http.Response) error { } else { msg = fmt.Sprintf("authentication failed: %s", authFailed.Message) } - return &AuthenticationFailedError{msg: msg, resp: resp} + return newAuthenticationFailedError(errors.New(msg), resp) } // refreshAccessToken creates a refresh token request and returns the resulting Access Token or @@ -171,7 +170,7 @@ func (c *aadIdentityClient) createAccessToken(res *http.Response) (*azcore.Acces ExpiresOn string `json:"expires_on"` }{} if err := runtime.UnmarshalAsJSON(res, &value); err != nil { - return nil, fmt.Errorf("internal AccessToken: %w", err) + return nil, fmt.Errorf("internal AccessToken: %v", err) } t, err := value.ExpiresIn.Int64() if err != nil { @@ -193,7 +192,7 @@ func (c *aadIdentityClient) createRefreshAccessToken(res *http.Response) (*token ExpiresOn string `json:"expires_on"` }{} if err := runtime.UnmarshalAsJSON(res, &value); err != nil { - return nil, fmt.Errorf("internal AccessToken: %w", err) + return nil, fmt.Errorf("internal AccessToken: %v", err) } t, err := value.ExpiresIn.Int64() if err != nil { @@ -321,7 +320,7 @@ func (c *aadIdentityClient) createUsernamePasswordAuthRequest(ctx context.Contex func createDeviceCodeResult(res *http.Response) (*deviceCodeResult, error) { value := &deviceCodeResult{} if err := runtime.UnmarshalAsJSON(res, &value); err != nil { - return nil, fmt.Errorf("DeviceCodeResult: %w", err) + return nil, fmt.Errorf("DeviceCodeResult: %v", err) } return value, nil } diff --git a/sdk/azidentity/aad_identity_client_test.go b/sdk/azidentity/aad_identity_client_test.go index a05a8372e072..2d83cafaa31e 100644 --- a/sdk/azidentity/aad_identity_client_test.go +++ b/sdk/azidentity/aad_identity_client_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) @@ -45,10 +46,8 @@ func TestTelemetryDefaultUserAgent(t *testing.T) { srv, close := mock.NewServer() defer close() srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) - options := pipelineOptions{ - HTTPClient: srv, - } - client, err := newAADIdentityClient(srv.URL(), options) + options := azcore.ClientOptions{Transport: srv} + client, err := newAADIdentityClient(srv.URL(), &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) } @@ -73,11 +72,9 @@ func TestTelemetryCustom(t *testing.T) { srv, close := mock.NewServer() defer close() srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) - options := pipelineOptions{ - HTTPClient: srv, - } + options := azcore.ClientOptions{Transport: srv} options.Telemetry.ApplicationID = customTelemetry - client, err := newAADIdentityClient(srv.URL(), options) + client, err := newAADIdentityClient(srv.URL(), &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) } diff --git a/sdk/azidentity/authorization_code_credential.go b/sdk/azidentity/authorization_code_credential.go index 27c2c8126939..e62d9d7a52bf 100644 --- a/sdk/azidentity/authorization_code_credential.go +++ b/sdk/azidentity/authorization_code_credential.go @@ -5,6 +5,7 @@ package azidentity import ( "context" + "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" @@ -13,20 +14,13 @@ import ( // AuthorizationCodeCredentialOptions contain optional parameters that can be used to configure the AuthorizationCodeCredential. // All zero-value fields will be initialized with their default values. type AuthorizationCodeCredentialOptions struct { + azcore.ClientOptions + // Gets the client secret that was generated for the App Registration used to authenticate the client. ClientSecret string // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // AuthorizationCodeCredential enables authentication to Azure Active Directory using an authorization code @@ -49,20 +43,21 @@ type AuthorizationCodeCredential struct { // options: Manage the configuration of the requests sent to Azure Active Directory, they can also include a client secret for web app authentication. func NewAuthorizationCodeCredential(tenantID string, clientID string, authCode string, redirectURL string, options *AuthorizationCodeCredentialOptions) (*AuthorizationCodeCredential, error) { if !validTenantID(tenantID) { - return nil, &CredentialUnavailableError{credentialType: "Authorization Code Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } - if options == nil { - options = &AuthorizationCodeCredentialOptions{} + cp := AuthorizationCodeCredentialOptions{} + if options != nil { + cp = *options } - authorityHost, err := setAuthorityHost(options.AuthorityHost) + authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } - return &AuthorizationCodeCredential{tenantID: tenantID, clientID: clientID, authCode: authCode, clientSecret: options.ClientSecret, redirectURI: redirectURL, client: c}, nil + return &AuthorizationCodeCredential{tenantID: tenantID, clientID: clientID, authCode: authCode, clientSecret: cp.ClientSecret, redirectURI: redirectURL, client: c}, nil } // GetToken obtains a token from Azure Active Directory, using the specified authorization code to authenticate. diff --git a/sdk/azidentity/authorization_code_credential_test.go b/sdk/azidentity/authorization_code_credential_test.go index 5ffc42bba45f..3c3a8f626e7c 100644 --- a/sdk/azidentity/authorization_code_credential_test.go +++ b/sdk/azidentity/authorization_code_credential_test.go @@ -28,10 +28,6 @@ func TestAuthorizationCodeCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestAuthorizationCodeCredential_CreateAuthRequestSuccess(t *testing.T) { @@ -82,7 +78,7 @@ func TestAuthorizationCodeCredential_GetTokenSuccess(t *testing.T) { options := AuthorizationCodeCredentialOptions{} options.ClientSecret = secret options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewAuthorizationCodeCredential(tenantID, clientID, testAuthCode, testRedirectURI, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -100,7 +96,7 @@ func TestAuthorizationCodeCredential_GetTokenInvalidCredentials(t *testing.T) { options := AuthorizationCodeCredentialOptions{} options.ClientSecret = secret options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewAuthorizationCodeCredential(tenantID, clientID, testAuthCode, testRedirectURI, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -109,7 +105,7 @@ func TestAuthorizationCodeCredential_GetTokenInvalidCredentials(t *testing.T) { if err == nil { t.Fatalf("Expected an error but did not receive one.") } - var authFailed *AuthenticationFailedError + var authFailed AuthenticationFailedError if !errors.As(err, &authFailed) { t.Fatalf("Expected: AuthenticationFailedError, Received: %T", err) } @@ -125,7 +121,7 @@ func TestAuthorizationCodeCredential_GetTokenUnexpectedJSON(t *testing.T) { options := AuthorizationCodeCredentialOptions{} options.ClientSecret = secret options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewAuthorizationCodeCredential(tenantID, clientID, testAuthCode, testRedirectURI, &options) if err != nil { t.Fatalf("Failed to create the credential") diff --git a/sdk/azidentity/azidentity.go b/sdk/azidentity/azidentity.go index 891454c01263..908611ab91b4 100644 --- a/sdk/azidentity/azidentity.go +++ b/sdk/azidentity/azidentity.go @@ -10,12 +10,8 @@ import ( "os" "path" "regexp" - "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" ) // AuthorityHost is the base URL for Azure Active Directory @@ -56,71 +52,6 @@ type tokenResponse struct { refreshToken string } -// AuthenticationFailedError is returned when the authentication request has failed. -type AuthenticationFailedError struct { - inner error - msg string - resp *http.Response -} - -// Unwrap method on AuthenticationFailedError provides access to the inner error if available. -func (e *AuthenticationFailedError) Unwrap() error { - return e.inner -} - -// NonRetriable indicates that this error should not be retried. -func (e *AuthenticationFailedError) NonRetriable() { - // marker method -} - -func (e *AuthenticationFailedError) Error() string { - return e.msg -} - -// RawResponse returns the HTTP response motivating the error, if available -func (e *AuthenticationFailedError) RawResponse() *http.Response { - return e.resp -} - -var _ azcore.HTTPResponse = (*AuthenticationFailedError)(nil) -var _ errorinfo.NonRetriable = (*AuthenticationFailedError)(nil) - -// CredentialUnavailableError is the error type returned when the conditions required to -// create a credential do not exist or are unavailable. -type CredentialUnavailableError struct { - // CredentialType holds the name of the credential that is unavailable - credentialType string - // Message contains the reason why the credential is unavailable - message string -} - -func (e *CredentialUnavailableError) Error() string { - return e.credentialType + ": " + e.message -} - -// NonRetriable indicates that this error should not be retried. -func (e *CredentialUnavailableError) NonRetriable() { - // marker method -} - -var _ errorinfo.NonRetriable = (*CredentialUnavailableError)(nil) - -// pipelineOptions are used to configure how requests are made to Azure Active Directory. -type pipelineOptions struct { - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions -} - // setAuthorityHost initializes the authority host for credentials. func setAuthorityHost(authorityHost AuthorityHost) (string, error) { host := string(authorityHost) @@ -140,54 +71,6 @@ func setAuthorityHost(authorityHost AuthorityHost) (string, error) { return host, nil } -// newDefaultPipeline creates a pipeline using the specified pipeline options. -func newDefaultPipeline(o pipelineOptions) runtime.Pipeline { - policies := []policy.Policy{} - if !o.Telemetry.Disabled { - policies = append(policies, runtime.NewTelemetryPolicy(component, version, &o.Telemetry)) - } - policies = append(policies, runtime.NewRetryPolicy(&o.Retry)) - policies = append(policies, runtime.NewLogPolicy(&o.Logging)) - return runtime.NewPipeline(o.HTTPClient, policies...) -} - -// newDefaultMSIPipeline creates a pipeline using the specified pipeline options needed -// for a Managed Identity, such as a MSI specific retry policy. -func newDefaultMSIPipeline(o ManagedIdentityCredentialOptions) runtime.Pipeline { - var statusCodes []int - // retry policy for MSI is not end-user configurable - retryOpts := policy.RetryOptions{ - MaxRetries: 5, - MaxRetryDelay: 1 * time.Minute, - RetryDelay: 2 * time.Second, - TryTimeout: 1 * time.Minute, - StatusCodes: append(statusCodes, - // The following status codes are a subset of those found in azcore.StatusCodesForRetry, these are the only ones specifically needed for MSI scenarios - http.StatusRequestTimeout, // 408 - http.StatusTooManyRequests, // 429 - http.StatusInternalServerError, // 500 - http.StatusBadGateway, // 502 - http.StatusGatewayTimeout, // 504 - http.StatusNotFound, //404 - http.StatusGone, //410 - // all remaining 5xx - http.StatusNotImplemented, // 501 - http.StatusHTTPVersionNotSupported, // 505 - http.StatusVariantAlsoNegotiates, // 506 - http.StatusInsufficientStorage, // 507 - http.StatusLoopDetected, // 508 - http.StatusNotExtended, // 510 - http.StatusNetworkAuthenticationRequired), // 511 - } - policies := []policy.Policy{} - if !o.Telemetry.Disabled { - policies = append(policies, runtime.NewTelemetryPolicy(component, version, &o.Telemetry)) - } - policies = append(policies, runtime.NewRetryPolicy(&retryOpts)) - policies = append(policies, runtime.NewLogPolicy(&o.Logging)) - return runtime.NewPipeline(o.HTTPClient, policies...) -} - // validTenantID return true is it receives a valid tenantID, returns false otherwise func validTenantID(tenantID string) bool { match, err := regexp.MatchString("^[0-9a-zA-Z-.]+$", tenantID) diff --git a/sdk/azidentity/azidentity_test.go b/sdk/azidentity/azidentity_test.go index 0c8bb85f1369..c7595d6c7a2b 100644 --- a/sdk/azidentity/azidentity_test.go +++ b/sdk/azidentity/azidentity_test.go @@ -18,6 +18,7 @@ const ( accessTokenRespError = `{"error": "invalid_client","error_description": "Invalid client secret is provided.","error_codes": [0],"timestamp": "2019-12-01 19:00:00Z","trace_id": "2d091b0","correlation_id": "a999","error_uri": "https://login.contoso.com/error?code=0"}` accessTokenRespSuccess = `{"access_token": "` + tokenValue + `", "expires_in": 3600}` accessTokenRespMalformed = `{"access_token": 0, "expires_in": 3600}` + tokenValue = "new_token" ) func defaultTestPipeline(srv policy.Transporter, cred azcore.TokenCredential, scope string) runtime.Pipeline { @@ -25,11 +26,8 @@ func defaultTestPipeline(srv policy.Transporter, cred azcore.TokenCredential, sc MaxRetryDelay: 500 * time.Millisecond, RetryDelay: 50 * time.Millisecond, } - return runtime.NewPipeline( - srv, - runtime.NewRetryPolicy(&retryOpts), - runtime.NewBearerTokenPolicy(cred, runtime.AuthenticationOptions{TokenRequest: policy.TokenRequestOptions{Scopes: []string{scope}}}), - runtime.NewLogPolicy(nil)) + b := runtime.NewBearerTokenPolicy(cred, []string{scope}, nil) + return runtime.NewPipeline("azidentity-test", version, nil, []policy.Policy{b}, &azcore.ClientOptions{Retry: retryOpts, Transport: srv}) } // constants for this file @@ -38,25 +36,30 @@ const ( customHostString = "https://custommock.com/" ) -// Set AZURE_AUTHORITY_HOST for the duration of a test. Restore its prior value -// after the test completes. Prevents tests which set the variable from breaking live -// tests in sovereign clouds. Obviated by 1.17's T.Setenv -func setEnvAuthorityHost(host string, t *testing.T) { - originalHost := os.Getenv("AZURE_AUTHORITY_HOST") - err := os.Setenv("AZURE_AUTHORITY_HOST", host) - if err != nil { - t.Fatalf("Unexpected error setting AZURE_AUTHORITY_HOST: %v", err) +// Set environment variables for the duration of a test. Restore their prior values +// after the test completes. Obviated by 1.17's T.Setenv +func setEnvironmentVariables(t *testing.T, vars map[string]string) { + priorValues := make(map[string]string, len(vars)) + for k, v := range vars { + priorValues[k] = os.Getenv(k) + err := os.Setenv(k, v) + if err != nil { + t.Fatalf("Unexpected error setting %s: %v", k, err) + } } + t.Cleanup(func() { - err = os.Setenv("AZURE_AUTHORITY_HOST", originalHost) - if err != nil { - t.Fatalf("Unexpected error resetting AZURE_AUTHORITY_HOST: %v", err) + for k, v := range priorValues { + err := os.Setenv(k, v) + if err != nil { + t.Fatalf("Unexpected error resetting %s: %v", k, err) + } } }) } func Test_SetEnvAuthorityHost(t *testing.T) { - setEnvAuthorityHost(envHostString, t) + setEnvironmentVariables(t, map[string]string{"AZURE_AUTHORITY_HOST": envHostString}) authorityHost, err := setAuthorityHost("") if err != nil { t.Fatal(err) @@ -67,7 +70,7 @@ func Test_SetEnvAuthorityHost(t *testing.T) { } func Test_CustomAuthorityHost(t *testing.T) { - setEnvAuthorityHost(envHostString, t) + setEnvironmentVariables(t, map[string]string{"AZURE_AUTHORITY_HOST": envHostString}) authorityHost, err := setAuthorityHost(customHostString) if err != nil { t.Fatal(err) @@ -79,7 +82,7 @@ func Test_CustomAuthorityHost(t *testing.T) { } func Test_DefaultAuthorityHost(t *testing.T) { - setEnvAuthorityHost("", t) + setEnvironmentVariables(t, map[string]string{"AZURE_AUTHORITY_HOST": ""}) authorityHost, err := setAuthorityHost("") if err != nil { t.Fatal(err) @@ -90,7 +93,7 @@ func Test_DefaultAuthorityHost(t *testing.T) { } func Test_NonHTTPSAuthorityHost(t *testing.T) { - setEnvAuthorityHost("", t) + setEnvironmentVariables(t, map[string]string{"AZURE_AUTHORITY_HOST": ""}) authorityHost, err := setAuthorityHost("http://foo.com") if err == nil { t.Fatal("Expected an error but did not receive one.") diff --git a/sdk/azidentity/azure_cli_credential.go b/sdk/azidentity/azure_cli_credential.go index bfbe9a6ab17d..5713c8f30d53 100644 --- a/sdk/azidentity/azure_cli_credential.go +++ b/sdk/azidentity/azure_cli_credential.go @@ -7,6 +7,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "os" "os/exec" @@ -20,12 +21,15 @@ import ( ) // used by tests to fake invoking the CLI -type azureCLITokenProvider func(ctx context.Context, resource string) ([]byte, error) +type azureCLITokenProvider func(ctx context.Context, resource string, tenantID string) ([]byte, error) // AzureCLICredentialOptions contains options used to configure the AzureCLICredential // All zero-value fields will be initialized with their default values. type AzureCLICredentialOptions struct { tokenProvider azureCLITokenProvider + // TenantID identifies the tenant the credential should authenticate in. + // Defaults to the CLI's default tenant, which is typically the home tenant of the user logged in to the CLI. + TenantID string } // init returns an instance of AzureCLICredentialOptions initialized with default values. @@ -38,6 +42,7 @@ func (o *AzureCLICredentialOptions) init() { // AzureCLICredential enables authentication to Azure Active Directory using the Azure CLI command "az account get-access-token". type AzureCLICredential struct { tokenProvider azureCLITokenProvider + tenantID string } // NewAzureCLICredential constructs a new AzureCLICredential with the details needed to authenticate against Azure Active Directory @@ -50,6 +55,7 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent cp.init() return &AzureCLICredential{ tokenProvider: cp.tokenProvider, + tenantID: cp.TenantID, }, nil } @@ -58,9 +64,12 @@ func NewAzureCLICredential(options *AzureCLICredentialOptions) (*AzureCLICredent // opts: TokenRequestOptions contains the list of scopes for which the token will have access. // Returns an AccessToken which can be used to authenticate service client calls. func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) { - // The following code will remove the /.default suffix from the scope passed into the method since AzureCLI expect a resource string instead of a scope string - opts.Scopes[0] = strings.TrimSuffix(opts.Scopes[0], defaultSuffix) - at, err := c.authenticate(ctx, opts.Scopes[0]) + if len(opts.Scopes) != 1 { + return nil, errors.New("this credential requires exactly one scope per token request") + } + // CLI expects an AAD v1 resource, not a v2 scope + scope := strings.TrimSuffix(opts.Scopes[0], defaultSuffix) + at, err := c.authenticate(ctx, scope) if err != nil { addGetTokenFailureLogs("Azure CLI Credential", err, true) return nil, err @@ -69,14 +78,14 @@ func (c *AzureCLICredential) GetToken(ctx context.Context, opts policy.TokenRequ return at, nil } -const timeoutCLIRequest = 10000 * time.Millisecond +const timeoutCLIRequest = 10 * time.Second // authenticate creates a client secret authentication request and returns the resulting Access Token or // an error in case of authentication failure. // ctx: The current request context // scopes: The scopes for which the token has access func (c *AzureCLICredential) authenticate(ctx context.Context, resource string) (*azcore.AccessToken, error) { - output, err := c.tokenProvider(ctx, resource) + output, err := c.tokenProvider(ctx, resource, c.tenantID) if err != nil { return nil, err } @@ -84,44 +93,36 @@ func (c *AzureCLICredential) authenticate(ctx context.Context, resource string) return c.createAccessToken(output) } -func defaultTokenProvider() func(ctx context.Context, resource string) ([]byte, error) { - return func(ctx context.Context, resource string) ([]byte, error) { - // This is the path that a developer can set to tell this class what the install path for Azure CLI is. - const azureCLIPath = "AZURE_CLI_PATH" - - // The default install paths are used to find Azure CLI. This is for security, so that any path in the calling program's Path environment is not used to execute Azure CLI. - azureCLIDefaultPathWindows := fmt.Sprintf("%s\\Microsoft SDKs\\Azure\\CLI2\\wbin; %s\\Microsoft SDKs\\Azure\\CLI2\\wbin", os.Getenv("ProgramFiles(x86)"), os.Getenv("ProgramFiles")) - - // Default path for non-Windows. - const azureCLIDefaultPath = "/bin:/sbin:/usr/bin:/usr/local/bin" - - // Validate resource, since it gets sent as a command line argument to Azure CLI - const invalidResourceErrorTemplate = "resource %s is not in expected format. Only alphanumeric characters, [dot], [colon], [hyphen], and [forward slash] are allowed" +func defaultTokenProvider() func(ctx context.Context, resource string, tenantID string) ([]byte, error) { + return func(ctx context.Context, resource string, tenantID string) ([]byte, error) { match, err := regexp.MatchString("^[0-9a-zA-Z-.:/]+$", resource) if err != nil { return nil, err } if !match { - return nil, fmt.Errorf(invalidResourceErrorTemplate, resource) + return nil, fmt.Errorf(`unexpected scope "%s". Only alphanumeric characters and ".", ";", "-", and "/" are allowed`, resource) } ctx, cancel := context.WithTimeout(ctx, timeoutCLIRequest) defer cancel() - // Execute Azure CLI to get token + commandLine := "az account get-access-token -o json --resource " + resource + if tenantID != "" { + commandLine += " --tenant " + tenantID + } var cliCmd *exec.Cmd if runtime.GOOS == "windows" { - cliCmd = exec.CommandContext(ctx, fmt.Sprintf("%s\\system32\\cmd.exe", os.Getenv("windir"))) - cliCmd.Env = os.Environ() - cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s;%s", os.Getenv(azureCLIPath), azureCLIDefaultPathWindows)) - cliCmd.Args = append(cliCmd.Args, "/c", "az") + dir := os.Getenv("SYSTEMROOT") + if dir == "" { + return nil, errors.New("environment variable 'SYSTEMROOT' has no value") + } + cliCmd = exec.CommandContext(ctx, "cmd.exe", "/c", commandLine) + cliCmd.Dir = dir } else { - cliCmd = exec.CommandContext(ctx, "az") - cliCmd.Env = os.Environ() - cliCmd.Env = append(cliCmd.Env, fmt.Sprintf("PATH=%s:%s", os.Getenv(azureCLIPath), azureCLIDefaultPath)) + cliCmd = exec.CommandContext(ctx, "/bin/sh", "-c", commandLine) + cliCmd.Dir = "/bin" } - cliCmd.Args = append(cliCmd.Args, "account", "get-access-token", "-o", "json", "--resource", resource) - + cliCmd.Env = os.Environ() var stderr bytes.Buffer cliCmd.Stderr = &stderr @@ -132,7 +133,7 @@ func defaultTokenProvider() func(ctx context.Context, resource string) ([]byte, // if there's no output in stderr report the error message instead msg = err.Error() } - return nil, &CredentialUnavailableError{credentialType: "Azure CLI Credential", message: msg} + return nil, newCredentialUnavailableError("Azure CLI Credential", msg) } return output, nil diff --git a/sdk/azidentity/azure_cli_credential_test.go b/sdk/azidentity/azure_cli_credential_test.go index 9259e9e30fc2..ac908024abe7 100644 --- a/sdk/azidentity/azure_cli_credential_test.go +++ b/sdk/azidentity/azure_cli_credential_test.go @@ -15,14 +15,14 @@ import ( ) var ( - mockCLITokenProviderSuccess = func(ctx context.Context, resource string) ([]byte, error) { + mockCLITokenProviderSuccess = func(ctx context.Context, resource string, tenantID string) ([]byte, error) { return []byte(" {\"accessToken\":\"mocktoken\" , " + "\"expiresOn\": \"2007-01-01 01:01:01.079627\"," + "\"subscription\": \"mocksub\"," + "\"tenant\": \"mocktenant\"," + "\"tokenType\": \"mocktype\"}"), nil } - mockCLITokenProviderFailure = func(ctx context.Context, resource string) ([]byte, error) { + mockCLITokenProviderFailure = func(ctx context.Context, resource string, tenantID string) ([]byte, error) { return nil, errors.New("provider failure message") } ) @@ -59,6 +59,32 @@ func TestAzureCLICredential_GetTokenInvalidToken(t *testing.T) { } } +func TestAzureCLICredential_TenantID(t *testing.T) { + expected := "expected-tenant-id" + called := false + options := AzureCLICredentialOptions{ + TenantID: expected, + tokenProvider: func(ctx context.Context, resource, tenantID string) ([]byte, error) { + called = true + if tenantID != expected { + t.Fatal("Unexpected tenant ID: " + tenantID) + } + return mockCLITokenProviderSuccess(ctx, resource, tenantID) + }, + } + cred, err := NewAzureCLICredential(&options) + if err != nil { + t.Fatalf("Unable to create credential. Received: %v", err) + } + _, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{scope}}) + if err != nil { + t.Fatalf("Unexpected error: %v", err) + } + if !called { + t.Fatal("token provider wasn't called") + } +} + func TestBearerPolicy_AzureCLICredential(t *testing.T) { srv, close := mock.NewTLSServer() defer close() diff --git a/sdk/azidentity/chained_token_credential.go b/sdk/azidentity/chained_token_credential.go index 128b65d882a3..f2eea3f271e9 100644 --- a/sdk/azidentity/chained_token_credential.go +++ b/sdk/azidentity/chained_token_credential.go @@ -6,6 +6,7 @@ package azidentity import ( "context" "errors" + "fmt" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" @@ -25,15 +26,11 @@ type ChainedTokenCredential struct { // NewChainedTokenCredential creates an instance of ChainedTokenCredential with the specified TokenCredential sources. func NewChainedTokenCredential(sources []azcore.TokenCredential, options *ChainedTokenCredentialOptions) (*ChainedTokenCredential, error) { if len(sources) == 0 { - credErr := &CredentialUnavailableError{credentialType: "Chained Token Credential", message: "Length of sources cannot be 0"} - logCredentialError(credErr.credentialType, credErr) - return nil, credErr + return nil, errors.New("sources must contain at least one TokenCredential") } for _, source := range sources { if source == nil { // cannot have a nil credential in the chain or else the application will panic when GetToken() is called on nil - credErr := &CredentialUnavailableError{credentialType: "Chained Token Credential", message: "Sources cannot contain a nil TokenCredential"} - logCredentialError(credErr.credentialType, credErr) - return nil, credErr + return nil, errors.New("sources cannot contain nil") } } cp := make([]azcore.TokenCredential, len(sources)) @@ -43,22 +40,23 @@ func NewChainedTokenCredential(sources []azcore.TokenCredential, options *Chaine // GetToken sequentially calls TokenCredential.GetToken on all the specified sources, returning the token from the first successful call to GetToken(). func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (token *azcore.AccessToken, err error) { - var errList []*CredentialUnavailableError + var errList []CredentialUnavailableError // loop through all of the credentials provided in sources for _, cred := range c.sources { // make a GetToken request for the current credential in the loop token, err = cred.GetToken(ctx, opts) // check if we received a CredentialUnavailableError - var credErr *CredentialUnavailableError + var credErr CredentialUnavailableError if errors.As(err, &credErr) { // if we did receive a CredentialUnavailableError then we append it to our error slice and continue looping for a good credential errList = append(errList, credErr) } else if err != nil { // if we receive some other type of error then we must stop looping and process the error accordingly - var authenticationFailed *AuthenticationFailedError - if errors.As(err, &authenticationFailed) { + var authFailed AuthenticationFailedError + if errors.As(err, &authFailed) { // if the error is an AuthenticationFailedError we return the error related to the invalid credential and append all of the other error messages received prior to this point - authErr := &AuthenticationFailedError{msg: "Received an AuthenticationFailedError, there is an invalid credential in the chain. " + createChainedErrorMessage(errList), inner: err} + err = fmt.Errorf("Authentication failed:\n%s\n%s"+createChainedErrorMessage(errList), err) + authErr := newAuthenticationFailedError(err, authFailed.RawResponse()) return nil, authErr } // if we receive some other error type this is unexpected and we simple return the unexpected error @@ -70,14 +68,14 @@ func (c *ChainedTokenCredential) GetToken(ctx context.Context, opts policy.Token } } // if we reach this point it means that all of the credentials in the chain returned CredentialUnavailableErrors - credErr := &CredentialUnavailableError{credentialType: "Chained Token Credential", message: createChainedErrorMessage(errList)} + credErr := newCredentialUnavailableError("Chained Token Credential", createChainedErrorMessage(errList)) // skip adding the stack trace here as it was already logged by other calls to GetToken() addGetTokenFailureLogs("Chained Token Credential", credErr, false) return nil, credErr } // helper function used to chain the error messages of the CredentialUnavailableError slice -func createChainedErrorMessage(errList []*CredentialUnavailableError) string { +func createChainedErrorMessage(errList []CredentialUnavailableError) string { msg := "" for _, err := range errList { msg += err.Error() diff --git a/sdk/azidentity/chained_token_credential_test.go b/sdk/azidentity/chained_token_credential_test.go index 3b163edb17cd..4d32c0b05bc1 100644 --- a/sdk/azidentity/chained_token_credential_test.go +++ b/sdk/azidentity/chained_token_credential_test.go @@ -48,17 +48,10 @@ func TestChainedTokenCredential_InstantiateFailure(t *testing.T) { if err == nil { t.Fatalf("Expected an error for sending a nil credential in the chain") } - var credErr *CredentialUnavailableError - if !errors.As(err, &credErr) { - t.Fatalf("Expected a CredentialUnavailableError, but received: %T", credErr) - } _, err = NewChainedTokenCredential([]azcore.TokenCredential{}, nil) if err == nil { t.Fatalf("Expected an error for not sending any credential sources") } - if !errors.As(err, &credErr) { - t.Fatalf("Expected a CredentialUnavailableError, but received: %T", credErr) - } } func TestChainedTokenCredential_GetTokenSuccess(t *testing.T) { @@ -71,12 +64,15 @@ func TestChainedTokenCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv secCred, err := NewClientSecretCredential(tenantID, clientID, secret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) } - envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{HTTPClient: srv, AuthorityHost: AuthorityHost(srv.URL())}) + envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{ + ClientOptions: azcore.ClientOptions{Transport: srv}, + AuthorityHost: AuthorityHost(srv.URL()), + }) if err != nil { t.Fatalf("Failed to create environment credential: %v", err) } @@ -102,7 +98,7 @@ func TestChainedTokenCredential_GetTokenFail(t *testing.T) { srv.AppendResponse(mock.WithStatusCode(http.StatusUnauthorized)) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv secCred, err := NewClientSecretCredential(tenantID, clientID, wrongSecret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -115,9 +111,9 @@ func TestChainedTokenCredential_GetTokenFail(t *testing.T) { if err == nil { t.Fatalf("Expected an error but did not receive one") } - var authErr *AuthenticationFailedError + var authErr AuthenticationFailedError if !errors.As(err, &authErr) { - t.Fatalf("Expected Error Type: AuthenticationFailedError, ReceivedErrorType: %T", err) + t.Fatalf("Expected AuthenticationFailedError, received %T", err) } if len(err.Error()) == 0 { t.Fatalf("Did not create an appropriate error message") @@ -127,11 +123,11 @@ func TestChainedTokenCredential_GetTokenFail(t *testing.T) { func TestChainedTokenCredential_GetTokenWithUnavailableCredentialInChain(t *testing.T) { srv, close := mock.NewTLSServer() defer close() - srv.AppendError(&CredentialUnavailableError{credentialType: "MockCredential", message: "Mocking a credential unavailable error"}) + srv.AppendError(newCredentialUnavailableError("MockCredential", "Mocking a credential unavailable error")) srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv secCred, err := NewClientSecretCredential(tenantID, clientID, wrongSecret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -168,7 +164,7 @@ func TestBearerPolicy_ChainedTokenCredential(t *testing.T) { srv.AppendResponse(mock.WithStatusCode(http.StatusOK)) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewClientSecretCredential(tenantID, clientID, secret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) diff --git a/sdk/azidentity/ci.yml b/sdk/azidentity/ci.yml index f145e1fd2d4a..459fbc9e256f 100644 --- a/sdk/azidentity/ci.yml +++ b/sdk/azidentity/ci.yml @@ -22,7 +22,6 @@ pr: - sdk/azidentity/ stages: -- template: ../../eng/pipelines/templates/jobs/archetype-sdk-client.yml +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml parameters: ServiceDirectory: 'azidentity' - RunTests: true diff --git a/sdk/azidentity/client_certificate_credential.go b/sdk/azidentity/client_certificate_credential.go index 2730f88bbf85..d31ac88258ba 100644 --- a/sdk/azidentity/client_certificate_credential.go +++ b/sdk/azidentity/client_certificate_credential.go @@ -19,6 +19,8 @@ import ( // ClientCertificateCredentialOptions contain optional parameters that can be used when configuring a ClientCertificateCredential. // All zero-value fields will be initialized with their default values. type ClientCertificateCredentialOptions struct { + azcore.ClientOptions + // The password required to decrypt the private key. Leave empty if there is no password. Password string // Set to true to include x5c header in client claims when acquiring a token to enable @@ -27,15 +29,6 @@ type ClientCertificateCredentialOptions struct { // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // ClientCertificateCredential enables authentication of a service principal to Azure Active Directory using a certificate that is assigned to its App Registration. More information @@ -56,29 +49,29 @@ type ClientCertificateCredential struct { // options: ClientCertificateCredentialOptions that can be used to provide additional configurations for the credential, such as the certificate password. func NewClientCertificateCredential(tenantID string, clientID string, certData []byte, options *ClientCertificateCredentialOptions) (*ClientCertificateCredential, error) { if !validTenantID(tenantID) { - return nil, &CredentialUnavailableError{credentialType: "Client Certificate Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } - if options == nil { - options = &ClientCertificateCredentialOptions{} + cp := ClientCertificateCredentialOptions{} + if options != nil { + cp = *options } - cert, err := loadPEMCert(certData, options.Password, options.SendCertificateChain) + cert, err := loadPEMCert(certData, cp.Password, cp.SendCertificateChain) if err != nil { - cert, err = loadPKCS12Cert(certData, options.Password, options.SendCertificateChain) + cert, err = loadPKCS12Cert(certData, cp.Password, cp.SendCertificateChain) } if err != nil { - credErr := &CredentialUnavailableError{credentialType: "Client Certificate Credential", message: err.Error()} - logCredentialError(credErr.credentialType, credErr) - return nil, credErr + logCredentialError("Client Certificate Credential", err) + return nil, err } - authorityHost, err := setAuthorityHost(options.AuthorityHost) + authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } - return &ClientCertificateCredential{tenantID: tenantID, clientID: clientID, cert: cert, sendCertificateChain: options.SendCertificateChain, client: c}, nil + return &ClientCertificateCredential{tenantID: tenantID, clientID: clientID, cert: cert, sendCertificateChain: cp.SendCertificateChain, client: c}, nil } // contains decoded cert contents we care about diff --git a/sdk/azidentity/client_certificate_credential_test.go b/sdk/azidentity/client_certificate_credential_test.go index 8cb58f5e2908..4a23449d3c4d 100644 --- a/sdk/azidentity/client_certificate_credential_test.go +++ b/sdk/azidentity/client_certificate_credential_test.go @@ -40,10 +40,6 @@ func TestClientCertificateCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestClientCertificateCredential_CreateAuthRequestSuccess(t *testing.T) { @@ -166,7 +162,7 @@ func TestClientCertificateCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv options.Password = test.password cred, err := NewClientCertificateCredential(tenantID, clientID, test.certData, &options) if err != nil { @@ -189,7 +185,7 @@ func TestClientCertificateCredential_GetTokenSuccess_withCertificateChain(t *tes options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) options.SendCertificateChain = true - options.HTTPClient = srv + options.Transport = srv options.Password = test.password cred, err := NewClientCertificateCredential(tenantID, clientID, test.certData, &options) if err != nil { @@ -211,7 +207,7 @@ func TestClientCertificateCredential_GetTokenInvalidCredentials(t *testing.T) { srv.SetResponse(mock.WithStatusCode(http.StatusUnauthorized)) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv options.Password = test.password cred, err := NewClientCertificateCredential(tenantID, clientID, test.certData, &options) if err != nil { @@ -221,7 +217,7 @@ func TestClientCertificateCredential_GetTokenInvalidCredentials(t *testing.T) { if err == nil { t.Fatalf("Expected to receive a nil error, but received: %v", err) } - var authFailed *AuthenticationFailedError + var authFailed AuthenticationFailedError if !errors.As(err, &authFailed) { t.Fatalf("Expected: AuthenticationFailedError, Received: %T", err) } @@ -235,7 +231,7 @@ func TestClientCertificateCredential_GetTokenCheckPrivateKeyBlocks(t *testing.T) srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv certData, err := os.ReadFile("testdata/certificate_formatB.pem") if err != nil { t.Fatalf("Failed to read certificate file: %s", err.Error()) @@ -256,7 +252,7 @@ func TestClientCertificateCredential_NoData(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv _, err := NewClientCertificateCredential(tenantID, clientID, []byte{}, &options) if err == nil { t.Fatalf("Expected an error but received nil") @@ -269,7 +265,7 @@ func TestClientCertificateCredential_NoCertificate(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv certData, err := os.ReadFile("testdata/certificate_empty.pem") if err != nil { t.Fatalf("Failed to read certificate file: %s", err.Error()) @@ -286,7 +282,7 @@ func TestClientCertificateCredential_NoPrivateKey(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv certData, err := os.ReadFile("testdata/certificate_nokey.pem") if err != nil { t.Fatalf("Failed to read certificate file: %s", err.Error()) @@ -304,7 +300,7 @@ func TestBearerPolicy_ClientCertificateCredential(t *testing.T) { srv.AppendResponse(mock.WithStatusCode(http.StatusOK)) options := ClientCertificateCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewClientCertificateCredential(tenantID, clientID, pemCert, &options) if err != nil { t.Fatalf("Did not expect an error but received: %v", err) diff --git a/sdk/azidentity/client_secret_credential.go b/sdk/azidentity/client_secret_credential.go index d6aeb2d5342c..adcfa4d48255 100644 --- a/sdk/azidentity/client_secret_credential.go +++ b/sdk/azidentity/client_secret_credential.go @@ -5,6 +5,7 @@ package azidentity import ( "context" + "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" @@ -13,18 +14,11 @@ import ( // ClientSecretCredentialOptions configures the ClientSecretCredential with optional parameters. // All zero-value fields will be initialized with their default values. type ClientSecretCredentialOptions struct { + azcore.ClientOptions + // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // ClientSecretCredential enables authentication to Azure Active Directory using a client secret that was generated for an App Registration. More information on how @@ -44,16 +38,17 @@ type ClientSecretCredential struct { // options: allow to configure the management of the requests sent to Azure Active Directory. func NewClientSecretCredential(tenantID string, clientID string, clientSecret string, options *ClientSecretCredentialOptions) (*ClientSecretCredential, error) { if !validTenantID(tenantID) { - return nil, &CredentialUnavailableError{credentialType: "Client Secret Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } - if options == nil { - options = &ClientSecretCredentialOptions{} + cp := ClientSecretCredentialOptions{} + if options != nil { + cp = *options } - authorityHost, err := setAuthorityHost(options.AuthorityHost) + authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } diff --git a/sdk/azidentity/client_secret_credential_test.go b/sdk/azidentity/client_secret_credential_test.go index 8cae6b6deb67..d12a2485d76f 100644 --- a/sdk/azidentity/client_secret_credential_test.go +++ b/sdk/azidentity/client_secret_credential_test.go @@ -18,10 +18,9 @@ import ( const ( tenantID = "expected-tenant" badTenantID = "bad_tenant" - clientID = "expected_client" + clientID = "expected-client-id" secret = "secret" wrongSecret = "wrong_secret" - tokenValue = "new_token" scope = "https://storage.azure.com/.default" defaultTestAuthorityHost = "login.microsoftonline.com" ) @@ -34,10 +33,6 @@ func TestClientSecretCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestClientSecretCredential_CreateAuthRequestSuccess(t *testing.T) { @@ -84,7 +79,7 @@ func TestClientSecretCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewClientSecretCredential(tenantID, clientID, secret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -101,7 +96,7 @@ func TestClientSecretCredential_GetTokenInvalidCredentials(t *testing.T) { srv.SetResponse(mock.WithBody([]byte(accessTokenRespError)), mock.WithStatusCode(http.StatusUnauthorized)) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewClientSecretCredential(tenantID, clientID, wrongSecret, &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -110,7 +105,7 @@ func TestClientSecretCredential_GetTokenInvalidCredentials(t *testing.T) { if err == nil { t.Fatalf("Expected an error but did not receive one.") } - var authFailed *AuthenticationFailedError + var authFailed AuthenticationFailedError if !errors.As(err, &authFailed) { t.Fatalf("Expected: AuthenticationFailedError, Received: %T", err) } @@ -125,7 +120,7 @@ func TestClientSecretCredential_GetTokenUnexpectedJSON(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespMalformed))) options := ClientSecretCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewClientSecretCredential(tenantID, clientID, secret, &options) if err != nil { t.Fatalf("Failed to create the credential") diff --git a/sdk/azidentity/default_azure_credential.go b/sdk/azidentity/default_azure_credential.go index de944c71c2a1..51957159c4f2 100644 --- a/sdk/azidentity/default_azure_credential.go +++ b/sdk/azidentity/default_azure_credential.go @@ -4,9 +4,11 @@ package azidentity import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - "github.com/Azure/azure-sdk-for-go/sdk/internal/log" ) const ( @@ -17,39 +19,39 @@ const ( // DefaultAzureCredentialOptions contains options for configuring authentication. These options // may not apply to all credentials in the default chain. type DefaultAzureCredentialOptions struct { + azcore.ClientOptions + // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions + // TenantID identifies the tenant the Azure CLI should authenticate in. + // Defaults to the CLI's default tenant, which is typically the home tenant of the user logged in to the CLI. + TenantID string } -// NewDefaultAzureCredential provides a default ChainedTokenCredential configuration for applications that will be deployed to Azure. The following credential -// types will be tried, in the following order: +// DefaultAzureCredential is a default credential chain for applications that will be deployed to Azure. +// It combines credentials suitable for deployed applications with credentials suitable in local development. +// It attempts to authenticate with each of these credential types, in the following order: // - EnvironmentCredential // - ManagedIdentityCredential // - AzureCLICredential -// Consult the documentation for these credential types for more information on how they attempt authentication. -func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*ChainedTokenCredential, error) { +// Consult the documentation for these credential types for more information on how they authenticate. +type DefaultAzureCredential struct { + chain *ChainedTokenCredential +} + +// NewDefaultAzureCredential creates a default credential chain for applications that will be deployed to Azure. +func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*DefaultAzureCredential, error) { var creds []azcore.TokenCredential errMsg := "" - if options == nil { - options = &DefaultAzureCredentialOptions{} + cp := DefaultAzureCredentialOptions{} + if options != nil { + cp = *options } - envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{AuthorityHost: options.AuthorityHost, - HTTPClient: options.HTTPClient, - Logging: options.Logging, - Retry: options.Retry, - Telemetry: options.Telemetry, + envCred, err := NewEnvironmentCredential(&EnvironmentCredentialOptions{AuthorityHost: cp.AuthorityHost, + ClientOptions: cp.ClientOptions, }) if err == nil { creds = append(creds, envCred) @@ -57,29 +59,33 @@ func NewDefaultAzureCredential(options *DefaultAzureCredentialOptions) (*Chained errMsg += err.Error() } - msiCred, err := NewManagedIdentityCredential(&ManagedIdentityCredentialOptions{HTTPClient: options.HTTPClient, - Logging: options.Logging, - Telemetry: options.Telemetry, - }) + msiCred, err := NewManagedIdentityCredential(&ManagedIdentityCredentialOptions{ClientOptions: cp.ClientOptions}) if err == nil { creds = append(creds, msiCred) } else { errMsg += err.Error() } - cliCred, err := NewAzureCLICredential(nil) + cliCred, err := NewAzureCLICredential(&AzureCLICredentialOptions{TenantID: cp.TenantID}) if err == nil { creds = append(creds, cliCred) } else { errMsg += err.Error() } - // if no credentials are added to the slice of TokenCredentials then return a CredentialUnavailableError if len(creds) == 0 { - err := &CredentialUnavailableError{credentialType: "Default Azure Credential", message: errMsg} - logCredentialError(err.credentialType, err) + err := errors.New(errMsg) + logCredentialError("Default Azure Credential", err) return nil, err } - log.Write(LogCredential, "Azure Identity => NewDefaultAzureCredential() invoking NewChainedTokenCredential()") - return NewChainedTokenCredential(creds, nil) + chain, err := NewChainedTokenCredential(creds, nil) + if err != nil { + return nil, err + } + return &DefaultAzureCredential{chain: chain}, nil +} + +// GetToken attempts to acquire a token from each of the default chain's credentials, stopping when one provides a token. +func (c *DefaultAzureCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (token *azcore.AccessToken, err error) { + return c.chain.GetToken(ctx, opts) } diff --git a/sdk/azidentity/default_azure_credential_test.go b/sdk/azidentity/default_azure_credential_test.go index 8cc5f6a3bd8c..7031a1c8dfed 100644 --- a/sdk/azidentity/default_azure_credential_test.go +++ b/sdk/azidentity/default_azure_credential_test.go @@ -4,38 +4,26 @@ package azidentity import ( - "errors" + "context" "testing" -) -const ( - lengthOfChainOneExcluded = 2 - lengthOfChainFull = 3 + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) -func TestDefaultAzureCredential_NilOptions(t *testing.T) { - resetEnvironmentVarsForTest() - err := initEnvironmentVarsForTest() +func TestDefaultAzureCredential_GetTokenSuccess(t *testing.T) { + env := map[string]string{"AZURE_TENANT_ID": tenantID, "AZURE_CLIENT_ID": clientID, "AZURE_CLIENT_SECRET": secret} + setEnvironmentVariables(t, env) + srv, close := mock.NewTLSServer() + defer close() + srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) + + cred, err := NewDefaultAzureCredential(&DefaultAzureCredentialOptions{AuthorityHost: AuthorityHost(srv.URL()), ClientOptions: policy.ClientOptions{Transport: srv}}) if err != nil { - t.Fatalf("Unexpected error when initializing environment variables: %v", err) + t.Fatalf("Unable to create credential. Received: %v", err) } - cred, err := NewDefaultAzureCredential(nil) + _, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{"scope"}}) if err != nil { - t.Fatalf("Did not expect to receive an error in creating the credential") - } - c := newManagedIdentityClient(&ManagedIdentityCredentialOptions{}) - // if the test is running in a MSI environment then the length of sources would be two since it will include environment credential and managed identity credential - if msiType, err := c.getMSIType(); !(msiType == msiTypeUnavailable || msiType == msiTypeUnknown) { - if len(cred.sources) != lengthOfChainFull { - t.Fatalf("Length of ChainedTokenCredential sources for DefaultAzureCredential. Expected: %d, Received: %d", lengthOfChainFull, len(cred.sources)) - } - //if a credential unavailable error is received or msiType is unknown then only the environment credential will be added - } else if unavailableErr := (*CredentialUnavailableError)(nil); errors.As(err, &unavailableErr) || msiType == msiTypeUnknown { - if len(cred.sources) != lengthOfChainOneExcluded { - t.Fatalf("Length of ChainedTokenCredential sources for DefaultAzureCredential. Expected: %d, Received: %d", lengthOfChainOneExcluded, len(cred.sources)) - } - // if there is some other unexpected error then we fail here - } else if err != nil { - t.Fatalf("Received an error when trying to determine MSI type: %v", err) + t.Fatalf("GetToken error: %v", err) } } diff --git a/sdk/azidentity/device_code_credential.go b/sdk/azidentity/device_code_credential.go index 186ee549df73..90ee87e8766b 100644 --- a/sdk/azidentity/device_code_credential.go +++ b/sdk/azidentity/device_code_credential.go @@ -22,6 +22,8 @@ const ( // All zero-value fields will be initialized with their default values. Please note, that both the TenantID or ClientID fields should // changed together if default values are not desired. type DeviceCodeCredentialOptions struct { + azcore.ClientOptions + // Gets the Azure Active Directory tenant (directory) ID of the service principal // The default value is "organizations". If this value is changed, then also change ClientID to the corresponding value. TenantID string @@ -34,15 +36,6 @@ type DeviceCodeCredentialOptions struct { // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // init provides the default settings for DeviceCodeCredential. @@ -95,13 +88,13 @@ func NewDeviceCodeCredential(options *DeviceCodeCredentialOptions) (*DeviceCodeC } cp.init() if !validTenantID(cp.TenantID) { - return nil, &CredentialUnavailableError{credentialType: "Device Code Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: cp.HTTPClient, Retry: cp.Retry, Telemetry: cp.Telemetry, Logging: cp.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } @@ -139,8 +132,9 @@ func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRe // make initial request to the device code endpoint for a device code and instructions for authentication dc, err := c.client.requestNewDeviceCode(ctx, c.tenantID, c.clientID, opts.Scopes) if err != nil { - addGetTokenFailureLogs("Device Code Credential", err, true) - return nil, err // TODO check what error type to return here + authErr := newAuthenticationFailedError(err, nil) + addGetTokenFailureLogs("Device Code Credential", authErr, true) + return nil, authErr } // send authentication flow instructions back to the user to log in and authorize the device @@ -163,8 +157,8 @@ func (c *DeviceCodeCredential) GetToken(ctx context.Context, opts policy.TokenRe } // if there is an error, check for an AADAuthenticationFailedError in order to check the status for token retrieval // if the error is not an AADAuthenticationFailedError, then fail here since something unexpected occurred - var authFailed *AuthenticationFailedError - if errors.As(err, &authFailed) && strings.Contains(authFailed.msg, "authorization_pending") { + var authFailed AuthenticationFailedError + if errors.As(err, &authFailed) && strings.Contains(authFailed.Error(), "authorization_pending") { // wait for the interval specified from the initial device code endpoint and then poll for the token again time.Sleep(time.Duration(dc.Interval) * time.Second) } else { diff --git a/sdk/azidentity/device_code_credential_test.go b/sdk/azidentity/device_code_credential_test.go index 265a900af389..d0c116b9e9dd 100644 --- a/sdk/azidentity/device_code_credential_test.go +++ b/sdk/azidentity/device_code_credential_test.go @@ -11,6 +11,7 @@ import ( "net/url" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" @@ -34,10 +35,6 @@ func TestDeviceCodeCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestDeviceCodeCredential_CreateAuthRequestSuccess(t *testing.T) { @@ -176,7 +173,7 @@ func TestDeviceCodeCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithStatusCode(http.StatusOK)) options := DeviceCodeCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewDeviceCodeCredential(&options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -197,7 +194,7 @@ func TestDeviceCodeCredential_GetTokenInvalidCredentials(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) cred, err := NewDeviceCodeCredential(&options) if err != nil { @@ -219,7 +216,7 @@ func TestDeviceCodeCredential_GetTokenAuthorizationPending(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) options.UserPrompt = func(context.Context, DeviceCodeMessage) error { return nil } cred, err := NewDeviceCodeCredential(&options) @@ -241,7 +238,7 @@ func TestDeviceCodeCredential_GetTokenExpiredToken(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) options.UserPrompt = func(context.Context, DeviceCodeMessage) error { return nil } cred, err := NewDeviceCodeCredential(&options) @@ -261,7 +258,7 @@ func TestDeviceCodeCredential_GetTokenWithRefreshTokenFailure(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) cred, err := NewDeviceCodeCredential(&options) if err != nil { @@ -272,7 +269,7 @@ func TestDeviceCodeCredential_GetTokenWithRefreshTokenFailure(t *testing.T) { if err == nil { t.Fatalf("Expected an error but did not receive one") } - var authFailed *AuthenticationFailedError + var authFailed AuthenticationFailedError if !errors.As(err, &authFailed) { t.Fatalf("Expected AuthenticationFailedError, got %T", err) } @@ -288,7 +285,7 @@ func TestDeviceCodeCredential_GetTokenWithRefreshTokenSuccess(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) options.UserPrompt = func(context.Context, DeviceCodeMessage) error { return nil } cred, err := NewDeviceCodeCredential(&options) @@ -314,7 +311,7 @@ func TestBearerPolicy_DeviceCodeCredential(t *testing.T) { options := DeviceCodeCredentialOptions{} options.ClientID = clientID options.TenantID = tenantID - options.HTTPClient = srv + options.Transport = srv options.AuthorityHost = AuthorityHost(srv.URL()) options.UserPrompt = func(context.Context, DeviceCodeMessage) error { return nil } cred, err := NewDeviceCodeCredential(&options) @@ -342,9 +339,9 @@ func TestDeviceCodeCredential_UserPrompt(t *testing.T) { key := "key" val := "value" options := DeviceCodeCredentialOptions{ + ClientOptions: azcore.ClientOptions{Transport: srv}, AuthorityHost: AuthorityHost(srv.URL()), ClientID: clientID, - HTTPClient: srv, TenantID: tenantID, UserPrompt: func(ctx context.Context, m DeviceCodeMessage) error { called = true @@ -377,9 +374,9 @@ func TestDeviceCodeCredential_UserPromptError(t *testing.T) { expectedCtx := context.WithValue(context.Background(), "", "") msg := "it worked" options := DeviceCodeCredentialOptions{ + ClientOptions: azcore.ClientOptions{Transport: srv}, AuthorityHost: AuthorityHost(srv.URL()), ClientID: clientID, - HTTPClient: srv, TenantID: tenantID, UserPrompt: func(ctx context.Context, m DeviceCodeMessage) error { if ctx != expectedCtx { diff --git a/sdk/azidentity/environment_credential.go b/sdk/azidentity/environment_credential.go index d8307686e1da..403fb80ebcbc 100644 --- a/sdk/azidentity/environment_credential.go +++ b/sdk/azidentity/environment_credential.go @@ -5,6 +5,8 @@ package azidentity import ( "context" + "errors" + "fmt" "os" "github.com/Azure/azure-sdk-for-go/sdk/azcore" @@ -15,18 +17,11 @@ import ( // EnvironmentCredentialOptions configures the EnvironmentCredential with optional parameters. // All zero-value fields will be initialized with their default values. type EnvironmentCredentialOptions struct { + azcore.ClientOptions + // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // EnvironmentCredential enables authentication to Azure Active Directory using either ClientSecretCredential, ClientCertificateCredential or UsernamePasswordCredential. @@ -47,36 +42,33 @@ type EnvironmentCredential struct { // If the expected environment variables are not found at this time, then a CredentialUnavailableError will be returned. // options: The options used to configure the management of the requests sent to Azure Active Directory. func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*EnvironmentCredential, error) { - if options == nil { - options = &EnvironmentCredentialOptions{} + cp := EnvironmentCredentialOptions{} + if options != nil { + cp = *options } tenantID := os.Getenv("AZURE_TENANT_ID") if tenantID == "" { - err := &CredentialUnavailableError{credentialType: "Environment Credential", message: "Missing environment variable AZURE_TENANT_ID"} - logCredentialError(err.credentialType, err) - return nil, err + return nil, errors.New("Missing environment variable AZURE_TENANT_ID") } clientID := os.Getenv("AZURE_CLIENT_ID") if clientID == "" { - err := &CredentialUnavailableError{credentialType: "Environment Credential", message: "Missing environment variable AZURE_CLIENT_ID"} - logCredentialError(err.credentialType, err) - return nil, err + return nil, errors.New("Missing environment variable AZURE_CLIENT_ID") } if clientSecret := os.Getenv("AZURE_CLIENT_SECRET"); clientSecret != "" { - log.Write(LogCredential, "Azure Identity => NewEnvironmentCredential() invoking ClientSecretCredential") - cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, &ClientSecretCredentialOptions{AuthorityHost: options.AuthorityHost, HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + log.Write(EventCredential, "Azure Identity => NewEnvironmentCredential() invoking ClientSecretCredential") + cred, err := NewClientSecretCredential(tenantID, clientID, clientSecret, &ClientSecretCredentialOptions{AuthorityHost: cp.AuthorityHost, ClientOptions: cp.ClientOptions}) if err != nil { return nil, err } return &EnvironmentCredential{cred: cred}, nil } if certPath := os.Getenv("AZURE_CLIENT_CERTIFICATE_PATH"); certPath != "" { - log.Write(LogCredential, "Azure Identity => NewEnvironmentCredential() invoking ClientCertificateCredential") + log.Write(EventCredential, "Azure Identity => NewEnvironmentCredential() invoking ClientCertificateCredential") certData, err := os.ReadFile(certPath) if err != nil { - return nil, &CredentialUnavailableError{credentialType: "Environment Credential", message: "Failed to read certificate file: " + err.Error()} + return nil, fmt.Errorf("Failed to read certificate file: %v", err) } - cred, err := NewClientCertificateCredential(tenantID, clientID, certData, &ClientCertificateCredentialOptions{AuthorityHost: options.AuthorityHost, HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + cred, err := NewClientCertificateCredential(tenantID, clientID, certData, &ClientCertificateCredentialOptions{AuthorityHost: cp.AuthorityHost, ClientOptions: cp.ClientOptions}) if err != nil { return nil, err } @@ -84,17 +76,15 @@ func NewEnvironmentCredential(options *EnvironmentCredentialOptions) (*Environme } if username := os.Getenv("AZURE_USERNAME"); username != "" { if password := os.Getenv("AZURE_PASSWORD"); password != "" { - log.Write(LogCredential, "Azure Identity => NewEnvironmentCredential() invoking UsernamePasswordCredential") - cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, &UsernamePasswordCredentialOptions{AuthorityHost: options.AuthorityHost, HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + log.Write(EventCredential, "Azure Identity => NewEnvironmentCredential() invoking UsernamePasswordCredential") + cred, err := NewUsernamePasswordCredential(tenantID, clientID, username, password, &UsernamePasswordCredentialOptions{AuthorityHost: cp.AuthorityHost, ClientOptions: cp.ClientOptions}) if err != nil { return nil, err } return &EnvironmentCredential{cred: cred}, nil } } - err := &CredentialUnavailableError{credentialType: "Environment Credential", message: "Missing environment variable AZURE_CLIENT_SECRET or AZURE_CLIENT_CERTIFICATE_PATH or AZURE_USERNAME and AZURE_PASSWORD"} - logCredentialError(err.credentialType, err) - return nil, err + return nil, errors.New("Missing environment variable AZURE_CLIENT_SECRET or AZURE_CLIENT_CERTIFICATE_PATH or AZURE_USERNAME and AZURE_PASSWORD") } // GetToken obtains a token from Azure Active Directory, using the underlying credential's GetToken method. diff --git a/sdk/azidentity/environment_credential_test.go b/sdk/azidentity/environment_credential_test.go index 427665df73d2..9d4caaacb314 100644 --- a/sdk/azidentity/environment_credential_test.go +++ b/sdk/azidentity/environment_credential_test.go @@ -4,7 +4,6 @@ package azidentity import ( - "errors" "os" "testing" ) @@ -43,10 +42,6 @@ func TestEnvironmentCredential_TenantIDNotSet(t *testing.T) { if err == nil { t.Fatalf("Expected an error but received nil") } - var credentialUnavailable *CredentialUnavailableError - if !errors.As(err, &credentialUnavailable) { - t.Fatalf("Expected a credential unavailable error, instead received: %T", err) - } } func TestEnvironmentCredential_ClientIDNotSet(t *testing.T) { @@ -63,10 +58,6 @@ func TestEnvironmentCredential_ClientIDNotSet(t *testing.T) { if err == nil { t.Fatalf("Expected an error but received nil") } - var credentialUnavailable *CredentialUnavailableError - if !errors.As(err, &credentialUnavailable) { - t.Fatalf("Expected a credential unavailable error, instead received: %T", err) - } } func TestEnvironmentCredential_ClientSecretNotSet(t *testing.T) { @@ -83,10 +74,6 @@ func TestEnvironmentCredential_ClientSecretNotSet(t *testing.T) { if err == nil { t.Fatalf("Expected an error but received nil") } - var credentialUnavailable *CredentialUnavailableError - if !errors.As(err, &credentialUnavailable) { - t.Fatalf("Expected a credential unavailable error, instead received: %T", err) - } } func TestEnvironmentCredential_ClientSecretSet(t *testing.T) { @@ -153,10 +140,6 @@ func TestEnvironmentCredential_UsernameOnlySet(t *testing.T) { if err == nil { t.Fatalf("Expected an error but received nil") } - var credentialUnavailable *CredentialUnavailableError - if !errors.As(err, &credentialUnavailable) { - t.Fatalf("Expected a credential unavailable error, instead received: %T", err) - } } func TestEnvironmentCredential_UsernamePasswordSet(t *testing.T) { diff --git a/sdk/azidentity/errors.go b/sdk/azidentity/errors.go new file mode 100644 index 000000000000..9c859fc01c41 --- /dev/null +++ b/sdk/azidentity/errors.go @@ -0,0 +1,79 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azidentity + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/internal/errorinfo" +) + +// AuthenticationFailedError indicates an authentication request has failed. +type AuthenticationFailedError interface { + azcore.HTTPResponse + errorinfo.NonRetriable + AuthenticationFailed() +} + +type authenticationFailedError struct { + error + resp *http.Response +} + +func newAuthenticationFailedError(err error, resp *http.Response) AuthenticationFailedError { + return authenticationFailedError{err, resp} +} + +// NonRetriable indicates that this error should not be retried. +func (authenticationFailedError) NonRetriable() { + // marker method +} + +// AuthenticationFailed indicates that an authentication attempt failed +func (authenticationFailedError) AuthenticationFailed() { + // marker method +} + +// RawResponse returns the HTTP response motivating the error, if available. +func (e authenticationFailedError) RawResponse() *http.Response { + return e.resp +} + +var _ AuthenticationFailedError = (*authenticationFailedError)(nil) +var _ azcore.HTTPResponse = (*authenticationFailedError)(nil) +var _ errorinfo.NonRetriable = (*authenticationFailedError)(nil) + +// CredentialUnavailableError indicates a credential can't attempt authenticate +// because it lacks required data or state. +type CredentialUnavailableError interface { + errorinfo.NonRetriable + CredentialUnavailable() +} + +type credentialUnavailableError struct { + credType string + message string +} + +func newCredentialUnavailableError(credType, message string) CredentialUnavailableError { + return credentialUnavailableError{credType: credType, message: message} +} + +func (e credentialUnavailableError) Error() string { + return e.credType + ": " + e.message +} + +// NonRetriable indicates that this error should not be retried. +func (e credentialUnavailableError) NonRetriable() { + // marker method +} + +// CredentialUnavailable indicates that the credential didn't attempt to authenticate +func (e credentialUnavailableError) CredentialUnavailable() { + // marker method +} + +var _ CredentialUnavailableError = (*credentialUnavailableError)(nil) +var _ errorinfo.NonRetriable = (*credentialUnavailableError)(nil) diff --git a/sdk/azidentity/go.mod b/sdk/azidentity/go.mod index e1e88f7dbb5f..82ded8237f73 100644 --- a/sdk/azidentity/go.mod +++ b/sdk/azidentity/go.mod @@ -1,12 +1,10 @@ module github.com/Azure/azure-sdk-for-go/sdk/azidentity -go 1.14 - -replace github.com/Azure/azure-sdk-for-go/sdk/azcore => ../azcore +go 1.16 require ( - github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 - github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.1 + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0 + github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1 github.com/davecgh/go-spew v1.1.1 // indirect github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4 golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897 diff --git a/sdk/azidentity/go.sum b/sdk/azidentity/go.sum index 891714da0078..4c0862037317 100644 --- a/sdk/azidentity/go.sum +++ b/sdk/azidentity/go.sum @@ -1,5 +1,7 @@ -github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.1 h1:8XSiy/LSvjtFwpguk7m6yGLgGkWocluo8hLM5vtcpcg= -github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.1/go.mod h1:KLF4gFr6DcKFZwSuH8w8yEK6DpFl3LP5rhdvAb7Yz5I= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0 h1:KQgdWmEOmaJKxaUUZwHAYh12t+b+ZJf8q3friycK1kA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0/go.mod h1:ZPW/Z0kLCTdDZaDbYTetxc9Cxl/2lNqxYHYNOF2bti0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1 h1:BUYIbDf/mMZ8945v3QkG3OuqGVyS4Iek0AOLwdRAYoc= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1/go.mod h1:KLF4gFr6DcKFZwSuH8w8yEK6DpFl3LP5rhdvAb7Yz5I= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= @@ -31,7 +33,6 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= diff --git a/sdk/azidentity/interactive_browser_credential.go b/sdk/azidentity/interactive_browser_credential.go index c445c3028293..5c5c00c5e907 100644 --- a/sdk/azidentity/interactive_browser_credential.go +++ b/sdk/azidentity/interactive_browser_credential.go @@ -7,6 +7,7 @@ import ( "context" "crypto/sha256" "encoding/base64" + "errors" "math/rand" "net/url" "path" @@ -24,6 +25,8 @@ import ( // All zero-value fields will be initialized with their default values. Please note, that both the TenantID or ClientID fields should // changed together if default values are not desired. type InteractiveBrowserCredentialOptions struct { + azcore.ClientOptions + // The Azure Active Directory tenant (directory) ID of the application. Defaults to "organizations". TenantID string // The ID of the application the user will sign in to. When not set, users will sign in to an Azure development application. @@ -34,15 +37,6 @@ type InteractiveBrowserCredentialOptions struct { // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // init returns an instance of InteractiveBrowserCredentialOptions initialized with default values. @@ -71,13 +65,13 @@ func NewInteractiveBrowserCredential(options *InteractiveBrowserCredentialOption } cp.init() if !validTenantID(cp.TenantID) { - return nil, &CredentialUnavailableError{credentialType: "Interactive Browser Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: cp.HTTPClient, Retry: cp.Retry, Telemetry: cp.Telemetry, Logging: cp.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } diff --git a/sdk/azidentity/interactive_browser_credential_test.go b/sdk/azidentity/interactive_browser_credential_test.go index 8c996cf72d11..25cf7e146144 100644 --- a/sdk/azidentity/interactive_browser_credential_test.go +++ b/sdk/azidentity/interactive_browser_credential_test.go @@ -24,10 +24,6 @@ func TestInteractiveBrowserCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestInteractiveBrowserCredential_CreateWithNilOptions(t *testing.T) { @@ -58,7 +54,7 @@ func TestInteractiveBrowserCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := InteractiveBrowserCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = client + options.Transport = client cred, err := NewInteractiveBrowserCredential(&options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -90,7 +86,7 @@ func TestInteractiveBrowserCredential_GetTokenInvalidCredentials(t *testing.T) { srv.SetResponse(mock.WithBody([]byte(accessTokenRespError)), mock.WithStatusCode(http.StatusUnauthorized)) options := InteractiveBrowserCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = client + options.Transport = client cred, err := NewInteractiveBrowserCredential(&options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -105,7 +101,7 @@ func TestInteractiveBrowserCredential_GetTokenInvalidCredentials(t *testing.T) { if err == nil { t.Fatalf("Expected an error but did not receive one.") } - var authFailed *AuthenticationFailedError + var authFailed AuthenticationFailedError if !errors.As(err, &authFailed) { t.Fatalf("Expected: AuthenticationFailedError, Received: %T", err) } diff --git a/sdk/azidentity/jwt.go b/sdk/azidentity/jwt.go index 88a815337f05..84f8c93aa1eb 100644 --- a/sdk/azidentity/jwt.go +++ b/sdk/azidentity/jwt.go @@ -48,7 +48,7 @@ func createClientAssertionJWT(clientID string, audience string, cert *certConten headerJSON, err := json.Marshal(headerData) if err != nil { - return "", fmt.Errorf("marshal headerJWT: %w", err) + return "", fmt.Errorf("marshal headerJWT: %v", err) } header := base64.RawURLEncoding.EncodeToString(headerJSON) jti, err := uuid.New() @@ -66,7 +66,7 @@ func createClientAssertionJWT(clientID string, audience string, cert *certConten payloadJSON, err := json.Marshal(payloadData) if err != nil { - return "", fmt.Errorf("marshal payloadJWT: %w", err) + return "", fmt.Errorf("marshal payloadJWT: %v", err) } payload := base64.RawURLEncoding.EncodeToString(payloadJSON) result := header + "." + payload diff --git a/sdk/azidentity/logging.go b/sdk/azidentity/logging.go index 97bf1fb1810d..0003a20d53ca 100644 --- a/sdk/azidentity/logging.go +++ b/sdk/azidentity/logging.go @@ -14,14 +14,14 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/internal/log" ) -// LogCredential entries contain information about authentication. +// EventCredential entries contain information about authentication. // This includes information like the names of environment variables // used when obtaining credentials and the type of credential used. -const LogCredential log.Classification = "Credential" +const EventCredential log.Event = "Credential" // log environment variables that can be used for credential types func logEnvVars() { - if !log.Should(LogCredential) { + if !log.Should(EventCredential) { return } // Log available environment variables @@ -38,29 +38,26 @@ func logEnvVars() { if envCheck := os.Getenv("AZURE_AUTHORITY_HOST"); len(envCheck) > 0 { envVars = append(envVars, "AZURE_AUTHORITY_HOST") } - if envCheck := os.Getenv("AZURE_CLI_PATH"); len(envCheck) > 0 { - envVars = append(envVars, "AZURE_CLI_PATH") - } if len(envVars) > 0 { - log.Writef(LogCredential, "Azure Identity => Found the following environment variables:\n\t%s", strings.Join(envVars, ", ")) + log.Writef(EventCredential, "Azure Identity => Found the following environment variables:\n\t%s", strings.Join(envVars, ", ")) } } func logGetTokenSuccess(cred azcore.TokenCredential, opts policy.TokenRequestOptions) { - if !log.Should(LogCredential) { + if !log.Should(EventCredential) { return } msg := fmt.Sprintf("Azure Identity => GetToken() result for %T: SUCCESS\n", cred) msg += fmt.Sprintf("\tCredential Scopes: [%s]", strings.Join(opts.Scopes, ", ")) - log.Write(LogCredential, msg) + log.Write(EventCredential, msg) } func logCredentialError(credName string, err error) { - log.Writef(LogCredential, "Azure Identity => ERROR in %s: %s", credName, err.Error()) + log.Writef(EventCredential, "Azure Identity => ERROR in %s: %s", credName, err.Error()) } func logMSIEnv(msi msiType) { - if !log.Should(LogCredential) { + if !log.Should(EventCredential) { return } var msg string @@ -74,11 +71,11 @@ func logMSIEnv(msi msiType) { default: msg = "Azure Identity => Managed Identity environment: Unknown" } - log.Write(LogCredential, msg) + log.Write(EventCredential, msg) } func addGetTokenFailureLogs(credName string, err error, includeStack bool) { - if !log.Should(LogCredential) { + if !log.Should(EventCredential) { return } stack := "" @@ -86,5 +83,5 @@ func addGetTokenFailureLogs(credName string, err error, includeStack bool) { // skip the stack trace frames and ourself stack = "\n" + diag.StackTrace(3, 32) } - log.Writef(LogCredential, "Azure Identity => ERROR in GetToken() call for %s: %s%s", credName, err.Error(), stack) + log.Writef(EventCredential, "Azure Identity => ERROR in GetToken() call for %s: %s%s", credName, err.Error(), stack) } diff --git a/sdk/azidentity/managed_identity_client.go b/sdk/azidentity/managed_identity_client.go index 659f94b4bb4c..591a25bc6130 100644 --- a/sdk/azidentity/managed_identity_client.go +++ b/sdk/azidentity/managed_identity_client.go @@ -73,6 +73,48 @@ func (n *wrappedNumber) UnmarshalJSON(b []byte) error { return json.Unmarshal(b, (*json.Number)(n)) } +// setRetryOptionDefaults sets zero-valued fields to default values appropriate for IMDS +func setRetryOptionDefaults(o *policy.RetryOptions) { + if o.MaxRetries == 0 { + o.MaxRetries = 5 + } + if o.MaxRetryDelay == 0 { + o.MaxRetryDelay = 1 * time.Minute + } + if o.RetryDelay == 0 { + o.RetryDelay = 2 * time.Second + } + if o.StatusCodes == nil { + o.StatusCodes = []int{ + // IMDS docs recommend retrying 404, 429 and all 5xx + // https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#error-handling + http.StatusNotFound, // 404 + http.StatusTooManyRequests, // 429 + http.StatusInternalServerError, // 500 + http.StatusNotImplemented, // 501 + http.StatusBadGateway, // 502 + http.StatusGatewayTimeout, // 504 + http.StatusHTTPVersionNotSupported, // 505 + http.StatusVariantAlsoNegotiates, // 506 + http.StatusInsufficientStorage, // 507 + http.StatusLoopDetected, // 508 + http.StatusNotExtended, // 510 + http.StatusNetworkAuthenticationRequired, // 511 + } + } + if o.TryTimeout == 0 { + o.TryTimeout = 1 * time.Minute + } +} + +// newDefaultMSIPipeline creates a pipeline using the specified pipeline options needed +// for a Managed Identity, such as a MSI specific retry policy. +func newDefaultMSIPipeline(o ManagedIdentityCredentialOptions) runtime.Pipeline { + cp := o.ClientOptions + setRetryOptionDefaults(&cp.Retry) + return runtime.NewPipeline(component, version, nil, nil, &cp) +} + // newManagedIdentityClient creates a new instance of the ManagedIdentityClient with the ManagedIdentityCredentialOptions // that are passed into it along with a default pipeline. // options: ManagedIdentityCredentialOptions configure policies for the pipeline and the authority host that @@ -94,7 +136,7 @@ func newManagedIdentityClient(options *ManagedIdentityCredentialOptions) *manage // scopes: The scopes required for the token. func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKind, scopes []string) (*azcore.AccessToken, error) { if len(c.unavailableMessage) > 0 { - return nil, &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: c.unavailableMessage} + return nil, newCredentialUnavailableError("Managed Identity Credential", c.unavailableMessage) } msg, err := c.createAuthRequest(ctx, id, scopes) @@ -113,13 +155,13 @@ func (c *managedIdentityClient) authenticate(ctx context.Context, id ManagedIDKi if c.msiType == msiTypeIMDS && resp.StatusCode == 400 { if id != nil { - return nil, &AuthenticationFailedError{msg: "The requested identity isn't assigned to this resource."} + return nil, newAuthenticationFailedError(errors.New("The requested identity isn't assigned to this resource."), resp) } c.unavailableMessage = "No default identity is assigned to this resource." - return nil, &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: c.unavailableMessage} + return nil, newCredentialUnavailableError("Managed Identity Credential", c.unavailableMessage) } - return nil, &AuthenticationFailedError{resp: resp, msg: "authentication failed"} + return nil, newAuthenticationFailedError(errors.New("authentication failed"), resp) } func (c *managedIdentityClient) createAccessToken(res *http.Response) (*azcore.AccessToken, error) { @@ -131,7 +173,7 @@ func (c *managedIdentityClient) createAccessToken(res *http.Response) (*azcore.A ExpiresOn interface{} `json:"expires_on,omitempty"` // the value returned in this field varies between a number and a date string }{} if err := runtime.UnmarshalAsJSON(res, &value); err != nil { - return nil, fmt.Errorf("internal AccessToken: %w", err) + return nil, fmt.Errorf("internal AccessToken: %v", err) } if value.ExpiresIn != "" { expiresIn, err := json.Number(value.ExpiresIn).Int64() @@ -159,7 +201,8 @@ func (c *managedIdentityClient) createAccessToken(res *http.Response) (*azcore.A return nil, err } default: - return nil, &AuthenticationFailedError{msg: fmt.Sprintf("unsupported type received in expires_on: %T, %v", v, v)} + err := fmt.Errorf("unsupported type received in expires_on: %T, %v", v, v) + return nil, newAuthenticationFailedError(err, res) } } @@ -173,7 +216,8 @@ func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id Manage // need to perform preliminary request to retreive the secret key challenge provided by the HIMDS service key, err := c.getAzureArcSecretKey(ctx, scopes) if err != nil { - return nil, &AuthenticationFailedError{msg: "failed to retreive secret key from the identity endpoint"} + msg := fmt.Errorf("failed to retreive secret key from the identity endpoint: %v", err) + return nil, newAuthenticationFailedError(msg, nil) } return c.createAzureArcAuthRequest(ctx, key, scopes) case msiTypeServiceFabric: @@ -189,7 +233,7 @@ func (c *managedIdentityClient) createAuthRequest(ctx context.Context, id Manage errorMsg = "unknown" } c.unavailableMessage = "managed identity support is " + errorMsg - return nil, &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: c.unavailableMessage} + return nil, newCredentialUnavailableError("Managed Identity Credential", c.unavailableMessage) } } @@ -284,7 +328,8 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour // the endpoint is expected to return a 401 with the WWW-Authenticate header set to the location // of the secret key file. Any other status code indicates an error in the request. if response.StatusCode != 401 { - return "", &AuthenticationFailedError{resp: response, msg: fmt.Sprintf("expected a 401 response, received %d", response.StatusCode)} + err := fmt.Errorf("expected a 401 response, received %d", response.StatusCode) + return "", newAuthenticationFailedError(err, response) } header := response.Header.Get("WWW-Authenticate") if len(header) == 0 { @@ -297,7 +342,7 @@ func (c *managedIdentityClient) getAzureArcSecretKey(ctx context.Context, resour } key, err := ioutil.ReadFile(header[pos+1:]) if err != nil { - return "", fmt.Errorf("could not read file (%s) contents: %w", header[pos+1:], err) + return "", fmt.Errorf("could not read file (%s) contents: %v", header[pos+1:], err) } return string(key), nil } @@ -355,14 +400,14 @@ func (c *managedIdentityClient) getMSIType() (msiType, error) { c.msiType = msiTypeAzureArc } else { c.msiType = msiTypeUnavailable - return c.msiType, &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: "this environment is not supported yet"} + return c.msiType, newCredentialUnavailableError("Managed Identity Credential", "this environment is not supported") } } else if c.imdsAvailable() { // if MSI_ENDPOINT is NOT set AND the IMDS endpoint is available the msiType is IMDS. This will timeout after 500 milliseconds c.endpoint = imdsEndpoint c.msiType = msiTypeIMDS } else { // if MSI_ENDPOINT is NOT set and IMDS endpoint is not available Managed Identity is not available c.msiType = msiTypeUnavailable - return c.msiType, &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: "no managed identity endpoint is available"} + return c.msiType, newCredentialUnavailableError("Managed Identity Credential", "no managed identity endpoint is available") } } return c.msiType, nil diff --git a/sdk/azidentity/managed_identity_client_test.go b/sdk/azidentity/managed_identity_client_test.go index dd46a9145fa5..2ff84dff8319 100644 --- a/sdk/azidentity/managed_identity_client_test.go +++ b/sdk/azidentity/managed_identity_client_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) @@ -25,9 +26,7 @@ func TestMSITelemetryDefaultUserAgent(t *testing.T) { srv, close := mock.NewServer() defer close() srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) - options := ManagedIdentityCredentialOptions{ - HTTPClient: srv, - } + options := ManagedIdentityCredentialOptions{ClientOptions: azcore.ClientOptions{Transport: srv}} pipeline := newDefaultMSIPipeline(options) req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL()) if err != nil { @@ -50,9 +49,7 @@ func TestMSITelemetryCustom(t *testing.T) { srv, close := mock.NewServer() defer close() srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) - options := ManagedIdentityCredentialOptions{ - HTTPClient: srv, - } + options := ManagedIdentityCredentialOptions{ClientOptions: azcore.ClientOptions{Transport: srv}} options.Telemetry.ApplicationID = customTelemetry pipeline := newDefaultMSIPipeline(options) req, err := runtime.NewRequest(context.Background(), http.MethodGet, srv.URL()) diff --git a/sdk/azidentity/managed_identity_credential.go b/sdk/azidentity/managed_identity_credential.go index 2a91e15e5baf..0619c49d922e 100644 --- a/sdk/azidentity/managed_identity_credential.go +++ b/sdk/azidentity/managed_identity_credential.go @@ -5,8 +5,8 @@ package azidentity import ( "context" + "errors" "fmt" - "os" "strings" "github.com/Azure/azure-sdk-for-go/sdk/azcore" @@ -53,20 +53,12 @@ func (r ResourceID) String() string { // ManagedIdentityCredentialOptions contains parameters that can be used to configure the pipeline used with Managed Identity Credential. // All zero-value fields will be initialized with their default values. type ManagedIdentityCredentialOptions struct { + azcore.ClientOptions + // ID is the ID of a managed identity the credential should authenticate. Set this field to use a specific identity // instead of the hosting environment's default. The value may be the identity's client ID or resource ID, but note that // some platforms don't accept resource IDs. ID ManagedIDKind - - // HTTPClient sets the transport for making HTTP requests. - // Leave this as nil to use the default HTTP transport. - HTTPClient policy.Transporter - - // Telemetry configures the built-in telemetry policy behavior. - Telemetry policy.TelemetryOptions - - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // ManagedIdentityCredential attempts authentication using a managed identity that has been assigned to the deployment environment. This authentication type works in several @@ -83,33 +75,20 @@ type ManagedIdentityCredential struct { // options: ManagedIdentityCredentialOptions that configure the pipeline for requests sent to Azure Active Directory. func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*ManagedIdentityCredential, error) { // Create a new Managed Identity Client with default options - if options == nil { - options = &ManagedIdentityCredentialOptions{} + cp := ManagedIdentityCredentialOptions{} + if options != nil { + cp = *options } - client := newManagedIdentityClient(options) + client := newManagedIdentityClient(&cp) msiType, err := client.getMSIType() // If there is an error that means that the code is not running in a Managed Identity environment if err != nil { - credErr := &CredentialUnavailableError{credentialType: "Managed Identity Credential", message: "Please make sure you are running in a managed identity environment, such as a VM, Azure Functions, Cloud Shell, etc..."} - logCredentialError(credErr.credentialType, credErr) - return nil, credErr + logCredentialError("Managed Identity Credential", err) + return nil, err } // Assign the msiType discovered onto the client client.msiType = msiType - // check if no clientID is specified then check if it exists in an environment variable - id := options.ID - if id == nil { - cID := os.Getenv("AZURE_CLIENT_ID") - if cID != "" { - id = ClientID(cID) - } else { - rID := os.Getenv("AZURE_RESOURCE_ID") - if rID != "" { - id = ResourceID(rID) - } - } - } - return &ManagedIdentityCredential{id: id, client: client}, nil + return &ManagedIdentityCredential{id: cp.ID, client: client}, nil } // GetToken obtains an AccessToken from the Managed Identity service if available. @@ -117,12 +96,12 @@ func NewManagedIdentityCredential(options *ManagedIdentityCredentialOptions) (*M // Returns an AccessToken which can be used to authenticate service client calls. func (c *ManagedIdentityCredential) GetToken(ctx context.Context, opts policy.TokenRequestOptions) (*azcore.AccessToken, error) { if opts.Scopes == nil { - err := &AuthenticationFailedError{msg: "must specify a resource in order to authenticate"} + err := errors.New("must specify a resource in order to authenticate") addGetTokenFailureLogs("Managed Identity Credential", err, true) return nil, err } if len(opts.Scopes) != 1 { - err := &AuthenticationFailedError{msg: "can only specify one resource to authenticate with ManagedIdentityCredential"} + err := errors.New("can only specify one resource to authenticate with ManagedIdentityCredential") addGetTokenFailureLogs("Managed Identity Credential", err, true) return nil, err } diff --git a/sdk/azidentity/managed_identity_credential_test.go b/sdk/azidentity/managed_identity_credential_test.go index fe3c4dcdb3ce..bfb57fc2ea5b 100644 --- a/sdk/azidentity/managed_identity_credential_test.go +++ b/sdk/azidentity/managed_identity_credential_test.go @@ -14,6 +14,7 @@ import ( "strings" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" @@ -88,7 +89,7 @@ func TestManagedIdentityCredential_GetTokenInCloudShellMock(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -107,7 +108,7 @@ func TestManagedIdentityCredential_GetTokenInCloudShellMockFail(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -127,7 +128,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20170901Mock_windows(t * _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -153,7 +154,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20170901Mock_linux(t *te _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -179,7 +180,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20190801Mock_windows(t * _ = os.Setenv("IDENTITY_HEADER", "header") defer clearEnvVars("IDENTITY_ENDPOINT", "IDENTITY_HEADER") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -205,7 +206,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceV20190801Mock_linux(t *te _ = os.Setenv("IDENTITY_HEADER", "header") defer clearEnvVars("IDENTITY_ENDPOINT", "IDENTITY_HEADER") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -235,9 +236,7 @@ func TestManagedIdentityCredential_GetTokenInAzureFunctions_linux(t *testing.T) _ = os.Setenv("IDENTITY_ENDPOINT", srv.URL()) _ = os.Setenv("IDENTITY_HEADER", "header") defer clearEnvVars("IDENTITY_ENDPOINT", "IDENTITY_HEADER") - msiCred, err := NewManagedIdentityCredential(&ManagedIdentityCredentialOptions{ - HTTPClient: srv, - }) + msiCred, err := NewManagedIdentityCredential(&ManagedIdentityCredentialOptions{ClientOptions: azcore.ClientOptions{Transport: srv}}) if err != nil { t.Fatalf("unexpected error: %v", err) } @@ -328,7 +327,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnStringInt(t *testin _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -348,7 +347,7 @@ func TestManagedIdentityCredential_GetTokenInAppServiceMockFail(t *testing.T) { _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -368,14 +367,14 @@ func TestManagedIdentityCredential_GetTokenIMDS400(t *testing.T) { Body: io.NopCloser(bytes.NewBufferString("")), } res2 := res1 - options.HTTPClient = newMockImds(res1, res2) + options.Transport = newMockImds(res1, res2) cred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) } // cred should return CredentialUnavailableError when IMDS responds 400 to a token request. // Also, it shouldn't send another token request (mockIMDS will appropriately panic if it does). - var expected *CredentialUnavailableError + var expected CredentialUnavailableError for i := 0; i < 3; i++ { _, err = cred.GetToken(context.Background(), policy.TokenRequestOptions{Scopes: []string{msiScope}}) if !errors.As(err, &expected) { @@ -392,7 +391,7 @@ func TestManagedIdentityCredential_NewManagedIdentityCredentialFail(t *testing.T _ = os.Setenv("MSI_ENDPOINT", "https://t .com") defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv cred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatal(err) @@ -411,7 +410,7 @@ func TestBearerPolicy_ManagedIdentityCredential(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv cred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -435,7 +434,7 @@ func TestManagedIdentityCredential_GetTokenUnexpectedJSON(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -496,7 +495,7 @@ func TestManagedIdentityCredential_GetTokenEnvVar(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -518,7 +517,7 @@ func TestManagedIdentityCredential_GetTokenNilResource(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -539,9 +538,7 @@ func TestManagedIdentityCredential_ScopesImmutable(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(expiresOnIntResp))) _ = os.Setenv(msiEndpoint, srv.URL()) defer clearEnvVars(msiEndpoint) - options := ManagedIdentityCredentialOptions{ - HTTPClient: srv, - } + options := ManagedIdentityCredentialOptions{ClientOptions: azcore.ClientOptions{Transport: srv}} cred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -565,7 +562,7 @@ func TestManagedIdentityCredential_GetTokenMultipleResources(t *testing.T) { _ = os.Setenv("MSI_ENDPOINT", srv.URL()) defer clearEnvVars("MSI_ENDPOINT") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -588,7 +585,7 @@ func TestManagedIdentityCredential_UseResourceID(t *testing.T) { _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv options.ID = ResourceID("sample/resource/id") cred, err := NewManagedIdentityCredential(&options) if err != nil { @@ -676,7 +673,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnInt(t *testing.T) { _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -697,7 +694,7 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnFail(t *testing.T) _ = os.Setenv("MSI_SECRET", "secret") defer clearEnvVars("MSI_ENDPOINT", "MSI_SECRET") options := ManagedIdentityCredentialOptions{} - options.HTTPClient = srv + options.Transport = srv msiCred, err := NewManagedIdentityCredential(&options) if err != nil { t.Fatalf("unexpected error: %v", err) @@ -707,34 +704,3 @@ func TestManagedIdentityCredential_CreateAccessTokenExpiresOnFail(t *testing.T) t.Fatalf("expected to receive an error but received none") } } - -func TestManagedIdentityCredential_ResourceID_envVar(t *testing.T) { - // setting a dummy value for IDENTITY_ENDPOINT in order to be able to get a ManagedIdentityCredential type - _ = os.Setenv("IDENTITY_ENDPOINT", "somevalue") - _ = os.Setenv("IDENTITY_HEADER", "header") - _ = os.Setenv("AZURE_RESOURCE_ID", "resource_id") - defer clearEnvVars("IDENTITY_ENDPOINT", "IDENTITY_HEADER", "AZURE_CLIENT_ID", "AZURE_RESOURCE_ID") - cred, err := NewManagedIdentityCredential(nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if cred.id != ResourceID("resource_id") { - t.Fatal("unexpected id value stored") - } - _ = os.Setenv("AZURE_RESOURCE_ID", "") - _ = os.Setenv("AZURE_CLIENT_ID", "client_id") - cred, err = NewManagedIdentityCredential(nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if cred.id != ClientID("client_id") { - t.Fatal("unexpected id value stored") - } - cred, err = NewManagedIdentityCredential(nil) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - if cred.id != ClientID("client_id") { - t.Fatal("unexpected id value stored") - } -} diff --git a/sdk/azidentity/username_password_credential.go b/sdk/azidentity/username_password_credential.go index 0be941e9e21f..b0f526c9073e 100644 --- a/sdk/azidentity/username_password_credential.go +++ b/sdk/azidentity/username_password_credential.go @@ -5,27 +5,21 @@ package azidentity import ( "context" + "errors" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" ) // UsernamePasswordCredentialOptions can be used to provide additional information to configure the UsernamePasswordCredential. -// Use these options to modify the default pipeline behavior through the TokenCredentialOptions. +// Use these options to modify the default pipeline behavior through the TokenCredentialcp. // All zero-value fields will be initialized with their default values. type UsernamePasswordCredentialOptions struct { + azcore.ClientOptions + // The host of the Azure Active Directory authority. The default is AzurePublicCloud. // Leave empty to allow overriding the value from the AZURE_AUTHORITY_HOST environment variable. AuthorityHost AuthorityHost - // HTTPClient sets the transport for making HTTP requests - // Leave this as nil to use the default HTTP transport - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions } // UsernamePasswordCredential enables authentication to Azure Active Directory using a user's username and password. If the user has MFA enabled this @@ -48,16 +42,17 @@ type UsernamePasswordCredential struct { // options: UsernamePasswordCredentialOptions used to configure the pipeline for the requests sent to Azure Active Directory. func NewUsernamePasswordCredential(tenantID string, clientID string, username string, password string, options *UsernamePasswordCredentialOptions) (*UsernamePasswordCredential, error) { if !validTenantID(tenantID) { - return nil, &CredentialUnavailableError{credentialType: "Username Password Credential", message: tenantIDValidationErr} + return nil, errors.New(tenantIDValidationErr) } - if options == nil { - options = &UsernamePasswordCredentialOptions{} + cp := UsernamePasswordCredentialOptions{} + if options != nil { + cp = *options } - authorityHost, err := setAuthorityHost(options.AuthorityHost) + authorityHost, err := setAuthorityHost(cp.AuthorityHost) if err != nil { return nil, err } - c, err := newAADIdentityClient(authorityHost, pipelineOptions{HTTPClient: options.HTTPClient, Retry: options.Retry, Telemetry: options.Telemetry, Logging: options.Logging}) + c, err := newAADIdentityClient(authorityHost, &cp.ClientOptions) if err != nil { return nil, err } diff --git a/sdk/azidentity/username_password_credential_test.go b/sdk/azidentity/username_password_credential_test.go index 0c600a9dcd7b..501100175db1 100644 --- a/sdk/azidentity/username_password_credential_test.go +++ b/sdk/azidentity/username_password_credential_test.go @@ -5,7 +5,6 @@ package azidentity import ( "context" - "errors" "io/ioutil" "net/http" "net/url" @@ -24,10 +23,6 @@ func TestUsernamePasswordCredential_InvalidTenantID(t *testing.T) { if cred != nil { t.Fatalf("Expected a nil credential value. Received: %v", cred) } - var errType *CredentialUnavailableError - if !errors.As(err, &errType) { - t.Fatalf("Did not receive a CredentialUnavailableError. Received: %t", err) - } } func TestUsernamePasswordCredential_CreateAuthRequestSuccess(t *testing.T) { @@ -83,7 +78,7 @@ func TestUsernamePasswordCredential_GetTokenSuccess(t *testing.T) { srv.AppendResponse(mock.WithBody([]byte(accessTokenRespSuccess))) options := UsernamePasswordCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewUsernamePasswordCredential(tenantID, clientID, "username", "password", &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -100,7 +95,7 @@ func TestUsernamePasswordCredential_GetTokenInvalidCredentials(t *testing.T) { srv.SetResponse(mock.WithStatusCode(http.StatusUnauthorized)) options := UsernamePasswordCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewUsernamePasswordCredential(tenantID, clientID, "username", "wrong_password", &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) @@ -118,7 +113,7 @@ func TestBearerPolicy_UsernamePasswordCredential(t *testing.T) { srv.AppendResponse(mock.WithStatusCode(http.StatusOK)) options := UsernamePasswordCredentialOptions{} options.AuthorityHost = AuthorityHost(srv.URL()) - options.HTTPClient = srv + options.Transport = srv cred, err := NewUsernamePasswordCredential(tenantID, clientID, "username", "password", &options) if err != nil { t.Fatalf("Unable to create credential. Received: %v", err) diff --git a/sdk/data/azcosmos/README.md b/sdk/data/azcosmos/README.md index 2acd29a1c526..055b43c12d6a 100644 --- a/sdk/data/azcosmos/README.md +++ b/sdk/data/azcosmos/README.md @@ -78,9 +78,8 @@ properties := azcosmos.ContainerProperties{ } throughput := azcosmos.NewManualThroughputProperties(400) -response, err := database.CreateContainer(context, properties, &CreateContainerOptions{ThroughputProperties: throughput}) +response, err := database.CreateContainer(context, properties, &CreateContainerOptions{ThroughputProperties: &throughput}) handle(err) -container := resp.ContainerProperties.Container ``` ### CRUD operation on Items @@ -92,21 +91,21 @@ item := map[string]string{ } // Create partition key -container := client.GetContainer(dbName, containerName) -pk, err := azcosmos.NewPartitionKey("1") +container, err := client.NewContainer(dbName, containerName) handle(err) +pk := azcosmos.NewPartitionKeyString("1") // Create an item -itemResponse, err := container.CreateItem(context, &pk, item, nil) +itemResponse, err := container.CreateItem(context, pk, item, nil) handle(err) -itemResponse, err = container.ReadItem(context, &pk, "1", nil) +itemResponse, err = container.ReadItem(context, pk, "1", nil) handle(err) -itemResponse, err = container.ReplaceItem(context, &pk, "1", item, nil) +itemResponse, err = container.ReplaceItem(context, pk, "1", item, nil) handle(err) -itemResponse, err = container.DeleteItem(context, &pk, "1", nil) +itemResponse, err = container.DeleteItem(context, pk, "1", nil) handle(err) ``` diff --git a/sdk/data/azcosmos/async_cache_test.go b/sdk/data/azcosmos/async_cache_test.go index 6b68f8bf63cf..69e26ec5b553 100644 --- a/sdk/data/azcosmos/async_cache_test.go +++ b/sdk/data/azcosmos/async_cache_test.go @@ -14,19 +14,19 @@ import ( func Test_set(t *testing.T) { key := "someKey" - expectedValue := ContainerProperties{Id: "someId"} + expectedValue := ContainerProperties{ID: "someId"} cache := newAsyncCache() cache.setValue(key, expectedValue) value, _ := cache.getValue(key) containerProps, _ := value.(ContainerProperties) - assert.Equal(t, expectedValue.Id, containerProps.Id) + assert.Equal(t, expectedValue.ID, containerProps.ID) } func Test_setAsync(t *testing.T) { key := "someKeyAsync" - expectedValue := ContainerProperties{Id: "someIdAsync"} + expectedValue := ContainerProperties{ID: "someIdAsync"} cache := newAsyncCache() @@ -38,13 +38,13 @@ func Test_setAsync(t *testing.T) { _ = cache.set(key, f, context.Background()) value, _ := cache.getValue(key) containerProps, _ := value.(ContainerProperties) - assert.Equal(t, expectedValue.Id, containerProps.Id) + assert.Equal(t, expectedValue.ID, containerProps.ID) } func Test_getAsync_not_obsolete(t *testing.T) { key := "testAsyncKey" - expectedValue0 := ContainerProperties{Id: "0"} - expectedValue1 := ContainerProperties{Id: "1"} + expectedValue0 := ContainerProperties{ID: "0"} + expectedValue1 := ContainerProperties{ID: "1"} f1Called := false f2Called := false @@ -80,17 +80,17 @@ func Test_getAsync_not_obsolete(t *testing.T) { assert.False(t, f2Called) containerProps, _ := value.(ContainerProperties) - assert.Equal(t, expectedValue1.Id, containerProps.Id) + assert.Equal(t, expectedValue1.ID, containerProps.ID) containerProps2, _ := value2.(ContainerProperties) - assert.Equal(t, expectedValue1.Id, containerProps2.Id) + assert.Equal(t, expectedValue1.ID, containerProps2.ID) } func Test_getAsync_obsolete(t *testing.T) { key := "testAsyncObsoleteKey" - expectedValue0 := ContainerProperties{Id: "0"} - expectedValue1 := ContainerProperties{Id: "1"} - expectedValue2 := ContainerProperties{Id: "2"} + expectedValue0 := ContainerProperties{ID: "0"} + expectedValue1 := ContainerProperties{ID: "1"} + expectedValue2 := ContainerProperties{ID: "2"} f1Called := false f2Called := false @@ -127,15 +127,15 @@ func Test_getAsync_obsolete(t *testing.T) { assert.True(t, f1Called) assert.True(t, f2Called) - assert.Equal(t, expectedValue2.Id, containerProps.Id) - assert.Equal(t, expectedValue2.Id, containerProps2.Id) + assert.Equal(t, expectedValue2.ID, containerProps.ID) + assert.Equal(t, expectedValue2.ID, containerProps2.ID) } func Test_getAsync_obsolete_with_error(t *testing.T) { key := "testAsyncObsoleteKey" - expectedValue0 := ContainerProperties{Id: "0"} - expectedValue1 := ContainerProperties{Id: "1"} - expectedValue2 := ContainerProperties{Id: "2"} + expectedValue0 := ContainerProperties{ID: "0"} + expectedValue1 := ContainerProperties{ID: "1"} + expectedValue2 := ContainerProperties{ID: "2"} f1Called := false f2Called := false @@ -176,9 +176,9 @@ func Test_getAsync_obsolete_with_error(t *testing.T) { func Test_getAsync_obsolete_with_context_error(t *testing.T) { key := "testAsyncObsoleteKey" - expectedValue0 := ContainerProperties{Id: "0"} - expectedValue1 := ContainerProperties{Id: "1"} - expectedValue2 := ContainerProperties{Id: "2"} + expectedValue0 := ContainerProperties{ID: "0"} + expectedValue1 := ContainerProperties{ID: "1"} + expectedValue2 := ContainerProperties{ID: "2"} f1Called := false f2Called := false @@ -221,14 +221,14 @@ func Test_getAsync_obsolete_with_context_error(t *testing.T) { func Test_remove(t *testing.T) { key := "someKeyToRemove" - expectedValue := ContainerProperties{Id: "someIdToRemove"} + expectedValue := ContainerProperties{ID: "someIdToRemove"} cache := newAsyncCache() cache.setValue(key, expectedValue) value, _ := cache.getValue(key) containerProps, _ := value.(ContainerProperties) - assert.Equal(t, expectedValue.Id, containerProps.Id) + assert.Equal(t, expectedValue.ID, containerProps.ID) cache.remove(key) @@ -239,21 +239,21 @@ func Test_remove(t *testing.T) { func Test_clear(t *testing.T) { key := "someKeyToClear" - expectedValue := ContainerProperties{Id: "someIdToDelete"} + expectedValue := ContainerProperties{ID: "someIdToDelete"} key2 := "someKeyToClear2" - expectedValue2 := ContainerProperties{Id: "someIdToDelete2"} + expectedValue2 := ContainerProperties{ID: "someIdToDelete2"} cache := newAsyncCache() cache.setValue(key, expectedValue) value, _ := cache.getValue(key) containerProps, _ := value.(ContainerProperties) - assert.Equal(t, expectedValue.Id, containerProps.Id) + assert.Equal(t, expectedValue.ID, containerProps.ID) cache.setValue(key2, expectedValue2) value2, _ := cache.getValue(key2) containerProps2, _ := value2.(ContainerProperties) - assert.Equal(t, expectedValue2.Id, containerProps2.Id) + assert.Equal(t, expectedValue2.ID, containerProps2.ID) cache.clear() diff --git a/sdk/data/azcosmos/cosmos_client.go b/sdk/data/azcosmos/cosmos_client.go index 1794c1da94cf..5668dcecb10d 100644 --- a/sdk/data/azcosmos/cosmos_client.go +++ b/sdk/data/azcosmos/cosmos_client.go @@ -4,16 +4,21 @@ package azcosmos import ( + "bytes" "context" "errors" + "net/http" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/streaming" ) // Cosmos client is used to interact with the Azure Cosmos DB database service. type Client struct { - endpoint string - connection *cosmosClientConnection - cred *KeyCredential - options *CosmosClientOptions + endpoint string + pipeline azruntime.Pipeline } // Endpoint used to create the client. @@ -25,39 +30,53 @@ func (c *Client) Endpoint() string { // endpoint - The cosmos service endpoint to use. // cred - The credential used to authenticate with the cosmos service. // options - Optional Cosmos client options. Pass nil to accept default values. -func NewClientWithKey(endpoint string, cred *KeyCredential, options *CosmosClientOptions) (*Client, error) { +func NewClientWithKey(endpoint string, cred KeyCredential, o *ClientOptions) (*Client, error) { + return &Client{endpoint: endpoint, pipeline: newPipeline(cred, o)}, nil +} + +func newPipeline(cred KeyCredential, options *ClientOptions) azruntime.Pipeline { if options == nil { - options = &CosmosClientOptions{} + options = &ClientOptions{} } - connection := newCosmosClientConnection(endpoint, cred, options) - - return &Client{endpoint: endpoint, connection: connection, cred: cred, options: options}, nil + return azruntime.NewPipeline("azcosmos", serviceLibVersion, + []policy.Policy{ + newSharedKeyCredPolicy(cred), + &headerPolicies{ + enableContentResponseOnWrite: options.EnableContentResponseOnWrite, + }}, + nil, + &options.ClientOptions) } // GetDatabase returns a Database object. // id - The id of the database. -func (c *Client) GetDatabase(id string) (*Database, error) { +func (c *Client) NewDatabase(id string) (DatabaseClient, error) { if id == "" { - return nil, errors.New("id is required") + return DatabaseClient{}, errors.New("id is required") } - return newDatabase(id, c), nil + return newDatabase(id, c) } -// GetContainer returns a Container object. +// NewContainer returns a Container object. // databaseId - The id of the database. // containerId - The id of the container. -func (c *Client) GetContainer(databaseId string, containerId string) (*Container, error) { +func (c *Client) NewContainer(databaseId string, containerId string) (ContainerClient, error) { if databaseId == "" { - return nil, errors.New("databaseId is required") + return ContainerClient{}, errors.New("databaseId is required") } if containerId == "" { - return nil, errors.New("containerId is required") + return ContainerClient{}, errors.New("containerId is required") } - return newDatabase(databaseId, c).GetContainer(containerId) + db, err := newDatabase(databaseId, c) + if err != nil { + return ContainerClient{}, err + } + + return db.NewContainer(containerId) } // CreateDatabase creates a new database. @@ -72,22 +91,16 @@ func (c *Client) CreateDatabase( o = &CreateDatabaseOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeDatabase, - resourceAddress: "", - } + resourceAddress: ""} path, err := generatePathForNameBased(resourceTypeDatabase, "", true) if err != nil { return DatabaseResponse{}, err } - database, err := c.GetDatabase(databaseProperties.Id) - if err != nil { - return DatabaseResponse{}, err - } - - azResponse, err := c.connection.sendPostRequest( + azResponse, err := c.sendPostRequest( path, ctx, databaseProperties, @@ -98,5 +111,185 @@ func (c *Client) CreateDatabase( return DatabaseResponse{}, err } - return newDatabaseResponse(azResponse, database) + return newDatabaseResponse(azResponse) +} + +func (c *Client) sendPostRequest( + path string, + ctx context.Context, + content interface{}, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*http.Response, error) { + req, err := c.createRequest(path, ctx, http.MethodPost, operationContext, requestOptions, requestEnricher) + if err != nil { + return nil, err + } + + err = c.attachContent(content, req) + if err != nil { + return nil, err + } + + return c.executeAndEnsureSuccessResponse(req) +} + +func (c *Client) sendQueryRequest( + path string, + ctx context.Context, + query string, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*http.Response, error) { + req, err := c.createRequest(path, ctx, http.MethodPost, operationContext, requestOptions, requestEnricher) + if err != nil { + return nil, err + } + + type queryBody struct { + Query string `json:"query"` + } + + err = azruntime.MarshalAsJSON(req, queryBody{ + Query: query, + }) + if err != nil { + return nil, err + } + + req.Raw().Header.Add(cosmosHeaderQuery, "True") + // Override content type for query + req.Raw().Header.Set(headerContentType, cosmosHeaderValuesQuery) + + return c.executeAndEnsureSuccessResponse(req) +} + +func (c *Client) sendPutRequest( + path string, + ctx context.Context, + content interface{}, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*http.Response, error) { + req, err := c.createRequest(path, ctx, http.MethodPut, operationContext, requestOptions, requestEnricher) + if err != nil { + return nil, err + } + + err = c.attachContent(content, req) + if err != nil { + return nil, err + } + + return c.executeAndEnsureSuccessResponse(req) +} + +func (c *Client) sendGetRequest( + path string, + ctx context.Context, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*http.Response, error) { + req, err := c.createRequest(path, ctx, http.MethodGet, operationContext, requestOptions, requestEnricher) + if err != nil { + return nil, err + } + + return c.executeAndEnsureSuccessResponse(req) +} + +func (c *Client) sendDeleteRequest( + path string, + ctx context.Context, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*http.Response, error) { + req, err := c.createRequest(path, ctx, http.MethodDelete, operationContext, requestOptions, requestEnricher) + if err != nil { + return nil, err + } + + return c.executeAndEnsureSuccessResponse(req) +} + +func (c *Client) createRequest( + path string, + ctx context.Context, + method string, + operationContext pipelineRequestOptions, + requestOptions cosmosRequestOptions, + requestEnricher func(*policy.Request)) (*policy.Request, error) { + + // todo: endpoint will be set originally by globalendpointmanager + finalURL := c.endpoint + + if path != "" { + finalURL = azruntime.JoinPaths(c.endpoint, path) + } + + req, err := azruntime.NewRequest(ctx, method, finalURL) + if err != nil { + return nil, err + } + + if requestOptions != nil { + headers := requestOptions.toHeaders() + if headers != nil { + for k, v := range *headers { + req.Raw().Header.Set(k, v) + } + } + } + + req.Raw().Header.Set(headerXmsDate, time.Now().UTC().Format(http.TimeFormat)) + req.Raw().Header.Set(headerXmsVersion, "2020-11-05") + + req.SetOperationValue(operationContext) + + if requestEnricher != nil { + requestEnricher(req) + } + + return req, nil +} + +func (c *Client) attachContent(content interface{}, req *policy.Request) error { + var err error + switch v := content.(type) { + case []byte: + // If its a raw byte array, we can just set the body + err = req.SetBody(streaming.NopCloser(bytes.NewReader(v)), "application/json") + default: + // Otherwise, we need to marshal it + err = azruntime.MarshalAsJSON(req, content) + + } + + if err != nil { + return err + } + + return nil +} + +func (c *Client) executeAndEnsureSuccessResponse(request *policy.Request) (*http.Response, error) { + response, err := c.pipeline.Do(request) + if err != nil { + return nil, err + } + + successResponse := (response.StatusCode >= 200 && response.StatusCode < 300) || response.StatusCode == 304 + if successResponse { + return response, nil + } + + return nil, newCosmosError(response) +} + +type pipelineRequestOptions struct { + headerOptionsOverride *headerOptionsOverride + resourceType resourceType + resourceAddress string + isRidBased bool + isWriteOperation bool } diff --git a/sdk/data/azcosmos/cosmos_client_connection.go b/sdk/data/azcosmos/cosmos_client_connection.go deleted file mode 100644 index f1997c873490..000000000000 --- a/sdk/data/azcosmos/cosmos_client_connection.go +++ /dev/null @@ -1,188 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "context" - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" -) - -// cosmosClientConnection maintains a Pipeline for the client. -// The Pipeline is build based on the CosmosClientOptions. -type cosmosClientConnection struct { - endpoint string - Pipeline azruntime.Pipeline -} - -// newConnection creates an instance of the connection type with the specified endpoint. -// Pass nil to accept the default options; this is the same as passing a zero-value options. -func newCosmosClientConnection(endpoint string, cred *KeyCredential, options *CosmosClientOptions) *cosmosClientConnection { - policies := []policy.Policy{ - azruntime.NewTelemetryPolicy("azcosmos", serviceLibVersion, &options.Telemetry), - } - policies = append(policies, options.PerCallPolicies...) - policies = append(policies, azruntime.NewRetryPolicy(&options.Retry)) - policies = append(policies, options.PerRetryPolicies...) - policies = append(policies, options.getSDKInternalPolicies()...) - policies = append(policies, newSharedKeyCredPolicy(cred)) - policies = append(policies, azruntime.NewLogPolicy(&options.Logging)) - return &cosmosClientConnection{endpoint: endpoint, Pipeline: azruntime.NewPipeline(options.HTTPClient, policies...)} -} - -func (c *cosmosClientConnection) sendPostRequest( - path string, - ctx context.Context, - content interface{}, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*http.Response, error) { - req, err := c.createRequest(path, ctx, http.MethodPost, operationContext, requestOptions, requestEnricher) - if err != nil { - return nil, err - } - - err = azruntime.MarshalAsJSON(req, content) - if err != nil { - return nil, err - } - - return c.executeAndEnsureSuccessResponse(req) -} - -func (c *cosmosClientConnection) sendQueryRequest( - path string, - ctx context.Context, - query string, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*http.Response, error) { - req, err := c.createRequest(path, ctx, http.MethodPost, operationContext, requestOptions, requestEnricher) - if err != nil { - return nil, err - } - - type queryBody struct { - Query string `json:"query"` - } - - err = azruntime.MarshalAsJSON(req, queryBody{ - Query: query, - }) - if err != nil { - return nil, err - } - - req.Raw().Header.Add(cosmosHeaderQuery, "True") - // Override content type for query - req.Raw().Header.Set(headerContentType, cosmosHeaderValuesQuery) - - return c.executeAndEnsureSuccessResponse(req) -} - -func (c *cosmosClientConnection) sendPutRequest( - path string, - ctx context.Context, - content interface{}, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*http.Response, error) { - req, err := c.createRequest(path, ctx, http.MethodPut, operationContext, requestOptions, requestEnricher) - if err != nil { - return nil, err - } - - err = azruntime.MarshalAsJSON(req, content) - if err != nil { - return nil, err - } - - return c.executeAndEnsureSuccessResponse(req) -} - -func (c *cosmosClientConnection) sendGetRequest( - path string, - ctx context.Context, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*http.Response, error) { - req, err := c.createRequest(path, ctx, http.MethodGet, operationContext, requestOptions, requestEnricher) - if err != nil { - return nil, err - } - - return c.executeAndEnsureSuccessResponse(req) -} - -func (c *cosmosClientConnection) sendDeleteRequest( - path string, - ctx context.Context, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*http.Response, error) { - req, err := c.createRequest(path, ctx, http.MethodDelete, operationContext, requestOptions, requestEnricher) - if err != nil { - return nil, err - } - - return c.executeAndEnsureSuccessResponse(req) -} - -func (c *cosmosClientConnection) createRequest( - path string, - ctx context.Context, - method string, - operationContext cosmosOperationContext, - requestOptions cosmosRequestOptions, - requestEnricher func(*policy.Request)) (*policy.Request, error) { - - // todo: endpoint will be set originally by globalendpointmanager - finalURL := c.endpoint - - if path != "" { - finalURL = azruntime.JoinPaths(c.endpoint, path) - } - - req, err := azruntime.NewRequest(ctx, method, finalURL) - if err != nil { - return nil, err - } - - if requestOptions != nil { - headers := requestOptions.toHeaders() - if headers != nil { - for k, v := range *headers { - req.Raw().Header.Set(k, v) - } - } - } - - req.Raw().Header.Set(headerXmsDate, time.Now().UTC().Format(http.TimeFormat)) - req.Raw().Header.Set(headerXmsVersion, "2020-11-05") - - req.SetOperationValue(operationContext) - - if requestEnricher != nil { - requestEnricher(req) - } - - return req, nil -} - -func (c *cosmosClientConnection) executeAndEnsureSuccessResponse(request *policy.Request) (*http.Response, error) { - response, err := c.Pipeline.Do(request) - if err != nil { - return nil, err - } - - successResponse := (response.StatusCode >= 200 && response.StatusCode < 300) || response.StatusCode == 304 - if successResponse { - return response, nil - } - - return nil, newCosmosError(response) -} diff --git a/sdk/data/azcosmos/cosmos_client_connection_test.go b/sdk/data/azcosmos/cosmos_client_connection_test.go deleted file mode 100644 index 807aa837eb01..000000000000 --- a/sdk/data/azcosmos/cosmos_client_connection_test.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "context" - "encoding/json" - "net/http" - "testing" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" -) - -func TestEnsureErrorIsGeneratedOnResponse(t *testing.T) { - someError := &cosmosErrorResponse{ - Code: "SomeCode", - } - - jsonString, err := json.Marshal(someError) - if err != nil { - t.Fatal(err) - } - - srv, close := mock.NewTLSServer() - defer close() - srv.SetResponse( - mock.WithBody(jsonString), - mock.WithStatusCode(404)) - - pl := azruntime.NewPipeline(srv) - connection := &cosmosClientConnection{endpoint: srv.URL(), Pipeline: pl} - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDatabase, - resourceAddress: "", - } - _, err = connection.sendGetRequest("/", context.Background(), operationContext, &ReadContainerOptions{}, nil) - if err == nil { - t.Fatal("Expected error") - } - - asError := err.(*cosmosError) - if asError.ErrorCode() != someError.Code { - t.Errorf("Expected %v, but got %v", someError.Code, asError.ErrorCode()) - } - - if err.Error() != asError.Error() { - t.Errorf("Expected %v, but got %v", err.Error(), asError.Error()) - } -} - -func TestEnsureErrorIsNotGeneratedOnResponse(t *testing.T) { - srv, close := mock.NewTLSServer() - defer close() - srv.SetResponse( - mock.WithStatusCode(200)) - - pl := azruntime.NewPipeline(srv) - connection := &cosmosClientConnection{endpoint: srv.URL(), Pipeline: pl} - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDatabase, - resourceAddress: "", - } - _, err := connection.sendGetRequest("/", context.Background(), operationContext, &ReadContainerOptions{}, nil) - if err != nil { - t.Fatal(err) - } -} - -func TestRequestEnricherIsCalled(t *testing.T) { - srv, close := mock.NewTLSServer() - defer close() - srv.SetResponse( - mock.WithStatusCode(200)) - - pl := azruntime.NewPipeline(srv) - connection := &cosmosClientConnection{endpoint: srv.URL(), Pipeline: pl} - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDatabase, - resourceAddress: "", - } - - addHeader := func(r *policy.Request) { - r.Raw().Header.Add("my-header", "12345") - } - - req, err := connection.createRequest("/", context.Background(), http.MethodGet, operationContext, &ReadContainerOptions{}, addHeader) - if err != nil { - t.Fatal(err) - } - - if req.Raw().Header.Get("my-header") != "12345" { - t.Errorf("Expected %v, but got %v", "12345", req.Raw().Header.Get("my-header")) - } -} - -func TestNoOptionsIsCalled(t *testing.T) { - srv, close := mock.NewTLSServer() - defer close() - srv.SetResponse( - mock.WithStatusCode(200)) - - pl := azruntime.NewPipeline(srv) - connection := &cosmosClientConnection{endpoint: srv.URL(), Pipeline: pl} - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDatabase, - resourceAddress: "", - } - - _, err := connection.createRequest("/", context.Background(), http.MethodGet, operationContext, nil, nil) - if err != nil { - t.Fatal(err) - } -} diff --git a/sdk/data/azcosmos/cosmos_client_options.go b/sdk/data/azcosmos/cosmos_client_options.go index 938fc0d945b3..8095f8bc2050 100644 --- a/sdk/data/azcosmos/cosmos_client_options.go +++ b/sdk/data/azcosmos/cosmos_client_options.go @@ -4,53 +4,13 @@ package azcosmos import ( - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) -// CosmosClientOptions defines the options for the Cosmos client. -type CosmosClientOptions struct { - // HTTPClient sets the transport for making HTTP requests. - HTTPClient policy.Transporter - // Retry configures the built-in retry policy behavior. - Retry policy.RetryOptions - // Telemetry configures the built-in telemetry policy behavior. - Telemetry policy.TelemetryOptions - // Logging configures the built-in logging policy behavior. - Logging policy.LogOptions - // PerCallPolicies contains custom policies to inject into the pipeline. - // Each policy is executed once per request. - PerCallPolicies []policy.Policy - // PerRetryPolicies contains custom policies to inject into the pipeline. - // Each policy is executed once per request, and for each retry request. - PerRetryPolicies []policy.Policy - // ApplicationPreferredRegions defines list of preferred regions for the client to connect to. - ApplicationPreferredRegions *[]string - // ConsistencyLevel can be used to weaken the database account consistency level for read operations. If this is not set the database account consistency level will be used for all requests. - ConsistencyLevel ConsistencyLevel +// ClientOptions defines the options for the Cosmos client. +type ClientOptions struct { + azcore.ClientOptions // When EnableContentResponseOnWrite is false will cause the response to have a null resource. This reduces networking and CPU load by not sending the resource back over the network and serializing it on the client. // The default is false. EnableContentResponseOnWrite bool - // LimitToEndpoint limits the operations to the provided endpoint on the Cosmos client. See https://docs.microsoft.com/azure/cosmos-db/troubleshoot-sdk-availability - LimitToEndpoint bool - // RateLimitedRetry defines the retry configuration for rate limited requests. - // By default, the SDK will do 9 retries. - RateLimitedRetry *CosmosClientOptionsRateLimitedRetry -} - -type CosmosClientOptionsRateLimitedRetry struct { - // MaxRetryAttempts specifies the number of retries to perform on rate limited requests. - MaxRetryAttempts int - // MaxRetryWaitTime specifies the maximum time to wait for retries. - MaxRetryWaitTime time.Duration -} - -// getSDKInternalPolicies builds a list of internal retry policies for the cosmos service. -// This includes throttling and failover policies. -func (o *CosmosClientOptions) getSDKInternalPolicies() []policy.Policy { - return []policy.Policy{ - newResourceThrottleRetryPolicy(o), - // TODO: Add more policies here. - } } diff --git a/sdk/data/azcosmos/cosmos_client_options_test.go b/sdk/data/azcosmos/cosmos_client_options_test.go deleted file mode 100644 index 7f6ce471dbe1..000000000000 --- a/sdk/data/azcosmos/cosmos_client_options_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "testing" -) - -func TestGetSDKInternalPolicies(t *testing.T) { - cosmosClientOptions := &CosmosClientOptions{} - policies := cosmosClientOptions.getSDKInternalPolicies() - if policies == nil { - t.Error("Expected policies to be not nil") - } - - if len(policies) == 0 { - t.Error("Expected policies to have more than 0 items ") - } -} - -func Test_newCosmosClientConnection(t *testing.T) { - cred, _ := NewKeyCredential("someKey") - connection := newCosmosClientConnection("https://test.com", cred, &CosmosClientOptions{}) - if connection == nil { - t.Error("Expected connection to be not nil") - } -} diff --git a/sdk/data/azcosmos/cosmos_client_test.go b/sdk/data/azcosmos/cosmos_client_test.go new file mode 100644 index 000000000000..a73ea5af7059 --- /dev/null +++ b/sdk/data/azcosmos/cosmos_client_test.go @@ -0,0 +1,371 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcosmos + +import ( + "context" + "encoding/json" + "io/ioutil" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" +) + +func TestEnsureErrorIsGeneratedOnResponse(t *testing.T) { + someError := &cosmosErrorResponse{ + Code: "SomeCode", + } + + jsonString, err := json.Marshal(someError) + if err != nil { + t.Fatal(err) + } + + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithBody(jsonString), + mock.WithStatusCode(404)) + + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + _, err = client.sendGetRequest("/", context.Background(), operationContext, &ReadContainerOptions{}, nil) + if err == nil { + t.Fatal("Expected error") + } + + asError := err.(*cosmosError) + if asError.ErrorCode() != someError.Code { + t.Errorf("Expected %v, but got %v", someError.Code, asError.ErrorCode()) + } + + if err.Error() != asError.Error() { + t.Errorf("Expected %v, but got %v", err.Error(), asError.Error()) + } +} + +func TestEnsureErrorIsNotGeneratedOnResponse(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + _, err := client.sendGetRequest("/", context.Background(), operationContext, &ReadContainerOptions{}, nil) + if err != nil { + t.Fatal(err) + } +} + +func TestRequestEnricherIsCalled(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + addHeader := func(r *policy.Request) { + r.Raw().Header.Add("my-header", "12345") + } + + req, err := client.createRequest("/", context.Background(), http.MethodGet, operationContext, &ReadContainerOptions{}, addHeader) + if err != nil { + t.Fatal(err) + } + + if req.Raw().Header.Get("my-header") != "12345" { + t.Errorf("Expected %v, but got %v", "12345", req.Raw().Header.Get("my-header")) + } +} + +func TestNoOptionsIsCalled(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + _, err := client.createRequest("/", context.Background(), http.MethodGet, operationContext, nil, nil) + if err != nil { + t.Fatal(err) + } +} + +func TestAttachContent(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + body := map[string]string{ + "foo": "bar", + } + + marshalled, _ := json.Marshal(body) + + // Using the interface{} + req, err := client.createRequest("/", context.Background(), http.MethodGet, operationContext, nil, nil) + if err != nil { + t.Fatal(err) + } + + err = client.attachContent(body, req) + if err != nil { + t.Fatal(err) + } + + readBody, _ := ioutil.ReadAll(req.Body()) + + if string(readBody) != string(marshalled) { + t.Errorf("Expected %v, but got %v", string(marshalled), string(readBody)) + } + + // Using the raw []byte + req, err = client.createRequest("/", context.Background(), http.MethodGet, operationContext, nil, nil) + if err != nil { + t.Fatal(err) + } + + err = client.attachContent(marshalled, req) + if err != nil { + t.Fatal(err) + } + + readBody, _ = ioutil.ReadAll(req.Body()) + + if string(readBody) != string(marshalled) { + t.Errorf("Expected %v, but got %v", string(marshalled), string(readBody)) + } +} + +func TestCreateRequest(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + req, err := client.createRequest("/", context.Background(), http.MethodGet, operationContext, nil, nil) + if err != nil { + t.Fatal(err) + } + + if req.Raw().URL.String() != srv.URL()+"/" { + t.Errorf("Expected %v, but got %v", srv.URL()+"/", req.Raw().URL.String()) + } + + if req.Raw().Method != http.MethodGet { + t.Errorf("Expected %v, but got %v", http.MethodGet, req.Raw().Method) + } + + if req.Raw().Header.Get(headerXmsDate) == "" { + t.Errorf("Expected %v, but got %v", "", req.Raw().Header.Get(headerXmsDate)) + } + + if req.Raw().Header.Get(headerXmsVersion) != "2020-11-05" { + t.Errorf("Expected %v, but got %v", "2020-11-05", req.Raw().Header.Get(headerXmsVersion)) + } + + opValue := pipelineRequestOptions{} + if !req.OperationValue(&opValue) { + t.Error("Expected to find operation value") + } +} + +func TestSendDelete(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + verifier := pipelineVerifier{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{&verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + _, err := client.sendDeleteRequest("/", context.Background(), operationContext, &DeleteDatabaseOptions{}, nil) + if err != nil { + t.Fatal(err) + } + + if verifier.method != http.MethodDelete { + t.Errorf("Expected %v, but got %v", http.MethodDelete, verifier.method) + } +} + +func TestSendGet(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + verifier := pipelineVerifier{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{&verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + _, err := client.sendGetRequest("/", context.Background(), operationContext, &DeleteDatabaseOptions{}, nil) + if err != nil { + t.Fatal(err) + } + + if verifier.method != http.MethodGet { + t.Errorf("Expected %v, but got %v", http.MethodGet, verifier.method) + } +} + +func TestSendPut(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + verifier := pipelineVerifier{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{&verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + body := map[string]string{ + "foo": "bar", + } + + marshalled, _ := json.Marshal(body) + + _, err := client.sendPutRequest("/", context.Background(), body, operationContext, &DeleteDatabaseOptions{}, nil) + if err != nil { + t.Fatal(err) + } + + if verifier.method != http.MethodPut { + t.Errorf("Expected %v, but got %v", http.MethodPut, verifier.method) + } + + if verifier.body != string(marshalled) { + t.Errorf("Expected %v, but got %v", string(marshalled), verifier.body) + } +} + +func TestSendPost(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + verifier := pipelineVerifier{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{&verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + body := map[string]string{ + "foo": "bar", + } + + marshalled, _ := json.Marshal(body) + + _, err := client.sendPostRequest("/", context.Background(), body, operationContext, &DeleteDatabaseOptions{}, nil) + if err != nil { + t.Fatal(err) + } + + if verifier.method != http.MethodPost { + t.Errorf("Expected %v, but got %v", http.MethodPost, verifier.method) + } + + if verifier.body != string(marshalled) { + t.Errorf("Expected %v, but got %v", string(marshalled), verifier.body) + } +} + +func TestSendQuery(t *testing.T) { + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse( + mock.WithStatusCode(200)) + verifier := pipelineVerifier{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{&verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + client := &Client{endpoint: srv.URL(), pipeline: pl} + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDatabase, + resourceAddress: "", + } + + _, err := client.sendQueryRequest("/", context.Background(), "SELECT * FROM c", operationContext, &DeleteDatabaseOptions{}, nil) + if err != nil { + t.Fatal(err) + } + + if verifier.method != http.MethodPost { + t.Errorf("Expected %v, but got %v", http.MethodPost, verifier.method) + } + + if verifier.isQuery != true { + t.Errorf("Expected %v, but got %v", true, verifier.isQuery) + } + + if verifier.contentType != cosmosHeaderValuesQuery { + t.Errorf("Expected %v, but got %v", cosmosHeaderValuesQuery, verifier.contentType) + } + + if verifier.body != "{\"query\":\"SELECT * FROM c\"}" { + t.Errorf("Expected %v, but got %v", "{\"query\":\"SELECT * FROM c\"}", verifier.body) + } +} + +type pipelineVerifier struct { + method string + body string + contentType string + isQuery bool +} + +func (p *pipelineVerifier) Do(req *policy.Request) (*http.Response, error) { + p.method = req.Raw().Method + if req.Body() != nil { + readBody, _ := ioutil.ReadAll(req.Body()) + p.body = string(readBody) + } + p.contentType = req.Raw().Header.Get(headerContentType) + p.isQuery = req.Raw().Method == http.MethodPost && req.Raw().Header.Get(cosmosHeaderQuery) == "True" + return req.Next() +} diff --git a/sdk/data/azcosmos/cosmos_container.go b/sdk/data/azcosmos/cosmos_container.go index 700532afedca..5d50ac9e3b32 100644 --- a/sdk/data/azcosmos/cosmos_container.go +++ b/sdk/data/azcosmos/cosmos_container.go @@ -9,35 +9,39 @@ import ( "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" ) -// A Container lets you perform read, update, change throughput, and delete container operations. +// A ContainerClient lets you perform read, update, change throughput, and delete container operations. // It also lets you perform read, update, change throughput, and delete item operations. -type Container struct { +type ContainerClient struct { // The Id of the Cosmos container - Id string + id string // The database that contains the container - Database *Database + database *DatabaseClient // The resource link link string } -func newContainer(id string, database *Database) *Container { - return &Container{ - Id: id, - Database: database, - link: createLink(database.link, pathSegmentCollection, id)} +func newContainer(id string, database *DatabaseClient) (ContainerClient, error) { + return ContainerClient{ + id: id, + database: database, + link: createLink(database.link, pathSegmentCollection, id)}, nil +} + +func (c *ContainerClient) ID() string { + return c.id } // Read obtains the information for a Cosmos container. // ctx - The context for the request. // o - Options for the operation. -func (c *Container) Read( +func (c *ContainerClient) Read( ctx context.Context, o *ReadContainerOptions) (ContainerResponse, error) { if o == nil { o = &ReadContainerOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeCollection, resourceAddress: c.link, } @@ -47,7 +51,7 @@ func (c *Container) Read( return ContainerResponse{}, err } - azResponse, err := c.Database.client.connection.sendGetRequest( + azResponse, err := c.database.client.sendGetRequest( path, ctx, operationContext, @@ -57,13 +61,13 @@ func (c *Container) Read( return ContainerResponse{}, err } - return newContainerResponse(azResponse, c) + return newContainerResponse(azResponse) } // Replace a Cosmos container. // ctx - The context for the request. // o - Options for the operation. -func (c *Container) Replace( +func (c *ContainerClient) Replace( ctx context.Context, containerProperties ContainerProperties, o *ReplaceContainerOptions) (ContainerResponse, error) { @@ -71,7 +75,7 @@ func (c *Container) Replace( o = &ReplaceContainerOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeCollection, resourceAddress: c.link, } @@ -81,7 +85,7 @@ func (c *Container) Replace( return ContainerResponse{}, err } - azResponse, err := c.Database.client.connection.sendPutRequest( + azResponse, err := c.database.client.sendPutRequest( path, ctx, containerProperties, @@ -92,20 +96,20 @@ func (c *Container) Replace( return ContainerResponse{}, err } - return newContainerResponse(azResponse, c) + return newContainerResponse(azResponse) } // Delete a Cosmos container. // ctx - The context for the request. // o - Options for the operation. -func (c *Container) Delete( +func (c *ContainerClient) Delete( ctx context.Context, o *DeleteContainerOptions) (ContainerResponse, error) { if o == nil { o = &DeleteContainerOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeCollection, resourceAddress: c.link, } @@ -115,7 +119,7 @@ func (c *Container) Delete( return ContainerResponse{}, err } - azResponse, err := c.Database.client.connection.sendDeleteRequest( + azResponse, err := c.database.client.sendDeleteRequest( path, ctx, operationContext, @@ -125,13 +129,13 @@ func (c *Container) Delete( return ContainerResponse{}, err } - return newContainerResponse(azResponse, c) + return newContainerResponse(azResponse) } // ReadThroughput obtains the provisioned throughput information for the container. // ctx - The context for the request. // o - Options for the operation. -func (c *Container) ReadThroughput( +func (c *ContainerClient) ReadThroughput( ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error) { if o == nil { @@ -143,7 +147,7 @@ func (c *Container) ReadThroughput( return ThroughputResponse{}, err } - offers := &cosmosOffers{connection: c.Database.client.connection} + offers := &cosmosOffers{client: c.database.client} return offers.ReadThroughputIfExists(ctx, rid, o) } @@ -151,7 +155,7 @@ func (c *Container) ReadThroughput( // ctx - The context for the request. // throughputProperties - The throughput configuration of the container. // o - Options for the operation. -func (c *Container) ReplaceThroughput( +func (c *ContainerClient) ReplaceThroughput( ctx context.Context, throughputProperties ThroughputProperties, o *ThroughputOptions) (ThroughputResponse, error) { @@ -164,7 +168,7 @@ func (c *Container) ReplaceThroughput( return ThroughputResponse{}, err } - offers := &cosmosOffers{connection: c.Database.client.connection} + offers := &cosmosOffers{client: c.database.client} return offers.ReadThroughputIfExists(ctx, rid, o) } @@ -173,38 +177,39 @@ func (c *Container) ReplaceThroughput( // partitionKey - The partition key for the item. // item - The item to create. // o - Options for the operation. -func (c *Container) CreateItem( +func (c *ContainerClient) CreateItem( ctx context.Context, partitionKey PartitionKey, - item interface{}, + item []byte, o *ItemOptions) (ItemResponse, error) { - - addHeader, err := c.buildRequestEnricher(partitionKey, o, true) - if err != nil { - return ItemResponse{}, err + h := headerOptionsOverride{ + partitionKey: &partitionKey, } if o == nil { o = &ItemOptions{} + } else { + h.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite } - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDocument, - resourceAddress: c.link, - } + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDocument, + resourceAddress: c.link, + isWriteOperation: true, + headerOptionsOverride: &h} path, err := generatePathForNameBased(resourceTypeDocument, c.link, true) if err != nil { return ItemResponse{}, err } - azResponse, err := c.Database.client.connection.sendPostRequest( + azResponse, err := c.database.client.sendPostRequest( path, ctx, item, operationContext, o, - addHeader) + nil) if err != nil { return ItemResponse{}, err } @@ -217,37 +222,37 @@ func (c *Container) CreateItem( // partitionKey - The partition key for the item. // item - The item to upsert. // o - Options for the operation. -func (c *Container) UpsertItem( +func (c *ContainerClient) UpsertItem( ctx context.Context, partitionKey PartitionKey, - item interface{}, + item []byte, o *ItemOptions) (ItemResponse, error) { - - addHeaderInternal, err := c.buildRequestEnricher(partitionKey, o, true) - if err != nil { - return ItemResponse{}, err + h := headerOptionsOverride{ + partitionKey: &partitionKey, } addHeader := func(r *policy.Request) { - addHeaderInternal(r) r.Raw().Header.Add(cosmosHeaderIsUpsert, "true") } if o == nil { o = &ItemOptions{} + } else { + h.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite } - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDocument, - resourceAddress: c.link, - } + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDocument, + resourceAddress: c.link, + isWriteOperation: true, + headerOptionsOverride: &h} path, err := generatePathForNameBased(resourceTypeDocument, c.link, true) if err != nil { return ItemResponse{}, err } - azResponse, err := c.Database.client.connection.sendPostRequest( + azResponse, err := c.database.client.sendPostRequest( path, ctx, item, @@ -267,39 +272,40 @@ func (c *Container) UpsertItem( // itemId - The id of the item to replace. // item - The content to be used to replace. // o - Options for the operation. -func (c *Container) ReplaceItem( +func (c *ContainerClient) ReplaceItem( ctx context.Context, partitionKey PartitionKey, itemId string, - item interface{}, + item []byte, o *ItemOptions) (ItemResponse, error) { - - addHeader, err := c.buildRequestEnricher(partitionKey, o, true) - if err != nil { - return ItemResponse{}, err + h := headerOptionsOverride{ + partitionKey: &partitionKey, } if o == nil { o = &ItemOptions{} + } else { + h.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite } - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDocument, - resourceAddress: createLink(c.link, pathSegmentDocument, itemId), - } + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDocument, + resourceAddress: createLink(c.link, pathSegmentDocument, itemId), + isWriteOperation: true, + headerOptionsOverride: &h} path, err := generatePathForNameBased(resourceTypeDocument, operationContext.resourceAddress, false) if err != nil { return ItemResponse{}, err } - azResponse, err := c.Database.client.connection.sendPutRequest( + azResponse, err := c.database.client.sendPutRequest( path, ctx, item, operationContext, o, - addHeader) + nil) if err != nil { return ItemResponse{}, err } @@ -312,37 +318,35 @@ func (c *Container) ReplaceItem( // partitionKey - The partition key for the item. // itemId - The id of the item to read. // o - Options for the operation. -func (c *Container) ReadItem( +func (c *ContainerClient) ReadItem( ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error) { - - addHeader, err := c.buildRequestEnricher(partitionKey, o, false) - if err != nil { - return ItemResponse{}, err + h := headerOptionsOverride{ + partitionKey: &partitionKey, } if o == nil { o = &ItemOptions{} } - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDocument, - resourceAddress: createLink(c.link, pathSegmentDocument, itemId), - } + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDocument, + resourceAddress: createLink(c.link, pathSegmentDocument, itemId), + headerOptionsOverride: &h} path, err := generatePathForNameBased(resourceTypeDocument, operationContext.resourceAddress, false) if err != nil { return ItemResponse{}, err } - azResponse, err := c.Database.client.connection.sendGetRequest( + azResponse, err := c.database.client.sendGetRequest( path, ctx, operationContext, o, - addHeader) + nil) if err != nil { return ItemResponse{}, err } @@ -355,37 +359,38 @@ func (c *Container) ReadItem( // partitionKey - The partition key for the item. // itemId - The id of the item to delete. // o - Options for the operation. -func (c *Container) DeleteItem( +func (c *ContainerClient) DeleteItem( ctx context.Context, partitionKey PartitionKey, itemId string, o *ItemOptions) (ItemResponse, error) { - - addHeader, err := c.buildRequestEnricher(partitionKey, o, true) - if err != nil { - return ItemResponse{}, err + h := headerOptionsOverride{ + partitionKey: &partitionKey, } if o == nil { o = &ItemOptions{} + } else { + h.enableContentResponseOnWrite = &o.EnableContentResponseOnWrite } - operationContext := cosmosOperationContext{ - resourceType: resourceTypeDocument, - resourceAddress: createLink(c.link, pathSegmentDocument, itemId), - } + operationContext := pipelineRequestOptions{ + resourceType: resourceTypeDocument, + resourceAddress: createLink(c.link, pathSegmentDocument, itemId), + isWriteOperation: true, + headerOptionsOverride: &h} path, err := generatePathForNameBased(resourceTypeDocument, operationContext.resourceAddress, false) if err != nil { return ItemResponse{}, err } - azResponse, err := c.Database.client.connection.sendDeleteRequest( + azResponse, err := c.database.client.sendDeleteRequest( path, ctx, operationContext, o, - addHeader) + nil) if err != nil { return ItemResponse{}, err } @@ -393,35 +398,11 @@ func (c *Container) DeleteItem( return newItemResponse(azResponse) } -func (c *Container) buildRequestEnricher( - partitionKey PartitionKey, - requestOptions *ItemOptions, - writeOperation bool) (func(r *policy.Request), error) { - pk, err := partitionKey.toJsonString() - if err != nil { - return nil, err - } - - var enableContentResponseOnWrite bool - if requestOptions == nil { - enableContentResponseOnWrite = c.Database.client.options.EnableContentResponseOnWrite - } else { - enableContentResponseOnWrite = requestOptions.EnableContentResponseOnWrite - } - - return func(r *policy.Request) { - r.Raw().Header.Add(cosmosHeaderPartitionKey, pk) - if writeOperation && !enableContentResponseOnWrite { - r.Raw().Header.Add(cosmosHeaderPrefer, cosmosHeaderValuesPreferMinimal) - } - }, nil -} - -func (c *Container) getRID(ctx context.Context) (string, error) { +func (c *ContainerClient) getRID(ctx context.Context) (string, error) { containerResponse, err := c.Read(ctx, nil) if err != nil { return "", err } - return containerResponse.ContainerProperties.ResourceId, nil + return containerResponse.ContainerProperties.ResourceID, nil } diff --git a/sdk/data/azcosmos/cosmos_container_properties.go b/sdk/data/azcosmos/cosmos_container_properties.go index b56feb0459a2..c6f1949d98ed 100644 --- a/sdk/data/azcosmos/cosmos_container_properties.go +++ b/sdk/data/azcosmos/cosmos_container_properties.go @@ -3,34 +3,190 @@ package azcosmos -import "github.com/Azure/azure-sdk-for-go/sdk/azcore" +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) // ContainerProperties represents the properties of a container. type ContainerProperties struct { - // Id contains the unique id of the container. - Id string `json:"id"` + // ID contains the unique id of the container. + ID string // ETag contains the entity etag of the container. - ETag azcore.ETag `json:"_etag,omitempty"` + ETag *azcore.ETag // SelfLink contains the self-link of the container. - SelfLink string `json:"_self,omitempty"` - // ResourceId contains the resource id of the container. - ResourceId string `json:"_rid,omitempty"` + SelfLink string + // ResourceID contains the resource id of the container. + ResourceID string // LastModified contains the last modified time of the container. - LastModified *UnixTime `json:"_ts,omitempty"` + LastModified time.Time // DefaultTimeToLive contains the default time to live in seconds for items in the container. // For more information see https://docs.microsoft.com/azure/cosmos-db/time-to-live#time-to-live-configurations - DefaultTimeToLive *int `json:"defaultTtl,omitempty"` + DefaultTimeToLive *int32 // AnalyticalStoreTimeToLiveInSeconds contains the default time to live in seconds for analytical store in the container. // For more information see https://docs.microsoft.com/azure/cosmos-db/analytical-store-introduction#analytical-ttl - AnalyticalStoreTimeToLiveInSeconds *int `json:"analyticalStorageTtl,omitempty"` + AnalyticalStoreTimeToLiveInSeconds *int32 // PartitionKeyDefinition contains the partition key definition of the container. - PartitionKeyDefinition PartitionKeyDefinition `json:"partitionKey,omitempty"` + PartitionKeyDefinition PartitionKeyDefinition // IndexingPolicy contains the indexing definition of the container. - IndexingPolicy *IndexingPolicy `json:"indexingPolicy,omitempty"` + IndexingPolicy *IndexingPolicy // UniqueKeyPolicy contains the unique key policy of the container. - UniqueKeyPolicy *UniqueKeyPolicy `json:"uniqueKeyPolicy,omitempty"` + UniqueKeyPolicy *UniqueKeyPolicy // ConflictResolutionPolicy contains the conflict resolution policy of the container. - ConflictResolutionPolicy *ConflictResolutionPolicy `json:"conflictResolutionPolicy,omitempty"` - // Container represented by these properties - Container *Container `json:"-"` + ConflictResolutionPolicy *ConflictResolutionPolicy +} + +func (tp ContainerProperties) MarshalJSON() ([]byte, error) { + pkDefinition, err := json.Marshal(tp.PartitionKeyDefinition) + if err != nil { + return nil, err + } + + buffer := bytes.NewBufferString("{") + buffer.WriteString(fmt.Sprintf("\"id\":\"%s\"", tp.ID)) + + if tp.ResourceID != "" { + buffer.WriteString(fmt.Sprintf(",\"_rid\":\"%s\"", tp.ResourceID)) + } + + if tp.ETag != nil { + buffer.WriteString(",\"_etag\":") + etag, err := json.Marshal(tp.ETag) + if err != nil { + return nil, err + } + buffer.Write(etag) + } + + if tp.SelfLink != "" { + buffer.WriteString(fmt.Sprintf(",\"_self\":\"%s\"", tp.SelfLink)) + } + + if !tp.LastModified.IsZero() { + buffer.WriteString(fmt.Sprintf(",\"_ts\":%v", strconv.FormatInt(tp.LastModified.Unix(), 10))) + } + + buffer.WriteString(",\"partitionKey\":") + buffer.Write(pkDefinition) + + if tp.DefaultTimeToLive != nil { + buffer.WriteString(fmt.Sprintf(",\"defaultTtl\":%v", *tp.DefaultTimeToLive)) + } + + if tp.AnalyticalStoreTimeToLiveInSeconds != nil { + buffer.WriteString(fmt.Sprintf(",\"analyticalStorageTtl\":%v", *tp.AnalyticalStoreTimeToLiveInSeconds)) + } + + if tp.IndexingPolicy != nil { + indexingPolicy, err := json.Marshal(tp.IndexingPolicy) + if err != nil { + return nil, err + } + buffer.WriteString(",\"indexingPolicy\":") + buffer.Write(indexingPolicy) + } + + if tp.UniqueKeyPolicy != nil { + uniquePolicy, err := json.Marshal(tp.UniqueKeyPolicy) + if err != nil { + return nil, err + } + buffer.WriteString(",\"uniqueKeyPolicy\":") + buffer.Write(uniquePolicy) + } + + if tp.ConflictResolutionPolicy != nil { + conflictPolicy, err := json.Marshal(tp.ConflictResolutionPolicy) + if err != nil { + return nil, err + } + buffer.WriteString(",\"conflictResolutionPolicy\":") + buffer.Write(conflictPolicy) + } + + buffer.WriteString("}") + return buffer.Bytes(), nil +} + +func (tp *ContainerProperties) UnmarshalJSON(b []byte) error { + var attributes map[string]json.RawMessage + err := json.Unmarshal(b, &attributes) + if err != nil { + return err + } + + if id, ok := attributes["id"]; ok { + if err := json.Unmarshal(id, &tp.ID); err != nil { + return err + } + } + + if etag, ok := attributes["_etag"]; ok { + if err := json.Unmarshal(etag, &tp.ETag); err != nil { + return err + } + } + + if self, ok := attributes["_self"]; ok { + if err := json.Unmarshal(self, &tp.SelfLink); err != nil { + return err + } + } + + if rid, ok := attributes["_rid"]; ok { + if err := json.Unmarshal(rid, &tp.ResourceID); err != nil { + return err + } + } + + if ttl, ok := attributes["defaultTtl"]; ok { + if err := json.Unmarshal(ttl, &tp.DefaultTimeToLive); err != nil { + return err + } + } + + if analyticalTtl, ok := attributes["analyticalStorageTtl"]; ok { + if err := json.Unmarshal(analyticalTtl, &tp.AnalyticalStoreTimeToLiveInSeconds); err != nil { + return err + } + } + + if ts, ok := attributes["_ts"]; ok { + var timestamp int64 + if err := json.Unmarshal(ts, ×tamp); err != nil { + return err + } + tp.LastModified = time.Unix(timestamp, 0) + } + + if pk, ok := attributes["partitionKey"]; ok { + if err := json.Unmarshal(pk, &tp.PartitionKeyDefinition); err != nil { + return err + } + } + + if ip, ok := attributes["indexingPolicy"]; ok { + if err := json.Unmarshal(ip, &tp.IndexingPolicy); err != nil { + return err + } + } + + if up, ok := attributes["uniqueKeyPolicy"]; ok { + if err := json.Unmarshal(up, &tp.UniqueKeyPolicy); err != nil { + return err + } + } + + if cp, ok := attributes["conflictResolutionPolicy"]; ok { + if err := json.Unmarshal(cp, &tp.ConflictResolutionPolicy); err != nil { + return err + } + } + + return nil } diff --git a/sdk/data/azcosmos/cosmos_container_properties_test.go b/sdk/data/azcosmos/cosmos_container_properties_test.go index 9195225da538..aca9c081a7a6 100644 --- a/sdk/data/azcosmos/cosmos_container_properties_test.go +++ b/sdk/data/azcosmos/cosmos_container_properties_test.go @@ -7,24 +7,24 @@ import ( "encoding/json" "testing" "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) func TestContainerPropertiesSerialization(t *testing.T) { - nowAsUnix := time.Now().Unix() + nowAsUnix := time.Unix(time.Now().Unix(), 0) - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } + etag := azcore.ETag("etag") - properties := &ContainerProperties{ - Id: "someId", - ETag: "someEtag", + properties := ContainerProperties{ + ID: "someId", + ETag: &etag, SelfLink: "someSelfLink", - ResourceId: "someResourceId", - LastModified: &now, + ResourceID: "someResourceId", + LastModified: nowAsUnix, PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"somePath"}, - Version: PartitionKeyDefinitionVersion2, + Version: 2, }, IndexingPolicy: &IndexingPolicy{ IncludedPaths: []IncludedPath{ @@ -66,24 +66,24 @@ func TestContainerPropertiesSerialization(t *testing.T) { t.Fatal(err, string(jsonString)) } - if properties.Id != otherProperties.Id { - t.Errorf("Expected Id to be %s, but got %s", properties.Id, otherProperties.Id) + if properties.ID != otherProperties.ID { + t.Errorf("Expected Id to be %s, but got %s", properties.ID, otherProperties.ID) } - if properties.ETag != otherProperties.ETag { - t.Errorf("Expected ETag to be %s, but got %s", properties.ETag, otherProperties.ETag) + if *properties.ETag != *otherProperties.ETag { + t.Errorf("Expected ETag to be %s, but got %s", *properties.ETag, *otherProperties.ETag) } if properties.SelfLink != otherProperties.SelfLink { t.Errorf("Expected SelfLink to be %s, but got %s", properties.SelfLink, otherProperties.SelfLink) } - if properties.ResourceId != otherProperties.ResourceId { - t.Errorf("Expected ResourceId to be %s, but got %s", properties.ResourceId, otherProperties.ResourceId) + if properties.ResourceID != otherProperties.ResourceID { + t.Errorf("Expected ResourceId to be %s, but got %s", properties.ResourceID, otherProperties.ResourceID) } - if properties.LastModified.Time != otherProperties.LastModified.Time { - t.Errorf("Expected LastModified.Time to be %s, but got %s", properties.LastModified.Time.UTC(), otherProperties.LastModified.Time.UTC()) + if properties.LastModified != otherProperties.LastModified { + t.Errorf("Expected LastModified.Time to be %v, but got %v", properties.LastModified, otherProperties.LastModified) } if otherProperties.AnalyticalStoreTimeToLiveInSeconds != nil { diff --git a/sdk/data/azcosmos/cosmos_container_request_options_test.go b/sdk/data/azcosmos/cosmos_container_request_options_test.go index f95911a61cb7..df667d0ad52d 100644 --- a/sdk/data/azcosmos/cosmos_container_request_options_test.go +++ b/sdk/data/azcosmos/cosmos_container_request_options_test.go @@ -16,7 +16,7 @@ func TestContainerRequestOptionsToHeaders(t *testing.T) { options.PopulateQuotaInfo = true header := options.toHeaders() if header == nil { - t.Error("toHeaders should return non-nil") + t.Fatal("toHeaders should return non-nil") } headers := *header diff --git a/sdk/data/azcosmos/cosmos_container_response.go b/sdk/data/azcosmos/cosmos_container_response.go index 44cda0195039..9d216ca3861d 100644 --- a/sdk/data/azcosmos/cosmos_container_response.go +++ b/sdk/data/azcosmos/cosmos_container_response.go @@ -16,7 +16,7 @@ type ContainerResponse struct { Response } -func newContainerResponse(resp *http.Response, container *Container) (ContainerResponse, error) { +func newContainerResponse(resp *http.Response) (ContainerResponse, error) { response := ContainerResponse{ Response: newResponse(resp), } @@ -26,6 +26,5 @@ func newContainerResponse(resp *http.Response, container *Container) (ContainerR return response, err } response.ContainerProperties = properties - response.ContainerProperties.Container = container return response, nil } diff --git a/sdk/data/azcosmos/cosmos_container_response_test.go b/sdk/data/azcosmos/cosmos_container_response_test.go index 39547fc4a686..2bb9023387aa 100644 --- a/sdk/data/azcosmos/cosmos_container_response_test.go +++ b/sdk/data/azcosmos/cosmos_container_response_test.go @@ -10,33 +10,28 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) func TestContainerResponseParsing(t *testing.T) { - nowAsUnix := time.Now().Unix() + nowAsUnix := time.Unix(time.Now().Unix(), 0) - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } - - properties := &ContainerProperties{ - Id: "someId", - ETag: "someEtag", + etag := azcore.ETag("etag") + properties := ContainerProperties{ + ID: "someId", + ETag: &etag, SelfLink: "someSelfLink", - ResourceId: "someResourceId", - LastModified: &now, + ResourceID: "someResourceId", + LastModified: nowAsUnix, PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"somePath"}, - Version: PartitionKeyDefinitionVersion2, + Version: 2, }, } - container := &Container{ - Id: "someId", - } - jsonString, err := json.Marshal(properties) if err != nil { t.Fatal(err) @@ -55,9 +50,9 @@ func TestContainerResponseParsing(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) - parsedResponse, err := newContainerResponse(resp, container) + parsedResponse, err := newContainerResponse(resp) if err != nil { t.Fatal(err) } @@ -70,24 +65,24 @@ func TestContainerResponseParsing(t *testing.T) { t.Fatal("parsedResponse.ContainerProperties is nil") } - if properties.Id != parsedResponse.ContainerProperties.Id { - t.Errorf("Expected Id to be %s, but got %s", properties.Id, parsedResponse.ContainerProperties.Id) + if properties.ID != parsedResponse.ContainerProperties.ID { + t.Errorf("Expected Id to be %s, but got %s", properties.ID, parsedResponse.ContainerProperties.ID) } - if properties.ETag != parsedResponse.ContainerProperties.ETag { - t.Errorf("Expected ETag to be %s, but got %s", properties.ETag, parsedResponse.ContainerProperties.ETag) + if *properties.ETag != *parsedResponse.ContainerProperties.ETag { + t.Errorf("Expected ETag to be %s, but got %s", *properties.ETag, *parsedResponse.ContainerProperties.ETag) } if properties.SelfLink != parsedResponse.ContainerProperties.SelfLink { t.Errorf("Expected SelfLink to be %s, but got %s", properties.SelfLink, parsedResponse.ContainerProperties.SelfLink) } - if properties.ResourceId != parsedResponse.ContainerProperties.ResourceId { - t.Errorf("Expected ResourceId to be %s, but got %s", properties.ResourceId, parsedResponse.ContainerProperties.ResourceId) + if properties.ResourceID != parsedResponse.ContainerProperties.ResourceID { + t.Errorf("Expected ResourceId to be %s, but got %s", properties.ResourceID, parsedResponse.ContainerProperties.ResourceID) } - if properties.LastModified.Time != parsedResponse.ContainerProperties.LastModified.Time { - t.Errorf("Expected LastModified.Time to be %s, but got %s", properties.LastModified.Time.UTC(), parsedResponse.ContainerProperties.LastModified.Time.UTC()) + if properties.LastModified != parsedResponse.ContainerProperties.LastModified { + t.Errorf("Expected LastModified.Time to be %v, but got %v", properties.LastModified, parsedResponse.ContainerProperties.LastModified) } if properties.PartitionKeyDefinition.Paths[0] != parsedResponse.ContainerProperties.PartitionKeyDefinition.Paths[0] { @@ -109,8 +104,4 @@ func TestContainerResponseParsing(t *testing.T) { if parsedResponse.ETag != "someEtag" { t.Errorf("Expected ETag to be %s, but got %s", "someEtag", parsedResponse.ETag) } - - if parsedResponse.ContainerProperties.Container != container { - t.Errorf("Expected Container to be %v, but got %v", container, parsedResponse.ContainerProperties.Container) - } } diff --git a/sdk/data/azcosmos/cosmos_database.go b/sdk/data/azcosmos/cosmos_database.go index 2f6ee77eef87..37d6fa9b2b4d 100644 --- a/sdk/data/azcosmos/cosmos_database.go +++ b/sdk/data/azcosmos/cosmos_database.go @@ -8,38 +8,42 @@ import ( "errors" ) -// A Database lets you perform read, update, change throughput, and delete database operations. -type Database struct { +// A DatabaseClient lets you perform read, update, change throughput, and delete database operations. +type DatabaseClient struct { // The Id of the Cosmos database - Id string + id string // The client associated with the Cosmos database client *Client // The resource link link string } -func newDatabase(id string, client *Client) *Database { - return &Database{ - Id: id, +func newDatabase(id string, client *Client) (DatabaseClient, error) { + return DatabaseClient{ + id: id, client: client, - link: createLink("", pathSegmentDatabase, id)} + link: createLink("", pathSegmentDatabase, id)}, nil } -// GetContainer returns a Container object for the container. +func (db *DatabaseClient) ID() string { + return db.id +} + +// NewContainer returns a Container object for the container. // id - The id of the container. -func (db *Database) GetContainer(id string) (*Container, error) { +func (db *DatabaseClient) NewContainer(id string) (ContainerClient, error) { if id == "" { - return nil, errors.New("id is required") + return ContainerClient{}, errors.New("id is required") } - return newContainer(id, db), nil + return newContainer(id, db) } // CreateContainer creates a container in the Cosmos database. // ctx - The context for the request. // containerProperties - The properties for the container. // o - Options for the create container operation. -func (db *Database) CreateContainer( +func (db *DatabaseClient) CreateContainer( ctx context.Context, containerProperties ContainerProperties, o *CreateContainerOptions) (ContainerResponse, error) { @@ -47,7 +51,7 @@ func (db *Database) CreateContainer( o = &CreateContainerOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeCollection, resourceAddress: db.link, } @@ -57,12 +61,7 @@ func (db *Database) CreateContainer( return ContainerResponse{}, err } - container, err := db.GetContainer(containerProperties.Id) - if err != nil { - return ContainerResponse{}, err - } - - azResponse, err := db.client.connection.sendPostRequest( + azResponse, err := db.client.sendPostRequest( path, ctx, containerProperties, @@ -73,20 +72,20 @@ func (db *Database) CreateContainer( return ContainerResponse{}, err } - return newContainerResponse(azResponse, container) + return newContainerResponse(azResponse) } // Read obtains the information for a Cosmos database. // ctx - The context for the request. // o - Options for Read operation. -func (db *Database) Read( +func (db *DatabaseClient) Read( ctx context.Context, o *ReadDatabaseOptions) (DatabaseResponse, error) { if o == nil { o = &ReadDatabaseOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeDatabase, resourceAddress: db.link, } @@ -96,7 +95,7 @@ func (db *Database) Read( return DatabaseResponse{}, err } - azResponse, err := db.client.connection.sendGetRequest( + azResponse, err := db.client.sendGetRequest( path, ctx, operationContext, @@ -106,13 +105,13 @@ func (db *Database) Read( return DatabaseResponse{}, err } - return newDatabaseResponse(azResponse, db) + return newDatabaseResponse(azResponse) } // ReadThroughput obtains the provisioned throughput information for the database. // ctx - The context for the request. // o - Options for the operation. -func (db *Database) ReadThroughput( +func (db *DatabaseClient) ReadThroughput( ctx context.Context, o *ThroughputOptions) (ThroughputResponse, error) { if o == nil { @@ -124,7 +123,7 @@ func (db *Database) ReadThroughput( return ThroughputResponse{}, err } - offers := &cosmosOffers{connection: db.client.connection} + offers := &cosmosOffers{client: db.client} return offers.ReadThroughputIfExists(ctx, rid, o) } @@ -132,7 +131,7 @@ func (db *Database) ReadThroughput( // ctx - The context for the request. // throughputProperties - The throughput configuration of the database. // o - Options for the operation. -func (db *Database) ReplaceThroughput( +func (db *DatabaseClient) ReplaceThroughput( ctx context.Context, throughputProperties ThroughputProperties, o *ThroughputOptions) (ThroughputResponse, error) { @@ -145,21 +144,21 @@ func (db *Database) ReplaceThroughput( return ThroughputResponse{}, err } - offers := &cosmosOffers{connection: db.client.connection} + offers := &cosmosOffers{client: db.client} return offers.ReadThroughputIfExists(ctx, rid, o) } // Delete a Cosmos database. // ctx - The context for the request. // o - Options for Read operation. -func (db *Database) Delete( +func (db *DatabaseClient) Delete( ctx context.Context, o *DeleteDatabaseOptions) (DatabaseResponse, error) { if o == nil { o = &DeleteDatabaseOptions{} } - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeDatabase, resourceAddress: db.link, } @@ -169,7 +168,7 @@ func (db *Database) Delete( return DatabaseResponse{}, err } - azResponse, err := db.client.connection.sendDeleteRequest( + azResponse, err := db.client.sendDeleteRequest( path, ctx, operationContext, @@ -179,14 +178,14 @@ func (db *Database) Delete( return DatabaseResponse{}, err } - return newDatabaseResponse(azResponse, db) + return newDatabaseResponse(azResponse) } -func (db *Database) getRID(ctx context.Context) (string, error) { +func (db *DatabaseClient) getRID(ctx context.Context) (string, error) { dbResponse, err := db.Read(ctx, nil) if err != nil { return "", err } - return dbResponse.DatabaseProperties.ResourceId, nil + return dbResponse.DatabaseProperties.ResourceID, nil } diff --git a/sdk/data/azcosmos/cosmos_database_properties.go b/sdk/data/azcosmos/cosmos_database_properties.go index cccec0da469d..5bbfcde3f479 100644 --- a/sdk/data/azcosmos/cosmos_database_properties.go +++ b/sdk/data/azcosmos/cosmos_database_properties.go @@ -3,20 +3,98 @@ package azcosmos -import "github.com/Azure/azure-sdk-for-go/sdk/azcore" +import ( + "bytes" + "encoding/json" + "fmt" + "strconv" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) // DatabaseProperties represents the properties of a database. type DatabaseProperties struct { - // Id contains the unique id of the database. - Id string `json:"id"` + // ID contains the unique id of the database. + ID string `json:"id"` // ETag contains the entity etag of the database - ETag azcore.ETag `json:"_etag,omitempty"` + ETag *azcore.ETag `json:"_etag,omitempty"` // SelfLink contains the self-link of the database SelfLink string `json:"_self,omitempty"` - // ResourceId contains the resource id of the database - ResourceId string `json:"_rid,omitempty"` + // ResourceID contains the resource id of the database + ResourceID string `json:"_rid,omitempty"` // LastModified contains the last modified time of the database - LastModified *UnixTime `json:"_ts,omitempty"` - // Database represented by these properties - Database *Database `json:"-"` + LastModified time.Time `json:"_ts,omitempty"` +} + +func (tp DatabaseProperties) MarshalJSON() ([]byte, error) { + buffer := bytes.NewBufferString("{") + + buffer.WriteString(fmt.Sprintf("\"id\":\"%s\"", tp.ID)) + + if tp.ResourceID != "" { + buffer.WriteString(fmt.Sprintf(",\"_rid\":\"%s\"", tp.ResourceID)) + } + + if tp.ETag != nil { + buffer.WriteString(",\"_etag\":") + etag, err := json.Marshal(tp.ETag) + if err != nil { + return nil, err + } + buffer.Write(etag) + } + + if tp.SelfLink != "" { + buffer.WriteString(fmt.Sprintf(",\"_self\":\"%s\"", tp.SelfLink)) + } + + if !tp.LastModified.IsZero() { + buffer.WriteString(fmt.Sprintf(",\"_ts\":%v", strconv.FormatInt(tp.LastModified.Unix(), 10))) + } + + buffer.WriteString("}") + return buffer.Bytes(), nil +} + +func (tp *DatabaseProperties) UnmarshalJSON(b []byte) error { + var attributes map[string]json.RawMessage + err := json.Unmarshal(b, &attributes) + if err != nil { + return err + } + + if id, ok := attributes["id"]; ok { + if err := json.Unmarshal(id, &tp.ID); err != nil { + return err + } + } + + if etag, ok := attributes["_etag"]; ok { + if err := json.Unmarshal(etag, &tp.ETag); err != nil { + return err + } + } + + if self, ok := attributes["_self"]; ok { + if err := json.Unmarshal(self, &tp.SelfLink); err != nil { + return err + } + } + + if rid, ok := attributes["_rid"]; ok { + if err := json.Unmarshal(rid, &tp.ResourceID); err != nil { + return err + } + } + + if ts, ok := attributes["_ts"]; ok { + var timestamp int64 + if err := json.Unmarshal(ts, ×tamp); err != nil { + return err + } + tp.LastModified = time.Unix(timestamp, 0) + } + + return nil } diff --git a/sdk/data/azcosmos/cosmos_database_properties_test.go b/sdk/data/azcosmos/cosmos_database_properties_test.go index 68c25fa7877b..0ae6a2258335 100644 --- a/sdk/data/azcosmos/cosmos_database_properties_test.go +++ b/sdk/data/azcosmos/cosmos_database_properties_test.go @@ -7,21 +7,20 @@ import ( "encoding/json" "testing" "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) func TestDatabasePropertiesSerialization(t *testing.T) { - nowAsUnix := time.Now().Unix() - - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } + nowAsUnix := time.Unix(time.Now().Unix(), 0) - properties := &DatabaseProperties{ - Id: "someId", - ETag: "someEtag", + etag := azcore.ETag("someETag") + properties := DatabaseProperties{ + ID: "someId", + ETag: &etag, SelfLink: "someSelfLink", - ResourceId: "someResourceId", - LastModified: &now, + ResourceID: "someResourceId", + LastModified: nowAsUnix, } jsonString, err := json.Marshal(properties) @@ -35,24 +34,24 @@ func TestDatabasePropertiesSerialization(t *testing.T) { t.Fatal(err, string(jsonString)) } - if properties.Id != otherProperties.Id { - t.Errorf("Expected otherProperties.Id to be %s, but got %s", properties.Id, otherProperties.Id) + if properties.ID != otherProperties.ID { + t.Errorf("Expected otherProperties.Id to be %s, but got %s", properties.ID, otherProperties.ID) } - if properties.ETag != otherProperties.ETag { - t.Errorf("Expected otherProperties.ETag to be %s, but got %s", properties.ETag, otherProperties.ETag) + if *properties.ETag != *otherProperties.ETag { + t.Errorf("Expected otherProperties.ETag to be %s, but got %s", *properties.ETag, *otherProperties.ETag) } if properties.SelfLink != otherProperties.SelfLink { t.Errorf("Expected otherProperties.SelfLink to be %s, but got %s", properties.SelfLink, otherProperties.SelfLink) } - if properties.ResourceId != otherProperties.ResourceId { - t.Errorf("Expected otherProperties.ResourceId to be %s, but got %s", properties.ResourceId, otherProperties.ResourceId) + if properties.ResourceID != otherProperties.ResourceID { + t.Errorf("Expected otherProperties.ResourceId to be %s, but got %s", properties.ResourceID, otherProperties.ResourceID) } - if properties.LastModified.Time != otherProperties.LastModified.Time { - t.Errorf("Expected otherProperties.LastModified.Time to be %s, but got %s", properties.LastModified.Time.UTC(), otherProperties.LastModified.Time.UTC()) + if properties.LastModified != otherProperties.LastModified { + t.Errorf("Expected otherProperties.LastModified.Time to be %v, but got %v", properties.LastModified, otherProperties.LastModified) } } diff --git a/sdk/data/azcosmos/cosmos_database_request_options_test.go b/sdk/data/azcosmos/cosmos_database_request_options_test.go index 3e3f70b7ea2b..ad6b9868f0b8 100644 --- a/sdk/data/azcosmos/cosmos_database_request_options_test.go +++ b/sdk/data/azcosmos/cosmos_database_request_options_test.go @@ -21,7 +21,7 @@ func TestDatabaseOptionsToHeaders(t *testing.T) { options.IfNoneMatchEtag = &noneEtagValue header := options.toHeaders() if header == nil { - t.Error("toHeaders should return non-nil") + t.Fatal("toHeaders should return non-nil") } headers := *header @@ -45,7 +45,7 @@ func TestDeleteDatabaseOptionsToHeaders(t *testing.T) { options.IfNoneMatchEtag = &noneEtagValue header := options.toHeaders() if header == nil { - t.Error("toHeaders should return non-nil") + t.Fatal("toHeaders should return non-nil") } headers := *header diff --git a/sdk/data/azcosmos/cosmos_database_response.go b/sdk/data/azcosmos/cosmos_database_response.go index f4972d26550e..614f4fbefc8f 100644 --- a/sdk/data/azcosmos/cosmos_database_response.go +++ b/sdk/data/azcosmos/cosmos_database_response.go @@ -16,7 +16,7 @@ type DatabaseResponse struct { Response } -func newDatabaseResponse(resp *http.Response, database *Database) (DatabaseResponse, error) { +func newDatabaseResponse(resp *http.Response) (DatabaseResponse, error) { response := DatabaseResponse{ Response: newResponse(resp), } @@ -26,6 +26,5 @@ func newDatabaseResponse(resp *http.Response, database *Database) (DatabaseRespo return response, err } response.DatabaseProperties = properties - response.DatabaseProperties.Database = database return response, nil } diff --git a/sdk/data/azcosmos/cosmos_database_response_test.go b/sdk/data/azcosmos/cosmos_database_response_test.go index 00a9e8f5d31f..2d80933ad72f 100644 --- a/sdk/data/azcosmos/cosmos_database_response_test.go +++ b/sdk/data/azcosmos/cosmos_database_response_test.go @@ -10,27 +10,22 @@ import ( "testing" "time" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) func TestDatabaseResponseParsing(t *testing.T) { - nowAsUnix := time.Now().Unix() + nowAsUnix := time.Unix(time.Now().Unix(), 0) - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } - - properties := &DatabaseProperties{ - Id: "someId", - ETag: "someEtag", + etag := azcore.ETag("someETag") + properties := DatabaseProperties{ + ID: "someId", + ETag: &etag, SelfLink: "someSelfLink", - ResourceId: "someResourceId", - LastModified: &now, - } - - database := &Database{ - Id: "someId", + ResourceID: "someResourceId", + LastModified: nowAsUnix, } jsonString, err := json.Marshal(properties) @@ -51,9 +46,9 @@ func TestDatabaseResponseParsing(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) - parsedResponse, err := newDatabaseResponse(resp, database) + parsedResponse, err := newDatabaseResponse(resp) if err != nil { t.Fatal(err) } @@ -66,24 +61,24 @@ func TestDatabaseResponseParsing(t *testing.T) { t.Fatal("parsedResponse.DatabaseProperties is nil") } - if properties.Id != parsedResponse.DatabaseProperties.Id { - t.Errorf("Expected properties.Id to be %s, but got %s", properties.Id, parsedResponse.DatabaseProperties.Id) + if properties.ID != parsedResponse.DatabaseProperties.ID { + t.Errorf("Expected properties.Id to be %s, but got %s", properties.ID, parsedResponse.DatabaseProperties.ID) } - if properties.ETag != parsedResponse.DatabaseProperties.ETag { - t.Errorf("Expected properties.ETag to be %s, but got %s", properties.ETag, parsedResponse.DatabaseProperties.ETag) + if *properties.ETag != *parsedResponse.DatabaseProperties.ETag { + t.Errorf("Expected properties.ETag to be %s, but got %s", *properties.ETag, *parsedResponse.DatabaseProperties.ETag) } if properties.SelfLink != parsedResponse.DatabaseProperties.SelfLink { t.Errorf("Expected properties.SelfLink to be %s, but got %s", properties.SelfLink, parsedResponse.DatabaseProperties.SelfLink) } - if properties.ResourceId != parsedResponse.DatabaseProperties.ResourceId { - t.Errorf("Expected properties.ResourceId to be %s, but got %s", properties.ResourceId, parsedResponse.DatabaseProperties.ResourceId) + if properties.ResourceID != parsedResponse.DatabaseProperties.ResourceID { + t.Errorf("Expected properties.ResourceId to be %s, but got %s", properties.ResourceID, parsedResponse.DatabaseProperties.ResourceID) } - if properties.LastModified.Time != parsedResponse.DatabaseProperties.LastModified.Time { - t.Errorf("Expected properties.LastModified.Time to be %s, but got %s", properties.LastModified.Time.UTC(), parsedResponse.DatabaseProperties.LastModified.Time.UTC()) + if properties.LastModified != parsedResponse.DatabaseProperties.LastModified { + t.Errorf("Expected properties.LastModified.Time to be %v, but got %v", properties.LastModified, parsedResponse.DatabaseProperties.LastModified) } if parsedResponse.ActivityId != "someActivityId" { @@ -97,8 +92,4 @@ func TestDatabaseResponseParsing(t *testing.T) { if parsedResponse.ETag != "someEtag" { t.Errorf("Expected ETag to be %s, but got %s", "someEtag", parsedResponse.ETag) } - - if parsedResponse.DatabaseProperties.Database != database { - t.Errorf("Expected database to be %v, but got %v", database, parsedResponse.DatabaseProperties.Database) - } } diff --git a/sdk/data/azcosmos/cosmos_error_test.go b/sdk/data/azcosmos/cosmos_error_test.go index db0d40642bab..539df8c69e90 100644 --- a/sdk/data/azcosmos/cosmos_error_test.go +++ b/sdk/data/azcosmos/cosmos_error_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) @@ -24,7 +25,7 @@ func TestCosmosErrorOnEmptyResponse(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) cError := newCosmosError(resp) @@ -45,7 +46,7 @@ func TestCosmosErrorOnNonJsonBody(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) cError := newCosmosError(resp) @@ -75,7 +76,7 @@ func TestCosmosErrorOnJsonBody(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) cError := newCosmosError(resp) diff --git a/sdk/data/azcosmos/cosmos_headers.go b/sdk/data/azcosmos/cosmos_headers.go index 4747b500e1a7..87dc74440054 100644 --- a/sdk/data/azcosmos/cosmos_headers.go +++ b/sdk/data/azcosmos/cosmos_headers.go @@ -4,7 +4,6 @@ package azcosmos const ( - cosmosHeaderRetryAfter string = "x-ms-retryafter" cosmosHeaderRequestCharge string = "x-ms-request-charge" cosmosHeaderActivityId string = "x-ms-activity-id" cosmosHeaderEtag string = "etag" diff --git a/sdk/data/azcosmos/cosmos_headers_policy.go b/sdk/data/azcosmos/cosmos_headers_policy.go new file mode 100644 index 000000000000..23ca2d4f5773 --- /dev/null +++ b/sdk/data/azcosmos/cosmos_headers_policy.go @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcosmos + +import ( + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +type headerPolicies struct { + enableContentResponseOnWrite bool +} + +type headerOptionsOverride struct { + enableContentResponseOnWrite *bool + partitionKey *PartitionKey +} + +func (p *headerPolicies) Do(req *policy.Request) (*http.Response, error) { + o := pipelineRequestOptions{} + if req.OperationValue(&o) { + enableContentResponseOnWrite := p.enableContentResponseOnWrite + + if o.headerOptionsOverride != nil { + if o.headerOptionsOverride.enableContentResponseOnWrite != nil { + enableContentResponseOnWrite = *o.headerOptionsOverride.enableContentResponseOnWrite + } + + if o.headerOptionsOverride.partitionKey != nil { + pkAsString, err := o.headerOptionsOverride.partitionKey.toJsonString() + if err != nil { + return nil, err + } + req.Raw().Header.Add(cosmosHeaderPartitionKey, string(pkAsString)) + } + } + + if o.isWriteOperation && !enableContentResponseOnWrite { + req.Raw().Header.Add(cosmosHeaderPrefer, cosmosHeaderValuesPreferMinimal) + } + } + + return req.Next() +} diff --git a/sdk/data/azcosmos/cosmos_headers_policy_test.go b/sdk/data/azcosmos/cosmos_headers_policy_test.go new file mode 100644 index 000000000000..a41ed0f36d5a --- /dev/null +++ b/sdk/data/azcosmos/cosmos_headers_policy_test.go @@ -0,0 +1,205 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package azcosmos + +import ( + "context" + "net/http" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" +) + +func TestAddContentHeaderDefaultOnWriteOperation(t *testing.T) { + headerPolicy := &headerPolicies{} + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: true, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if !verifier.isEnableContentResponseOnWriteHeaderSet { + t.Fatalf("expected content response header to be set") + } +} + +func TestAddContentHeaderDefaultOnReadOperation(t *testing.T) { + headerPolicy := &headerPolicies{} + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: false, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if verifier.isEnableContentResponseOnWriteHeaderSet { + t.Fatalf("expected content response header to not be set") + } +} + +func TestAddContentHeaderOnWriteOperation(t *testing.T) { + headerPolicy := &headerPolicies{ + enableContentResponseOnWrite: true, + } + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: true, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if verifier.isEnableContentResponseOnWriteHeaderSet { + t.Fatalf("expected content response header to not be set") + } +} + +func TestAddContentHeaderOnWriteOperationWithOverride(t *testing.T) { + headerPolicy := &headerPolicies{ + enableContentResponseOnWrite: true, + } + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + contentOverride := false + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: true, + headerOptionsOverride: &headerOptionsOverride{ + enableContentResponseOnWrite: &contentOverride, + }, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if !verifier.isEnableContentResponseOnWriteHeaderSet { + t.Fatalf("expected content response header to be set") + } +} + +func TestAddContentHeaderDefaultOnWriteOperationWithOverride(t *testing.T) { + headerPolicy := &headerPolicies{} + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + contentOverride := true + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: true, + headerOptionsOverride: &headerOptionsOverride{ + enableContentResponseOnWrite: &contentOverride, + }, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if verifier.isEnableContentResponseOnWriteHeaderSet { + t.Fatalf("expected content response header to not be set") + } +} + +func TestAddPartitionKeyHeader(t *testing.T) { + headerPolicy := &headerPolicies{} + srv, close := mock.NewTLSServer() + defer close() + srv.SetResponse(mock.WithStatusCode(http.StatusOK)) + + verifier := headerPoliciesVerify{} + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{headerPolicy, &verifier}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) + req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) + + partitionKey := NewPartitionKeyString("some string") + req.SetOperationValue(pipelineRequestOptions{ + isWriteOperation: true, + headerOptionsOverride: &headerOptionsOverride{ + partitionKey: &partitionKey, + }, + }) + + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + _, err = pl.Do(req) + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + if verifier.isPartitionKeyHeaderSet != "[\"some string\"]" { + t.Fatalf("expected pk header to be set") + } +} + +type headerPoliciesVerify struct { + isEnableContentResponseOnWriteHeaderSet bool + isPartitionKeyHeaderSet string +} + +func (p *headerPoliciesVerify) Do(req *policy.Request) (*http.Response, error) { + p.isEnableContentResponseOnWriteHeaderSet = req.Raw().Header.Get(cosmosHeaderPrefer) != "" + p.isPartitionKeyHeaderSet = req.Raw().Header.Get(cosmosHeaderPartitionKey) + + return req.Next() +} diff --git a/sdk/data/azcosmos/cosmos_item_request_options_test.go b/sdk/data/azcosmos/cosmos_item_request_options_test.go index 02625f799b68..d9d08da73c63 100644 --- a/sdk/data/azcosmos/cosmos_item_request_options_test.go +++ b/sdk/data/azcosmos/cosmos_item_request_options_test.go @@ -20,7 +20,7 @@ func TestItemRequestOptionsToHeaders(t *testing.T) { options.IfMatchEtag = &etagValue header := options.toHeaders() if header == nil { - t.Error("toHeaders should return non-nil") + t.Fatal("toHeaders should return non-nil") } headers := *header diff --git a/sdk/data/azcosmos/cosmos_item_response_test.go b/sdk/data/azcosmos/cosmos_item_response_test.go index 90c3c3f78351..4b6c22baad2a 100644 --- a/sdk/data/azcosmos/cosmos_item_response_test.go +++ b/sdk/data/azcosmos/cosmos_item_response_test.go @@ -9,6 +9,7 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) @@ -37,7 +38,7 @@ func TestItemResponseParsing(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) parsedResponse, err := newItemResponse(resp) if err != nil { diff --git a/sdk/data/azcosmos/cosmos_offers.go b/sdk/data/azcosmos/cosmos_offers.go index e04e14453864..9b4d2b8238f6 100644 --- a/sdk/data/azcosmos/cosmos_offers.go +++ b/sdk/data/azcosmos/cosmos_offers.go @@ -12,7 +12,7 @@ import ( ) type cosmosOffers struct { - connection *cosmosClientConnection + client *Client } type cosmosOffersResponse struct { @@ -24,7 +24,7 @@ func (c cosmosOffers) ReadThroughputIfExists( targetRID string, requestOptions *ThroughputOptions) (ThroughputResponse, error) { // TODO: might want to replace with query iterator once that is in - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeOffer, resourceAddress: "", } @@ -34,7 +34,7 @@ func (c cosmosOffers) ReadThroughputIfExists( return ThroughputResponse{}, err } - azResponse, err := c.connection.sendQueryRequest( + azResponse, err := c.client.sendQueryRequest( path, ctx, fmt.Sprintf(`SELECT * FROM c WHERE c.offerResourceId = '%s'`, targetRID), @@ -57,7 +57,7 @@ func (c cosmosOffers) ReadThroughputIfExists( } // Now read the individual offer - operationContext = cosmosOperationContext{ + operationContext = pipelineRequestOptions{ resourceType: resourceTypeOffer, resourceAddress: theOffers.Offers[0].offerId, isRidBased: true, @@ -68,7 +68,7 @@ func (c cosmosOffers) ReadThroughputIfExists( return ThroughputResponse{}, err } - azResponse, err = c.connection.sendGetRequest( + azResponse, err = c.client.sendGetRequest( path, ctx, operationContext, @@ -95,7 +95,7 @@ func (c cosmosOffers) ReplaceThroughputIfExists( readRequestCharge := readResponse.RequestCharge readResponse.ThroughputProperties.offer = properties.offer - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeOffer, resourceAddress: readResponse.ThroughputProperties.offerId, isRidBased: true, @@ -106,7 +106,7 @@ func (c cosmosOffers) ReplaceThroughputIfExists( return ThroughputResponse{}, err } - azResponse, err := c.connection.sendPutRequest( + azResponse, err := c.client.sendPutRequest( path, ctx, readResponse.ThroughputProperties, diff --git a/sdk/data/azcosmos/cosmos_operation_context.go b/sdk/data/azcosmos/cosmos_operation_context.go deleted file mode 100644 index 49692a4b28ce..000000000000 --- a/sdk/data/azcosmos/cosmos_operation_context.go +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -type cosmosOperationContext struct { - resourceType resourceType - resourceAddress string - isRidBased bool -} diff --git a/sdk/data/azcosmos/emulator_cosmos_container_test.go b/sdk/data/azcosmos/emulator_cosmos_container_test.go index 420938662384..bf314f3b660c 100644 --- a/sdk/data/azcosmos/emulator_cosmos_container_test.go +++ b/sdk/data/azcosmos/emulator_cosmos_container_test.go @@ -15,7 +15,7 @@ func TestContainerCRUD(t *testing.T) { database := emulatorTests.createDatabase(t, context.TODO(), client, "containerCRUD") defer emulatorTests.deleteDatabase(t, context.TODO(), database) properties := ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"/id"}, }, @@ -33,12 +33,12 @@ func TestContainerCRUD(t *testing.T) { throughput := NewManualThroughputProperties(400) - resp, err := database.CreateContainer(context.TODO(), properties, &CreateContainerOptions{ThroughputProperties: throughput}) + resp, err := database.CreateContainer(context.TODO(), properties, &CreateContainerOptions{ThroughputProperties: &throughput}) if err != nil { t.Fatalf("Failed to create container: %v", err) } - if resp.ContainerProperties.Id != properties.Id { + if resp.ContainerProperties.ID != properties.ID { t.Errorf("Unexpected id match: %v", resp.ContainerProperties) } @@ -46,14 +46,14 @@ func TestContainerCRUD(t *testing.T) { t.Errorf("Unexpected path match: %v", resp.ContainerProperties) } - container := resp.ContainerProperties.Container + container, _ := database.NewContainer("aContainer") resp, err = container.Read(context.TODO(), nil) if err != nil { t.Fatalf("Failed to read container: %v", err) } updatedProperties := ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"/id"}, }, @@ -75,9 +75,9 @@ func TestContainerCRUD(t *testing.T) { t.Fatalf("Failed to read throughput: %v", err) } - mt, err := throughputResponse.ThroughputProperties.ManualThroughput() - if err != nil { - t.Errorf("Failed to read throughput: %v", err) + mt, hasManualThroughput := throughputResponse.ThroughputProperties.ManualThroughput() + if !hasManualThroughput { + t.Fatalf("Expected manual throughput to be available") } if mt != 400 { @@ -85,7 +85,7 @@ func TestContainerCRUD(t *testing.T) { } newScale := NewManualThroughputProperties(500) - _, err = container.ReplaceThroughput(context.TODO(), *newScale, nil) + _, err = container.ReplaceThroughput(context.TODO(), newScale, nil) if err != nil { t.Errorf("Failed to read throughput: %v", err) } @@ -103,7 +103,7 @@ func TestContainerAutoscaleCRUD(t *testing.T) { database := emulatorTests.createDatabase(t, context.TODO(), client, "containerCRUD") defer emulatorTests.deleteDatabase(t, context.TODO(), database) properties := ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"/id"}, }, @@ -121,12 +121,12 @@ func TestContainerAutoscaleCRUD(t *testing.T) { throughput := NewAutoscaleThroughputProperties(5000) - resp, err := database.CreateContainer(context.TODO(), properties, &CreateContainerOptions{ThroughputProperties: throughput}) + resp, err := database.CreateContainer(context.TODO(), properties, &CreateContainerOptions{ThroughputProperties: &throughput}) if err != nil { t.Fatalf("Failed to create container: %v", err) } - if resp.ContainerProperties.Id != properties.Id { + if resp.ContainerProperties.ID != properties.ID { t.Errorf("Unexpected id match: %v", resp.ContainerProperties) } @@ -134,7 +134,7 @@ func TestContainerAutoscaleCRUD(t *testing.T) { t.Errorf("Unexpected path match: %v", resp.ContainerProperties) } - container := resp.ContainerProperties.Container + container, _ := database.NewContainer("aContainer") resp, err = container.Read(context.TODO(), nil) if err != nil { t.Fatalf("Failed to read container: %v", err) @@ -145,9 +145,9 @@ func TestContainerAutoscaleCRUD(t *testing.T) { t.Fatalf("Failed to read throughput: %v", err) } - maxru, err := throughputResponse.ThroughputProperties.AutoscaleMaxThroughput() - if err != nil { - t.Errorf("Failed to read throughput: %v", err) + maxru, hasAutoscale := throughputResponse.ThroughputProperties.AutoscaleMaxThroughput() + if !hasAutoscale { + t.Fatalf("Expected autoscale throughput to be available") } if maxru != 5000 { @@ -155,7 +155,7 @@ func TestContainerAutoscaleCRUD(t *testing.T) { } newScale := NewAutoscaleThroughputProperties(10000) - _, err = container.ReplaceThroughput(context.TODO(), *newScale, nil) + _, err = container.ReplaceThroughput(context.TODO(), newScale, nil) if err != nil { t.Errorf("Failed to read throughput: %v", err) } diff --git a/sdk/data/azcosmos/emulator_cosmos_database_test.go b/sdk/data/azcosmos/emulator_cosmos_database_test.go index 3566b2e69b5a..a517109cbefb 100644 --- a/sdk/data/azcosmos/emulator_cosmos_database_test.go +++ b/sdk/data/azcosmos/emulator_cosmos_database_test.go @@ -12,32 +12,33 @@ func TestDatabaseCRUD(t *testing.T) { emulatorTests := newEmulatorTests(t) client := emulatorTests.getClient(t) - database := DatabaseProperties{Id: "baseDbTest"} + database := DatabaseProperties{ID: "baseDbTest"} resp, err := client.CreateDatabase(context.TODO(), database, nil) if err != nil { t.Fatalf("Failed to create database: %v", err) } - if resp.DatabaseProperties.Id != database.Id { + if resp.DatabaseProperties.ID != database.ID { t.Errorf("Unexpected id match: %v", resp.DatabaseProperties) } - resp, err = resp.DatabaseProperties.Database.Read(context.TODO(), nil) + db, _ := client.NewDatabase("baseDbTest") + resp, err = db.Read(context.TODO(), nil) if err != nil { t.Fatalf("Failed to read database: %v", err) } - if resp.DatabaseProperties.Id != database.Id { + if resp.DatabaseProperties.ID != database.ID { t.Errorf("Unexpected id match: %v", resp.DatabaseProperties) } - throughputResponse, err := resp.DatabaseProperties.Database.ReadThroughput(context.TODO(), nil) + throughputResponse, err := db.ReadThroughput(context.TODO(), nil) if err == nil { t.Fatalf("Expected not finding throughput but instead got : %v", throughputResponse) } - resp, err = resp.DatabaseProperties.Database.Delete(context.TODO(), nil) + resp, err = db.Delete(context.TODO(), nil) if err != nil { t.Fatalf("Failed to delete database: %v", err) } @@ -47,34 +48,35 @@ func TestDatabaseWithOfferCRUD(t *testing.T) { emulatorTests := newEmulatorTests(t) client := emulatorTests.getClient(t) - database := DatabaseProperties{Id: "baseDbTest"} + database := DatabaseProperties{ID: "baseDbTest"} tp := NewManualThroughputProperties(400) - resp, err := client.CreateDatabase(context.TODO(), database, &CreateDatabaseOptions{ThroughputProperties: tp}) + resp, err := client.CreateDatabase(context.TODO(), database, &CreateDatabaseOptions{ThroughputProperties: &tp}) if err != nil { t.Fatalf("Failed to create database: %v", err) } - if resp.DatabaseProperties.Id != database.Id { + if resp.DatabaseProperties.ID != database.ID { t.Errorf("Unexpected id match: %v", resp.DatabaseProperties) } - resp, err = resp.DatabaseProperties.Database.Read(context.TODO(), nil) + db, _ := client.NewDatabase("baseDbTest") + resp, err = db.Read(context.TODO(), nil) if err != nil { t.Fatalf("Failed to read database: %v", err) } - if resp.DatabaseProperties.Id != database.Id { + if resp.DatabaseProperties.ID != database.ID { t.Errorf("Unexpected id match: %v", resp.DatabaseProperties) } - throughputResponse, err := resp.DatabaseProperties.Database.ReadThroughput(context.TODO(), nil) + throughputResponse, err := db.ReadThroughput(context.TODO(), nil) if err != nil { t.Fatalf("Failed to read throughput: %v", err) } - mt, err := throughputResponse.ThroughputProperties.ManualThroughput() - if err != nil { - t.Errorf("Failed to read throughput: %v", err) + mt, hasManualThroughput := throughputResponse.ThroughputProperties.ManualThroughput() + if !hasManualThroughput { + t.Fatalf("Expected manual throughput to be available") } if mt != 400 { @@ -82,12 +84,12 @@ func TestDatabaseWithOfferCRUD(t *testing.T) { } newScale := NewManualThroughputProperties(500) - _, err = resp.DatabaseProperties.Database.ReplaceThroughput(context.TODO(), *newScale, nil) + _, err = db.ReplaceThroughput(context.TODO(), newScale, nil) if err != nil { t.Errorf("Failed to read throughput: %v", err) } - resp, err = resp.DatabaseProperties.Database.Delete(context.TODO(), nil) + resp, err = db.Delete(context.TODO(), nil) if err != nil { t.Fatalf("Failed to delete database: %v", err) } diff --git a/sdk/data/azcosmos/emulator_cosmos_item_test.go b/sdk/data/azcosmos/emulator_cosmos_item_test.go index c1569967ddec..b4d2e90c1f8d 100644 --- a/sdk/data/azcosmos/emulator_cosmos_item_test.go +++ b/sdk/data/azcosmos/emulator_cosmos_item_test.go @@ -16,13 +16,13 @@ func TestItemCRUD(t *testing.T) { database := emulatorTests.createDatabase(t, context.TODO(), client, "itemCRUD") defer emulatorTests.deleteDatabase(t, context.TODO(), database) properties := ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: PartitionKeyDefinition{ Paths: []string{"/id"}, }, } - resp, err := database.CreateContainer(context.TODO(), properties, nil) + _, err := database.CreateContainer(context.TODO(), properties, nil) if err != nil { t.Fatalf("Failed to create container: %v", err) } @@ -32,13 +32,15 @@ func TestItemCRUD(t *testing.T) { "value": "2", } - container := resp.ContainerProperties.Container - pk, err := NewPartitionKey("1") + container, _ := database.NewContainer("aContainer") + pk := NewPartitionKeyString("1") + + marshalled, err := json.Marshal(item) if err != nil { - t.Fatalf("Failed to create pk: %v", err) + t.Fatal(err) } - itemResponse, err := container.CreateItem(context.TODO(), *pk, item, nil) + itemResponse, err := container.CreateItem(context.TODO(), pk, marshalled, nil) if err != nil { t.Fatalf("Failed to create item: %v", err) } @@ -52,7 +54,7 @@ func TestItemCRUD(t *testing.T) { t.Fatalf("Expected empty response, got %v", itemResponse.Value) } - itemResponse, err = container.ReadItem(context.TODO(), *pk, "1", nil) + itemResponse, err = container.ReadItem(context.TODO(), pk, "1", nil) if err != nil { t.Fatalf("Failed to read item: %v", err) } @@ -74,7 +76,11 @@ func TestItemCRUD(t *testing.T) { } item["value"] = "3" - itemResponse, err = container.ReplaceItem(context.TODO(), *pk, "1", item, &ItemOptions{EnableContentResponseOnWrite: true}) + marshalled, err = json.Marshal(item) + if err != nil { + t.Fatal(err) + } + itemResponse, err = container.ReplaceItem(context.TODO(), pk, "1", marshalled, &ItemOptions{EnableContentResponseOnWrite: true}) if err != nil { t.Fatalf("Failed to replace item: %v", err) } @@ -96,7 +102,11 @@ func TestItemCRUD(t *testing.T) { } item["value"] = "4" - itemResponse, err = container.UpsertItem(context.TODO(), *pk, item, &ItemOptions{EnableContentResponseOnWrite: true}) + marshalled, err = json.Marshal(item) + if err != nil { + t.Fatal(err) + } + itemResponse, err = container.UpsertItem(context.TODO(), pk, marshalled, &ItemOptions{EnableContentResponseOnWrite: true}) if err != nil { t.Fatalf("Failed to upsert item: %v", err) } @@ -117,7 +127,7 @@ func TestItemCRUD(t *testing.T) { t.Fatalf("Expected value to be 4, got %v", itemResponseBody["value"]) } - itemResponse, err = container.DeleteItem(context.TODO(), *pk, "1", nil) + itemResponse, err = container.DeleteItem(context.TODO(), pk, "1", nil) if err != nil { t.Fatalf("Failed to replace item: %v", err) } diff --git a/sdk/data/azcosmos/emulator_tests.go b/sdk/data/azcosmos/emulator_tests.go index 97b825488a5f..1cdfabb2787f 100644 --- a/sdk/data/azcosmos/emulator_tests.go +++ b/sdk/data/azcosmos/emulator_tests.go @@ -40,24 +40,25 @@ func (e *emulatorTests) createDatabase( t *testing.T, ctx context.Context, client *Client, - dbName string) *Database { - database := DatabaseProperties{Id: dbName} + dbName string) DatabaseClient { + database := DatabaseProperties{ID: dbName} resp, err := client.CreateDatabase(ctx, database, nil) if err != nil { t.Fatalf("Failed to create database: %v", err) } - if resp.DatabaseProperties.Id != database.Id { + if resp.DatabaseProperties.ID != database.ID { t.Errorf("Unexpected id match: %v", resp.DatabaseProperties) } - return resp.DatabaseProperties.Database + db, _ := client.NewDatabase(dbName) + return db } func (e *emulatorTests) deleteDatabase( t *testing.T, ctx context.Context, - database *Database) { + database DatabaseClient) { _, err := database.Delete(ctx, nil) if err != nil { t.Fatalf("Failed to delete database: %v", err) diff --git a/sdk/data/azcosmos/example_test.go b/sdk/data/azcosmos/example_test.go index fb458a66ed9e..8db61f8c9b3d 100644 --- a/sdk/data/azcosmos/example_test.go +++ b/sdk/data/azcosmos/example_test.go @@ -36,16 +36,18 @@ func Example() { // ===== 1. Creating a database ===== - databaseName := azcosmos.DatabaseProperties{Id: "databaseName"} - database, err := client.CreateDatabase(ctx, databaseName, nil) + databaseProperties := azcosmos.DatabaseProperties{ID: "databaseName"} + databaseResponse, err := client.CreateDatabase(ctx, databaseProperties, nil) if err != nil { log.Fatal(err) } + log.Printf("Database created. ActivityId %s", databaseResponse.ActivityId) + // ===== 2. Creating a container ===== properties := azcosmos.ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{ Paths: []string{"/myPartitionKey"}, }, @@ -53,12 +55,22 @@ func Example() { throughput := azcosmos.NewManualThroughputProperties(400) - resp, err := database.DatabaseProperties.Database.CreateContainer(ctx, properties, &azcosmos.CreateContainerOptions{ThroughputProperties: throughput}) + database, err := client.NewDatabase("databaseName") + if err != nil { + log.Fatal(err) + } + + resp, err := database.CreateContainer(ctx, properties, &azcosmos.CreateContainerOptions{ThroughputProperties: &throughput}) if err != nil { log.Fatal(err) } - container := resp.ContainerProperties.Container + log.Printf("Container created. ActivityId %s", resp.ActivityId) + + container, err := client.NewContainer("databaseName", "aContainer") + if err != nil { + log.Fatal(err) + } // ===== 3. Update container properties ===== @@ -68,11 +80,10 @@ func Example() { } updatedProperties := azcosmos.ContainerProperties{ - Id: "aContainer", + ID: "aContainer", PartitionKeyDefinition: azcosmos.PartitionKeyDefinition{ Paths: []string{"/myPartitionKey"}, }, - ETag: "someEtag", IndexingPolicy: &azcosmos.IndexingPolicy{ IncludedPaths: []azcosmos.IncludedPath{}, ExcludedPaths: []azcosmos.ExcludedPath{}, @@ -93,30 +104,30 @@ func Example() { log.Fatal(err) } - manualThroughput, err := throughputResponse.ThroughputProperties.ManualThroughput() - if err != nil { - log.Fatal(err) + manualThroughput, hasManual := throughputResponse.ThroughputProperties.ManualThroughput() + if !hasManual { + log.Fatal("Expected to have manual throughput") } fmt.Printf("Container is provisioned with %v RU/s", manualThroughput) // Replace manual throughput property newScale := azcosmos.NewManualThroughputProperties(500) - _, err = container.ReplaceThroughput(ctx, *newScale, nil) + _, err = container.ReplaceThroughput(ctx, newScale, nil) if err != nil { log.Fatal(err) } // Migrate from manual throughput to autoscale newScale = azcosmos.NewAutoscaleThroughputProperties(10000) - replaceThroughputResponse, err := container.ReplaceThroughput(ctx, *newScale, nil) + replaceThroughputResponse, err := container.ReplaceThroughput(ctx, newScale, nil) if err != nil { log.Fatal(err) } - autoscaleMaxThroughputResponse, err := replaceThroughputResponse.ThroughputProperties.AutoscaleMaxThroughput() - if err != nil { - log.Fatal(err) + autoscaleMaxThroughputResponse, hasAutoscale := replaceThroughputResponse.ThroughputProperties.AutoscaleMaxThroughput() + if !hasAutoscale { + log.Fatal("Expected to have autoscale throughput") } fmt.Printf("Container is provisioned with %v RU/s", autoscaleMaxThroughputResponse) @@ -124,7 +135,7 @@ func Example() { // ===== 4. Item CRUD ===== // Items in an Azure Cosmos container are uniquely identified by their id and partition key value. - pk, err := azcosmos.NewPartitionKey("newPartitionKey") + pk := azcosmos.NewPartitionKeyString("newPartitionKey") item := map[string]string{ "id": "1", @@ -132,19 +143,24 @@ func Example() { "myPartitionKey": "newPartitionKey", } + marshalled, err := json.Marshal(item) + if err != nil { + log.Fatal(err) + } + // Create item. - itemResponse, err := container.CreateItem(ctx, *pk, item, nil) + itemResponse, err := container.CreateItem(ctx, pk, marshalled, nil) if err != nil { log.Fatal(err) } // Read item. - itemResponse, err = container.ReadItem(ctx, *pk, "1", nil) + itemResponse, err = container.ReadItem(ctx, pk, "1", nil) if err != nil { log.Fatal(err) } - var itemResponseBody map[string]interface{} + var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) if err != nil { log.Fatal(err) @@ -152,28 +168,32 @@ func Example() { // Modify some property itemResponseBody["value"] = "newValue" + marshalledReplace, err := json.Marshal(itemResponseBody) + if err != nil { + log.Fatal(err) + } // Replace item - itemResponse, err = container.ReplaceItem(ctx, *pk, "1", itemResponseBody, nil) + itemResponse, err = container.ReplaceItem(ctx, pk, "1", marshalledReplace, nil) if err != nil { log.Fatal(err) } // Delete item. - itemResponse, err = container.DeleteItem(ctx, *pk, "1", nil) + itemResponse, err = container.DeleteItem(ctx, pk, "1", nil) if err != nil { log.Fatal(err) } // ===== 5. Session consistency ===== - itemResponse, err = container.UpsertItem(ctx, *pk, item, nil) + itemResponse, err = container.UpsertItem(ctx, pk, marshalled, nil) if err != nil { log.Fatal(err) } itemSessionToken := itemResponse.SessionToken - itemResponse, err = container.ReadItem(ctx, *pk, "1", &azcosmos.ItemOptions{SessionToken: itemSessionToken}) + itemResponse, err = container.ReadItem(ctx, pk, "1", &azcosmos.ItemOptions{SessionToken: itemSessionToken}) if err != nil { log.Fatal(err) } @@ -184,12 +204,12 @@ func Example() { // Check the item response status code. If an error is imitted and the response code is 412 then retry operation. numberRetry := 3 err = retryOptimisticConcurrency(numberRetry, 1000*time.Millisecond, func() (bool, error) { - itemResponse, err = container.ReadItem(ctx, *pk, "1", nil) + itemResponse, err = container.ReadItem(ctx, pk, "1", nil) if err != nil { log.Fatal(err) } - var itemResponseBody map[string]interface{} + var itemResponseBody map[string]string err = json.Unmarshal(itemResponse.Value, &itemResponseBody) if err != nil { log.Fatal(err) @@ -198,9 +218,14 @@ func Example() { // Change a value in the item response body. itemResponseBody["value"] = "newValue" + marshalledReplace, err := json.Marshal(itemResponseBody) + if err != nil { + log.Fatal(err) + } + // Replace with Etag etag := itemResponse.ETag - itemResponse, err = container.ReplaceItem(ctx, *pk, "1", itemResponseBody, &azcosmos.ItemOptions{IfMatchEtag: &etag}) + itemResponse, err = container.ReplaceItem(ctx, pk, "1", marshalledReplace, &azcosmos.ItemOptions{IfMatchEtag: &etag}) var httpErr azcore.HTTPResponse return (errors.As(err, &httpErr) && itemResponse.RawResponse.StatusCode == 412), err diff --git a/sdk/data/azcosmos/go.mod b/sdk/data/azcosmos/go.mod index e7b91b970732..1d01b67de5e0 100644 --- a/sdk/data/azcosmos/go.mod +++ b/sdk/data/azcosmos/go.mod @@ -4,7 +4,9 @@ go 1.16 require ( github.com/Azure/azure-sdk-for-go v57.3.0+incompatible - github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 - github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0 + github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1 + github.com/davecgh/go-spew v1.1.1 // indirect github.com/stretchr/testify v1.7.0 + gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect ) diff --git a/sdk/data/azcosmos/go.sum b/sdk/data/azcosmos/go.sum index df703095a287..6c817e79efe9 100644 --- a/sdk/data/azcosmos/go.sum +++ b/sdk/data/azcosmos/go.sum @@ -1,30 +1,39 @@ github.com/Azure/azure-sdk-for-go v57.3.0+incompatible h1:zxuxvsRYSXcowMuT/P5b7o6YJYuGYP74jCb9IvlgOLA= github.com/Azure/azure-sdk-for-go v57.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= -github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= -github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= -github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= -github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0 h1:KQgdWmEOmaJKxaUUZwHAYh12t+b+ZJf8q3friycK1kA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.20.0/go.mod h1:ZPW/Z0kLCTdDZaDbYTetxc9Cxl/2lNqxYHYNOF2bti0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1 h1:BUYIbDf/mMZ8945v3QkG3OuqGVyS4Iek0AOLwdRAYoc= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.8.1/go.mod h1:KLF4gFr6DcKFZwSuH8w8yEK6DpFl3LP5rhdvAb7Yz5I= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/dnaeon/go-vcr v1.1.0/go.mod h1:M7tiix8f0r6mKKJ3Yq/kqU1OYf3MnfmBWVbPx/yU9ko= github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= diff --git a/sdk/data/azcosmos/partition_key.go b/sdk/data/azcosmos/partition_key.go index dfad7db1ea75..1290e79b1c44 100644 --- a/sdk/data/azcosmos/partition_key.go +++ b/sdk/data/azcosmos/partition_key.go @@ -3,41 +3,38 @@ package azcosmos -import "encoding/json" +import ( + "encoding/json" +) // PartitionKey represents a logical partition key value. type PartitionKey struct { - isNone bool - partitionKeyInternal *partitionKeyInternal + values []interface{} } -// NewPartitionKeyNone creates a partition key value for non-partitioned containers. -func NewPartitionKeyNone() *PartitionKey { - return &PartitionKey{ - isNone: true, - partitionKeyInternal: nonePartitionKey, +func NewPartitionKeyString(value string) PartitionKey { + components := []interface{}{value} + return PartitionKey{ + values: components, } } -// NewPartitionKey creates a new partition key. -// value - the partition key value. -func NewPartitionKey(value interface{}) (*PartitionKey, error) { - pkInternal, err := newPartitionKeyInternal([]interface{}{value}) - if err != nil { - return nil, err +func NewPartitionKeyBool(value bool) PartitionKey { + components := []interface{}{value} + return PartitionKey{ + values: components, } - return &PartitionKey{ - partitionKeyInternal: pkInternal, - isNone: false, - }, nil } -func (pk *PartitionKey) toJsonString() (string, error) { - if pk.isNone { - return "", nil +func NewPartitionKeyNumber(value float64) PartitionKey { + components := []interface{}{value} + return PartitionKey{ + values: components, } +} - res, err := json.Marshal(pk.partitionKeyInternal) +func (pk *PartitionKey) toJsonString() (string, error) { + res, err := json.Marshal(pk.values) if err != nil { return "", err } diff --git a/sdk/data/azcosmos/partition_key_definition.go b/sdk/data/azcosmos/partition_key_definition.go index 65268d81dab4..f77d3bdff8c0 100644 --- a/sdk/data/azcosmos/partition_key_definition.go +++ b/sdk/data/azcosmos/partition_key_definition.go @@ -9,5 +9,5 @@ type PartitionKeyDefinition struct { // Paths returns the list of partition key paths of the container. Paths []string `json:"paths"` // Version returns the version of the hash partitioning of the container. - Version PartitionKeyDefinitionVersion `json:"version,omitempty"` + Version int `json:"version,omitempty"` } diff --git a/sdk/data/azcosmos/partition_key_definition_version.go b/sdk/data/azcosmos/partition_key_definition_version.go deleted file mode 100644 index 2e5db610ec2b..000000000000 --- a/sdk/data/azcosmos/partition_key_definition_version.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -// Version of the hash partitioning -type PartitionKeyDefinitionVersion int - -const ( - // Original version of hash partitioning. - PartitionKeyDefinitionVersion1 PartitionKeyDefinitionVersion = 1 - // Enhanced version of hash partitioning - offers better distribution of long partition keys and uses less storage. - PartitionKeyDefinitionVersion2 PartitionKeyDefinitionVersion = 2 -) - -// Returns a list of available consistency levels -func PartitionKeyDefinitionVersionValues() []PartitionKeyDefinitionVersion { - return []PartitionKeyDefinitionVersion{PartitionKeyDefinitionVersion1, PartitionKeyDefinitionVersion2} -} - -func (c PartitionKeyDefinitionVersion) ToPtr() *PartitionKeyDefinitionVersion { - return &c -} diff --git a/sdk/data/azcosmos/partition_key_internal.go b/sdk/data/azcosmos/partition_key_internal.go deleted file mode 100644 index fc548614538c..000000000000 --- a/sdk/data/azcosmos/partition_key_internal.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "encoding/json" - "fmt" -) - -var ( - nonePartitionKey = &partitionKeyInternal{components: nil} - emptyPartitionKey = &partitionKeyInternal{components: []interface{}{}} - undefinedPartitionKey = &partitionKeyInternal{components: []interface{}{&partitionKeyUndefinedComponent{}}} -) - -type partitionKeyInternal struct { - components []interface{} -} - -func newPartitionKeyInternal(values []interface{}) (*partitionKeyInternal, error) { - components := make([]interface{}, len(values)) - for i, v := range values { - var component interface{} - switch val := v.(type) { - case nil: - component = &partitionKeyNullComponent{} - case bool: - component = &partitionKeyBoolComponent{val} - case string: - component = &partitionKeyStringComponent{val} - case int: - component = &partitionKeyNumberComponent{float64(val)} - case int8: - component = &partitionKeyNumberComponent{float64(val)} - case int16: - component = &partitionKeyNumberComponent{float64(val)} - case int32: - component = &partitionKeyNumberComponent{float64(val)} - case int64: - component = &partitionKeyNumberComponent{float64(val)} - case uint: - component = &partitionKeyNumberComponent{float64(val)} - case uint8: - component = &partitionKeyNumberComponent{float64(val)} - case uint16: - component = &partitionKeyNumberComponent{float64(val)} - case uint32: - component = &partitionKeyNumberComponent{float64(val)} - case uint64: - component = &partitionKeyNumberComponent{float64(val)} - case float32: - component = &partitionKeyNumberComponent{float64(val)} - case float64: - component = &partitionKeyNumberComponent{val} - default: - return nil, fmt.Errorf("PartitionKey can only be a string, bool, or a number: '%T'", v) - } - - components[i] = component - } - - return &partitionKeyInternal{components: components}, nil -} - -func (p *partitionKeyInternal) MarshalJSON() ([]byte, error) { - return json.Marshal(p.components) -} - -type partitionKeyNumberComponent struct { - value float64 -} - -func (p *partitionKeyNumberComponent) MarshalJSON() ([]byte, error) { - return json.Marshal(p.value) -} - -type partitionKeyBoolComponent struct { - value bool -} - -func (p *partitionKeyBoolComponent) MarshalJSON() ([]byte, error) { - return json.Marshal(p.value) -} - -type partitionKeyStringComponent struct { - value string -} - -func (p *partitionKeyStringComponent) MarshalJSON() ([]byte, error) { - return json.Marshal(p.value) -} - -type partitionKeyNullComponent struct{} - -func (p *partitionKeyNullComponent) MarshalJSON() ([]byte, error) { - return []byte("null"), nil -} - -type partitionKeyUndefinedComponent struct{} - -func (p *partitionKeyUndefinedComponent) MarshalJSON() ([]byte, error) { - return []byte("{}"), nil -} diff --git a/sdk/data/azcosmos/partition_key_test.go b/sdk/data/azcosmos/partition_key_test.go index d9b1545d222d..44096f5444c5 100644 --- a/sdk/data/azcosmos/partition_key_test.go +++ b/sdk/data/azcosmos/partition_key_test.go @@ -8,57 +8,23 @@ import ( "testing" ) -func TestInvalidPartitionKeyValues(t *testing.T) { - invalidTypes := []interface{}{ - complex64(0), - complex128(0), - []byte(nil), - []byte{}, - // whatever other type of struct - cosmosOperationContext{}, +func TestSerialization(t *testing.T) { + validTypes := map[string]PartitionKey{ + "[10.5]": NewPartitionKeyNumber(float64(10.5)), + "[10]": NewPartitionKeyNumber(float64(10)), + "[\"some string\"]": NewPartitionKeyString("some string"), + "[true]": NewPartitionKeyBool(true), + "[false]": NewPartitionKeyBool(false), } - for _, invalidType := range invalidTypes { - _, err := NewPartitionKey(invalidType) - if err == nil { - t.Errorf("Expected error for partition key type %v", invalidType) - } - } -} - -func TestValidPartitionKeyValues(t *testing.T) { - validTypes := map[interface{}]string{ - nil: "[null]", - true: "[true]", - false: "[false]", - "some string": "[\"some string\"]", - int(10): "[10]", - int8(10): "[10]", - int16(10): "[10]", - int32(10): "[10]", - int64(10): "[10]", - uint(10): "[10]", - uint8(10): "[10]", - uint16(10): "[10]", - uint32(10): "[10]", - uint64(10): "[10]", - float32(10.5): "[10.5]", - float64(10.5): "[10.5]", - } - - for validType, expectedSerialization := range validTypes { - pk, err := NewPartitionKey(validType) - if err != nil { - t.Errorf("Expected success for partition key type %v and got %v", validType, err) - } - - if len(pk.partitionKeyInternal.components) != 1 { - t.Errorf("Expected partition key to have 1 component, but it has %v", len(pk.partitionKeyInternal.components)) + for expectedSerialization, pk := range validTypes { + if len(pk.values) != 1 { + t.Errorf("Expected partition key to have 1 component, but it has %v", len(pk.values)) } serialization, err := pk.toJsonString() if err != nil { - t.Errorf("Failed to serialize PK for %v, got %v", validType, err) + t.Errorf("Failed to serialize PK for %v, got %v", pk, err) } if serialization != expectedSerialization { @@ -67,65 +33,39 @@ func TestValidPartitionKeyValues(t *testing.T) { } } -func TestPartitionKeyEmpty(t *testing.T) { - pk := &PartitionKey{ - partitionKeyInternal: emptyPartitionKey, - } +func TestPartitionKeyEquality(t *testing.T) { + pk := NewPartitionKeyNumber(float64(10.5)) + pk2 := NewPartitionKeyNumber(float64(10.5)) - serialization, err := pk.toJsonString() - if err != nil { - t.Errorf("Failed to serialize PK, %v", err) + if !reflect.DeepEqual(pk, pk2) { + t.Errorf("Expected %v to equal %v", pk, pk2) } - if serialization != "[]" { - t.Errorf("Expected serialization [], but got %v", serialization) - } -} + pk = NewPartitionKeyNumber(float64(50)) + pk2 = NewPartitionKeyNumber(float64(50)) -func TestPartitionKeyUndefined(t *testing.T) { - pk := &PartitionKey{ - partitionKeyInternal: undefinedPartitionKey, + if !reflect.DeepEqual(pk, pk2) { + t.Errorf("Expected %v to equal %v", pk, pk2) } - serialization, err := pk.toJsonString() - if err != nil { - t.Errorf("Failed to serialize PK, %v", err) - } + pk = NewPartitionKeyBool(true) + pk2 = NewPartitionKeyBool(true) - if serialization != "[{}]" { - t.Errorf("Expected serialization [{}], but got %v", serialization) + if !reflect.DeepEqual(pk, pk2) { + t.Errorf("Expected %v to equal %v", pk, pk2) } -} -func TestPartitionKeyEquality(t *testing.T) { - validTypes := []interface{}{ - nil, - true, - false, - "some string", - int(10), - int8(10), - int16(10), - int32(10), - int64(10), - uint(10), - uint8(10), - uint16(10), - uint32(10), - uint64(10), - float32(10.5), - float64(10.5), + pk = NewPartitionKeyBool(false) + pk2 = NewPartitionKeyBool(false) + + if !reflect.DeepEqual(pk, pk2) { + t.Errorf("Expected %v to equal %v", pk, pk2) } - for _, validType := range validTypes { - pk, err := NewPartitionKey(validType) - if err != nil { - t.Errorf("Expected success for partition key type %v and got %v", validType, err) - } + pk = NewPartitionKeyString("some string") + pk2 = NewPartitionKeyString("some string") - pk2, _ := NewPartitionKey(validType) - if !reflect.DeepEqual(pk, pk2) { - t.Errorf("Expected %v to equal %v", pk, pk2) - } + if !reflect.DeepEqual(pk, pk2) { + t.Errorf("Expected %v to equal %v", pk, pk2) } } diff --git a/sdk/data/azcosmos/resource_throttle_retry_policy.go b/sdk/data/azcosmos/resource_throttle_retry_policy.go deleted file mode 100644 index c27566857c0f..000000000000 --- a/sdk/data/azcosmos/resource_throttle_retry_policy.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "net/http" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" - azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/internal/log" -) - -const ( - defaultResourceThrottleRetryPolicyMaxWaitTime time.Duration = 60 * time.Second - defaultResourceThrottleRetryPolicyRetryCount int = 9 -) - -// resourceThrottleRetryPolicy retries on HTTP 429. -type resourceThrottleRetryPolicy struct { - MaxWaitTime time.Duration - MaxRetryCount int -} - -func newResourceThrottleRetryPolicy(o *CosmosClientOptions) *resourceThrottleRetryPolicy { - if o.RateLimitedRetry == nil { - return &resourceThrottleRetryPolicy{ - MaxWaitTime: defaultResourceThrottleRetryPolicyMaxWaitTime, - MaxRetryCount: defaultResourceThrottleRetryPolicyRetryCount} - } - - return &resourceThrottleRetryPolicy{ - MaxWaitTime: o.RateLimitedRetry.MaxRetryWaitTime, - MaxRetryCount: o.RateLimitedRetry.MaxRetryAttempts} -} - -func (p *resourceThrottleRetryPolicy) Do(req *policy.Request) (*http.Response, error) { - // Policy disabled - if p.MaxRetryCount == 0 { - return req.Next() - } - - var resp *http.Response - var err error - var cumulativeWaitTime time.Duration - for attempts := 0; attempts < p.MaxRetryCount; attempts++ { - err = req.RewindBody() - if err != nil { - return resp, err - } - - resp, err = req.Next() - if err != nil || resp.StatusCode != http.StatusTooManyRequests { - return resp, err - } - - retryAfter := resp.Header.Get(cosmosHeaderRetryAfter) - retryAfterDuration := parseRetryAfter(retryAfter) - cumulativeWaitTime += retryAfterDuration - - if retryAfterDuration > p.MaxWaitTime || cumulativeWaitTime > p.MaxWaitTime { - return resp, err - } - - // drain before retrying so nothing is leaked - azruntime.Drain(resp) - - select { - case <-time.After(retryAfterDuration): - // retry - case <-req.Raw().Context().Done(): - err = req.Raw().Context().Err() - log.Writef(log.RetryPolicy, "ResourceThrottleRetryPolicy abort due to %v", err) - return resp, err - } - } - - return resp, err -} - -func parseRetryAfter(retryAfter string) time.Duration { - if retryAfter == "" { - return 0 - } - - retryAfterDuration, err := time.ParseDuration(retryAfter + "ms") - if err != nil { - return 0 - } - - return retryAfterDuration -} diff --git a/sdk/data/azcosmos/resource_throttle_retry_policy_test.go b/sdk/data/azcosmos/resource_throttle_retry_policy_test.go deleted file mode 100644 index b796046ccc54..000000000000 --- a/sdk/data/azcosmos/resource_throttle_retry_policy_test.go +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "context" - "net/http" - "testing" - "time" - - azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" - "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" -) - -func TestDefaultRetryConfiguration(t *testing.T) { - cosmosClientOptions := &CosmosClientOptions{} - retryPolicy := newResourceThrottleRetryPolicy(cosmosClientOptions) - if retryPolicy.MaxRetryCount != defaultResourceThrottleRetryPolicyRetryCount { - t.Errorf("Expected the MaxRetryCount to match the default but got, but got %d", retryPolicy.MaxRetryCount) - } - - if retryPolicy.MaxWaitTime != defaultResourceThrottleRetryPolicyMaxWaitTime { - t.Errorf("Expected the MaxWaitTime to match the default but got, but got %s", retryPolicy.MaxWaitTime) - } -} - -func TestCustomRetryConfiguration(t *testing.T) { - cosmosClientOptions := &CosmosClientOptions{} - maxRetryCount := 5 - maxRetryDuration, _ := time.ParseDuration("1s") - cosmosClientOptions.RateLimitedRetry = &CosmosClientOptionsRateLimitedRetry{ - MaxRetryAttempts: maxRetryCount, - MaxRetryWaitTime: maxRetryDuration, - } - retryPolicy := newResourceThrottleRetryPolicy(cosmosClientOptions) - if retryPolicy.MaxRetryCount != maxRetryCount { - t.Errorf("Expected the MaxRetryCount to match the %d but got, but got %d", maxRetryCount, retryPolicy.MaxRetryCount) - } - - if retryPolicy.MaxWaitTime != maxRetryDuration { - t.Errorf("Expected the MaxWaitTime to match the %s but got, but got %s", maxRetryDuration, retryPolicy.MaxWaitTime) - } -} - -func TestRetryOn429WithCustomCount(t *testing.T) { - cosmosClientOptions := &CosmosClientOptions{} - maxRetryCount := 5 - maxRetryDuration, _ := time.ParseDuration("5s") - cosmosClientOptions.RateLimitedRetry = &CosmosClientOptionsRateLimitedRetry{ - MaxRetryAttempts: maxRetryCount, - MaxRetryWaitTime: maxRetryDuration, - } - retryPolicy := newResourceThrottleRetryPolicy(cosmosClientOptions) - - srv, close := mock.NewTLSServer() - defer close() - srv.SetResponse(mock.WithStatusCode(http.StatusTooManyRequests)) - - pl := azruntime.NewPipeline(srv, retryPolicy) - req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - resp, _ := pl.Do(req) - if resp.StatusCode != http.StatusTooManyRequests { - t.Fatalf("unexpected status code: %d", resp.StatusCode) - } - if r := srv.Requests(); r != maxRetryCount { - t.Fatalf("wrong request count, got %d expected %d", r, maxRetryCount) - } -} - -func TestRetryOn429WithCustomTime(t *testing.T) { - cosmosClientOptions := &CosmosClientOptions{} - maxRetryCount := 5 - maxRetryDuration, _ := time.ParseDuration("1s") - cosmosClientOptions.RateLimitedRetry = &CosmosClientOptionsRateLimitedRetry{ - MaxRetryAttempts: maxRetryCount, - MaxRetryWaitTime: maxRetryDuration, - } - retryPolicy := newResourceThrottleRetryPolicy(cosmosClientOptions) - - srv, close := mock.NewTLSServer() - defer close() - // Should wait only 1 second and when the retry comes, it should stop - srv.SetResponse(mock.WithStatusCode(http.StatusTooManyRequests), mock.WithHeader(cosmosHeaderRetryAfter, "1000")) - - pl := azruntime.NewPipeline(srv, retryPolicy) - req, err := azruntime.NewRequest(context.Background(), http.MethodGet, srv.URL()) - if err != nil { - t.Fatalf("unexpected error: %v", err) - } - - resp, _ := pl.Do(req) - if resp.StatusCode != http.StatusTooManyRequests { - t.Fatalf("unexpected status code: %d", resp.StatusCode) - } - if r := srv.Requests(); r != 2 { - t.Fatalf("wrong request count, got %d expected %d", r, 2) - } -} diff --git a/sdk/data/azcosmos/shared_key_credential.go b/sdk/data/azcosmos/shared_key_credential.go index d17f29b03530..9e10c96b6afd 100644 --- a/sdk/data/azcosmos/shared_key_credential.go +++ b/sdk/data/azcosmos/shared_key_credential.go @@ -20,12 +20,12 @@ import ( // KeyCredential creates an immutable KeyCredential containing the // account's primary or secondary key. -func NewKeyCredential(accountKey string) (*KeyCredential, error) { +func NewKeyCredential(accountKey string) (KeyCredential, error) { c := KeyCredential{} if err := c.Update(accountKey); err != nil { - return nil, err + return c, err } - return &c, nil + return c, nil } // KeyCredential contains an account's name and its primary or secondary key. @@ -53,7 +53,7 @@ func (c *KeyCredential) computeHMACSHA256(s string) (base64String string) { } func (c *KeyCredential) buildCanonicalizedAuthHeaderFromRequest(req *policy.Request) (string, error) { - var opValues cosmosOperationContext + var opValues pipelineRequestOptions value := "" if req.OperationValue(&opValues) { @@ -88,10 +88,10 @@ func (c *KeyCredential) buildCanonicalizedAuthHeader(method, resourceType, resou } type sharedKeyCredPolicy struct { - cred *KeyCredential + cred KeyCredential } -func newSharedKeyCredPolicy(cred *KeyCredential) *sharedKeyCredPolicy { +func newSharedKeyCredPolicy(cred KeyCredential) *sharedKeyCredPolicy { s := &sharedKeyCredPolicy{ cred: cred, } @@ -117,7 +117,7 @@ func (s *sharedKeyCredPolicy) Do(req *policy.Request) (*http.Response, error) { response, err := req.Next() if err != nil && response != nil && response.StatusCode == http.StatusForbidden { // Service failed to authenticate request, log it - log.Write(log.Response, "===== HTTP Forbidden status, Authorization:\n"+authHeader+"\n=====\n") + log.Write(log.EventResponse, "===== HTTP Forbidden status, Authorization:\n"+authHeader+"\n=====\n") } return response, err } diff --git a/sdk/data/azcosmos/shared_key_credential_test.go b/sdk/data/azcosmos/shared_key_credential_test.go index 55e50639eee5..bacb67c993d1 100644 --- a/sdk/data/azcosmos/shared_key_credential_test.go +++ b/sdk/data/azcosmos/shared_key_credential_test.go @@ -63,7 +63,7 @@ func Test_buildCanonicalizedAuthHeaderFromRequest(t *testing.T) { expected := url.QueryEscape(fmt.Sprintf("type=%s&ver=%s&sig=%s", tokenType, version, signature)) req, _ := azruntime.NewRequest(context.TODO(), http.MethodGet, "http://localhost") - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeDatabase, resourceAddress: "dbs/testdb", } @@ -95,7 +95,7 @@ func Test_buildCanonicalizedAuthHeaderFromRequestWithRid(t *testing.T) { expected := url.QueryEscape(fmt.Sprintf("type=%s&ver=%s&sig=%s", tokenType, version, signature)) req, _ := azruntime.NewRequest(context.TODO(), http.MethodGet, "http://localhost") - operationContext := cosmosOperationContext{ + operationContext := pipelineRequestOptions{ resourceType: resourceTypeDatabase, resourceAddress: "dbs/Rid", isRidBased: true, diff --git a/sdk/data/azcosmos/throughput_properties.go b/sdk/data/azcosmos/throughput_properties.go index 6009c1520284..104ff17f6fe5 100644 --- a/sdk/data/azcosmos/throughput_properties.go +++ b/sdk/data/azcosmos/throughput_properties.go @@ -8,6 +8,7 @@ import ( "encoding/json" "fmt" "strconv" + "time" "github.com/Azure/azure-sdk-for-go/sdk/azcore" "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" @@ -18,9 +19,10 @@ const ( ) // ThroughputProperties describes the throughput configuration of a resource. +// It must be initialized through the available constructors. type ThroughputProperties struct { - ETag azcore.ETag - LastModified *UnixTime + ETag *azcore.ETag + LastModified time.Time version string offerType string @@ -32,8 +34,8 @@ type ThroughputProperties struct { // NewManualThroughputProperties returns a ThroughputProperties object with the given throughput in manual mode. // throughput - the throughput in RU/s -func NewManualThroughputProperties(throughput int) *ThroughputProperties { - return &ThroughputProperties{ +func NewManualThroughputProperties(throughput int32) ThroughputProperties { + return ThroughputProperties{ version: offerVersion2, offer: newManualOffer(throughput), } @@ -42,8 +44,8 @@ func NewManualThroughputProperties(throughput int) *ThroughputProperties { // NewAutoscaleThroughputPropertiesWithIncrement returns a ThroughputProperties object with the given max throughput on autoscale mode. // maxThroughput - the max throughput in RU/s // incrementPercentage - the auto upgrade max throughput increment percentage -func NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput int, incrementPercentage int) *ThroughputProperties { - return &ThroughputProperties{ +func NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput int32, incrementPercentage int32) ThroughputProperties { + return ThroughputProperties{ version: offerVersion2, offer: newAutoscaleOfferWithIncrement(startingMaxThroughput, incrementPercentage), } @@ -51,8 +53,8 @@ func NewAutoscaleThroughputPropertiesWithIncrement(startingMaxThroughput int, in // NewAutoscaleThroughputProperties returns a ThroughputProperties object with the given max throughput on autoscale mode. // maxThroughput - the max throughput in RU/s -func NewAutoscaleThroughputProperties(startingMaxThroughput int) *ThroughputProperties { - return &ThroughputProperties{ +func NewAutoscaleThroughputProperties(startingMaxThroughput int32) ThroughputProperties { + return ThroughputProperties{ version: offerVersion2, offer: newAutoscaleOffer(startingMaxThroughput), } @@ -79,7 +81,7 @@ func (tp *ThroughputProperties) MarshalJSON() ([]byte, error) { buffer.WriteString(fmt.Sprintf(",\"offerType\":\"%s\"", tp.offerType)) buffer.WriteString(fmt.Sprintf(",\"offerVersion\":\"%s\"", tp.version)) - if tp.ETag != "" { + if tp.ETag != nil { buffer.WriteString(",\"_etag\":") etag, err := json.Marshal(tp.ETag) if err != nil { @@ -92,13 +94,8 @@ func (tp *ThroughputProperties) MarshalJSON() ([]byte, error) { buffer.WriteString(fmt.Sprintf(",\"_self\":\"%s\"", tp.selfLink)) } - if tp.LastModified != nil { - buffer.WriteString(",\"_ts\":") - ts, err := json.Marshal(tp.LastModified) - if err != nil { - return nil, err - } - buffer.Write(ts) + if !tp.LastModified.IsZero() { + buffer.WriteString(fmt.Sprintf(",\"_ts\":%v", strconv.FormatInt(tp.LastModified.Unix(), 10))) } buffer.WriteString("}") @@ -143,9 +140,11 @@ func (tp *ThroughputProperties) UnmarshalJSON(b []byte) error { } if ts, ok := attributes["_ts"]; ok { - if err := json.Unmarshal(ts, &tp.LastModified); err != nil { + var timestamp int64 + if err := json.Unmarshal(ts, ×tamp); err != nil { return err } + tp.LastModified = time.Unix(timestamp, 0) } if id, ok := attributes["id"]; ok { @@ -164,21 +163,32 @@ func (tp *ThroughputProperties) UnmarshalJSON(b []byte) error { } // ManualThroughput returns the provisioned throughput in manual mode. -func (tp *ThroughputProperties) ManualThroughput() (int, error) { +func (tp *ThroughputProperties) ManualThroughput() (int32, bool) { if tp.offer.Throughput == nil { - return 0, fmt.Errorf("offer is not a manual offer") + return 0, false } - return *tp.offer.Throughput, nil + return *tp.offer.Throughput, true } // AutoscaleMaxThroughput returns the configured max throughput on autoscale mode. -func (tp *ThroughputProperties) AutoscaleMaxThroughput() (int, error) { +func (tp *ThroughputProperties) AutoscaleMaxThroughput() (int32, bool) { if tp.offer.AutoScale == nil { - return 0, fmt.Errorf("offer is not an autoscale offer") + return 0, false + } + + return tp.offer.AutoScale.MaxThroughput, true +} + +// AutoscaleIncrement returns the configured percent increment on autoscale mode. +func (tp *ThroughputProperties) AutoscaleIncrement() (int32, bool) { + if tp.offer.AutoScale == nil || + tp.offer.AutoScale.AutoscaleAutoUpgradeProperties == nil || + tp.offer.AutoScale.AutoscaleAutoUpgradeProperties.ThroughputPolicy == nil { + return 0, false } - return tp.offer.AutoScale.MaxThroughput, nil + return tp.offer.AutoScale.AutoscaleAutoUpgradeProperties.ThroughputPolicy.IncrementPercent, true } func (tp *ThroughputProperties) addHeadersToRequest(req *policy.Request) { @@ -187,24 +197,24 @@ func (tp *ThroughputProperties) addHeadersToRequest(req *policy.Request) { } if tp.offer.Throughput != nil { - req.Raw().Header.Add(cosmosHeaderOfferThroughput, strconv.Itoa(*tp.offer.Throughput)) + req.Raw().Header.Add(cosmosHeaderOfferThroughput, strconv.Itoa(int(*tp.offer.Throughput))) } else { req.Raw().Header.Add(cosmosHeaderOfferAutoscale, tp.offer.AutoScale.ToJsonString()) } } type offer struct { - Throughput *int `json:"offerThroughput,omitempty"` + Throughput *int32 `json:"offerThroughput,omitempty"` AutoScale *autoscaleSettings `json:"offerAutopilotSettings,omitempty"` } -func newManualOffer(throughput int) *offer { +func newManualOffer(throughput int32) *offer { return &offer{ Throughput: &throughput, } } -func newAutoscaleOfferWithIncrement(startingMaxThroughput int, incrementPercentage int) *offer { +func newAutoscaleOfferWithIncrement(startingMaxThroughput int32, incrementPercentage int32) *offer { return &offer{ AutoScale: &autoscaleSettings{ MaxThroughput: startingMaxThroughput, @@ -217,7 +227,7 @@ func newAutoscaleOfferWithIncrement(startingMaxThroughput int, incrementPercenta } } -func newAutoscaleOffer(startingMaxThroughput int) *offer { +func newAutoscaleOffer(startingMaxThroughput int32) *offer { return &offer{ AutoScale: &autoscaleSettings{ MaxThroughput: startingMaxThroughput, @@ -226,7 +236,7 @@ func newAutoscaleOffer(startingMaxThroughput int) *offer { } type autoscaleSettings struct { - MaxThroughput int `json:"maxThroughput,omitempty"` + MaxThroughput int32 `json:"maxThroughput,omitempty"` AutoscaleAutoUpgradeProperties *autoscaleAutoUpgradeProperties `json:"autoUpgradePolicy,omitempty"` } @@ -245,5 +255,5 @@ type autoscaleAutoUpgradeProperties struct { } type autoscaleThroughputPolicy struct { - IncrementPercent int `json:"incrementPercent,omitempty"` + IncrementPercent int32 `json:"incrementPercent,omitempty"` } diff --git a/sdk/data/azcosmos/throughput_properties_test.go b/sdk/data/azcosmos/throughput_properties_test.go index d16faecaf6e2..4fe56f5a3422 100644 --- a/sdk/data/azcosmos/throughput_properties_test.go +++ b/sdk/data/azcosmos/throughput_properties_test.go @@ -7,6 +7,8 @@ import ( "encoding/json" "testing" "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) func TestThroughputPropertiesManualRawSerialization(t *testing.T) { @@ -36,17 +38,17 @@ func TestThroughputPropertiesManualRawSerialization(t *testing.T) { t.Errorf("OfferId mismatch %v", otherProperties.offerId) } - if otherProperties.ETag != "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" { + if *otherProperties.ETag != "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" { t.Errorf("Etag mismatch %v", otherProperties.ETag) } - if otherProperties.LastModified.Time != nowAsUnix { - t.Errorf("Timestamp mismatch %v", otherProperties.LastModified.Time) + if otherProperties.LastModified != nowAsUnix { + t.Errorf("Timestamp mismatch %v", otherProperties.LastModified) } - mt, err := otherProperties.ManualThroughput() - if err != nil { - t.Fatal(err) + mt, isManual := otherProperties.ManualThroughput() + if !isManual { + t.Fatal("Expected to have manual throughput available") } if mt != 400 { @@ -55,18 +57,15 @@ func TestThroughputPropertiesManualRawSerialization(t *testing.T) { } func TestThroughputPropertiesManualE2ESerialization(t *testing.T) { - nowAsUnix := time.Now().Unix() - - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } + nowAsUnix := time.Unix(time.Now().Unix(), 0) + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") properties := NewManualThroughputProperties(400) properties.offerId = "HFln" properties.offerResourceId = "4SRTANCD3Dw=" - properties.ETag = "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" - properties.LastModified = &now - jsonString, err := json.Marshal(properties) + properties.ETag = &etag + properties.LastModified = nowAsUnix + jsonString, err := json.Marshal(&properties) if err != nil { t.Fatal(err) } @@ -93,17 +92,17 @@ func TestThroughputPropertiesManualE2ESerialization(t *testing.T) { t.Errorf("OfferId mismatch %v", otherProperties.offerId) } - if otherProperties.ETag != "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" { + if *otherProperties.ETag != etag { t.Errorf("Etag mismatch %v", otherProperties.ETag) } - if otherProperties.LastModified.Time != properties.LastModified.Time { - t.Errorf("Timestamp mismatch %v", otherProperties.LastModified.Time) + if otherProperties.LastModified != properties.LastModified { + t.Errorf("Timestamp mismatch %v", otherProperties.LastModified) } - mt, err := otherProperties.ManualThroughput() - if err != nil { - t.Fatal(err) + mt, isManual := otherProperties.ManualThroughput() + if !isManual { + t.Fatal("Expected to have manual throughput available") } if mt != 400 { @@ -111,19 +110,83 @@ func TestThroughputPropertiesManualE2ESerialization(t *testing.T) { } } -func TestThroughputPropertiesAutoscaleE2ESerialization(t *testing.T) { - nowAsUnix := time.Now().Unix() +func TestThroughputPropertiesAutoscaleWithIncrementE2ESerialization(t *testing.T) { + nowAsUnix := time.Unix(time.Now().Unix(), 0) + + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") + properties := NewAutoscaleThroughputPropertiesWithIncrement(400, 500) + properties.offerId = "HFln" + properties.offerResourceId = "4SRTANCD3Dw=" + properties.ETag = &etag + properties.LastModified = nowAsUnix + jsonString, err := json.Marshal(&properties) + if err != nil { + t.Fatal(err) + } + + otherProperties := &ThroughputProperties{} + err = json.Unmarshal(jsonString, otherProperties) + if err != nil { + t.Fatal(err, string(jsonString)) + } + + if otherProperties.offerType != "" { + t.Errorf("OfferType mismatch %v", otherProperties.offerType) + } + + if otherProperties.offerResourceId != "4SRTANCD3Dw=" { + t.Errorf("OfferResourceId mismatch %v", otherProperties.offerResourceId) + } + + if otherProperties.version != offerVersion2 { + t.Errorf("OfferVersion mismatch %v", otherProperties.version) + } + + if otherProperties.offerId != "HFln" { + t.Errorf("OfferId mismatch %v", otherProperties.offerId) + } + + if *otherProperties.ETag != etag { + t.Errorf("Etag mismatch %v", otherProperties.ETag) + } - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), + if otherProperties.LastModified != properties.LastModified { + t.Errorf("Timestamp mismatch %v", otherProperties.LastModified) + } + + at, hasAutoscale := otherProperties.AutoscaleMaxThroughput() + if !hasAutoscale { + t.Errorf("Expected to have autoscale") + } + + inc, hasAutoscale := otherProperties.AutoscaleIncrement() + if !hasAutoscale { + t.Errorf("Expected to have autoscale") + } + + if at != 400 { + t.Errorf("MaxThroughput mismatch %v", at) } + if inc != 500 { + t.Errorf("Increment mismatch %v", inc) + } + + if otherProperties.offer.AutoScale.AutoscaleAutoUpgradeProperties == nil { + t.Errorf("AutoscaleAutoUpgradeProperties mismatch %v", *otherProperties.offer.AutoScale.AutoscaleAutoUpgradeProperties) + } +} + +func TestThroughputPropertiesAutoscaleE2ESerialization(t *testing.T) { + nowAsUnix := time.Unix(time.Now().Unix(), 0) + + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") properties := NewAutoscaleThroughputProperties(400) properties.offerId = "HFln" properties.offerResourceId = "4SRTANCD3Dw=" - properties.ETag = "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" - properties.LastModified = &now - jsonString, err := json.Marshal(properties) + properties.ETag = &etag + properties.LastModified = nowAsUnix + jsonString, err := json.Marshal(&properties) if err != nil { t.Fatal(err) } @@ -150,17 +213,22 @@ func TestThroughputPropertiesAutoscaleE2ESerialization(t *testing.T) { t.Errorf("OfferId mismatch %v", otherProperties.offerId) } - if otherProperties.ETag != "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" { + if *otherProperties.ETag != etag { t.Errorf("Etag mismatch %v", otherProperties.ETag) } - if otherProperties.LastModified.Time != properties.LastModified.Time { - t.Errorf("Timestamp mismatch %v", otherProperties.LastModified.Time) + if otherProperties.LastModified != properties.LastModified { + t.Errorf("Timestamp mismatch %v", otherProperties.LastModified) } - at, err := otherProperties.AutoscaleMaxThroughput() - if err != nil { - t.Fatal(err) + at, hasAutoscale := otherProperties.AutoscaleMaxThroughput() + if !hasAutoscale { + t.Errorf("Expected to have autoscale") + } + + _, hasAutoscaleIncrement := otherProperties.AutoscaleIncrement() + if hasAutoscaleIncrement { + t.Errorf("Expected not to have autoscale increment") } if at != 400 { @@ -168,23 +236,20 @@ func TestThroughputPropertiesAutoscaleE2ESerialization(t *testing.T) { } if otherProperties.offer.AutoScale.AutoscaleAutoUpgradeProperties != nil { - t.Errorf("AutoscaleAutoUpgradeProperties mismatch %v", otherProperties.offer.AutoScale.AutoscaleAutoUpgradeProperties) + t.Errorf("AutoscaleAutoUpgradeProperties mismatch %v", *otherProperties.offer.AutoScale.AutoscaleAutoUpgradeProperties) } } func TestThroughputPropertiesAutoscaleIncrementE2ESerialization(t *testing.T) { - nowAsUnix := time.Now().Unix() - - now := UnixTime{ - Time: time.Unix(nowAsUnix, 0), - } + nowAsUnix := time.Unix(time.Now().Unix(), 0) + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") properties := NewAutoscaleThroughputPropertiesWithIncrement(400, 10) properties.offerId = "HFln" properties.offerResourceId = "4SRTANCD3Dw=" - properties.ETag = "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" - properties.LastModified = &now - jsonString, err := json.Marshal(properties) + properties.ETag = &etag + properties.LastModified = nowAsUnix + jsonString, err := json.Marshal(&properties) if err != nil { t.Fatal(err) } @@ -211,17 +276,17 @@ func TestThroughputPropertiesAutoscaleIncrementE2ESerialization(t *testing.T) { t.Errorf("OfferId mismatch %v", otherProperties.offerId) } - if otherProperties.ETag != "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" { + if *otherProperties.ETag != etag { t.Errorf("Etag mismatch %v", otherProperties.ETag) } - if otherProperties.LastModified.Time != properties.LastModified.Time { - t.Errorf("Timestamp mismatch %v", otherProperties.LastModified.Time) + if otherProperties.LastModified != properties.LastModified { + t.Errorf("Timestamp mismatch %v", otherProperties.LastModified) } - at, err := otherProperties.AutoscaleMaxThroughput() - if err != nil { - t.Fatal(err) + at, hasAutoscale := otherProperties.AutoscaleMaxThroughput() + if !hasAutoscale { + t.Errorf("Expected to have autoscale") } if at != 400 { diff --git a/sdk/data/azcosmos/throughput_request_options.go b/sdk/data/azcosmos/throughput_request_options.go index 160c40c8f5c8..a633492fc12b 100644 --- a/sdk/data/azcosmos/throughput_request_options.go +++ b/sdk/data/azcosmos/throughput_request_options.go @@ -3,23 +3,27 @@ package azcosmos +import ( + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + // ThroughputOptions includes options for throughput operations. type ThroughputOptions struct { - IfMatchEtag string - IfNoneMatchEtag string + IfMatchEtag *azcore.ETag + IfNoneMatchEtag *azcore.ETag } func (options *ThroughputOptions) toHeaders() *map[string]string { - if options.IfMatchEtag == "" && options.IfNoneMatchEtag == "" { + if options.IfMatchEtag == nil && options.IfNoneMatchEtag == nil { return nil } headers := make(map[string]string) - if options.IfMatchEtag != "" { - headers[headerIfMatch] = options.IfMatchEtag + if options.IfMatchEtag != nil { + headers[headerIfMatch] = string(*options.IfMatchEtag) } - if options.IfNoneMatchEtag != "" { - headers[headerIfNoneMatch] = options.IfNoneMatchEtag + if options.IfNoneMatchEtag != nil { + headers[headerIfNoneMatch] = string(*options.IfNoneMatchEtag) } return &headers } diff --git a/sdk/data/azcosmos/throughput_request_options_test.go b/sdk/data/azcosmos/throughput_request_options_test.go index 2887d6b3b373..30c413447a2c 100644 --- a/sdk/data/azcosmos/throughput_request_options_test.go +++ b/sdk/data/azcosmos/throughput_request_options_test.go @@ -5,6 +5,8 @@ package azcosmos import ( "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" ) func TestThroughputRequestOptionsToHeaders(t *testing.T) { @@ -13,18 +15,21 @@ func TestThroughputRequestOptionsToHeaders(t *testing.T) { t.Error("toHeaders should return nil") } - options.IfMatchEtag = "etag" - options.IfNoneMatchEtag = "noneetag" + etag := azcore.ETag("etag") + noneetag := azcore.ETag("noneetag") + options.IfMatchEtag = &etag + options.IfNoneMatchEtag = &noneetag + header := options.toHeaders() if header == nil { - t.Error("toHeaders should return non-nil") + t.Fatal("toHeaders should return non-nil") } headers := *header - if headers[headerIfMatch] != options.IfMatchEtag { + if headers[headerIfMatch] != string(*options.IfMatchEtag) { t.Errorf("IfMatchEtag not set matching expected %v got %v", options.IfMatchEtag, headers[headerIfMatch]) } - if headers[headerIfNoneMatch] != options.IfNoneMatchEtag { + if headers[headerIfNoneMatch] != string(*options.IfNoneMatchEtag) { t.Errorf("IfNoneMatchEtag not set matching expected %v got %v", options.IfNoneMatchEtag, headers[headerIfNoneMatch]) } } diff --git a/sdk/data/azcosmos/throughput_response_test.go b/sdk/data/azcosmos/throughput_response_test.go index e3f0cade795a..c894967b3162 100644 --- a/sdk/data/azcosmos/throughput_response_test.go +++ b/sdk/data/azcosmos/throughput_response_test.go @@ -9,16 +9,21 @@ import ( "net/http" "testing" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" azruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" "github.com/Azure/azure-sdk-for-go/sdk/internal/mock" ) func TestThroughputResponseParsing(t *testing.T) { properties := NewManualThroughputProperties(400) + + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") + properties.offerId = "HFln" properties.offerResourceId = "4SRTANCD3Dw=" - properties.ETag = "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" - jsonString, err := json.Marshal(properties) + properties.ETag = &etag + jsonString, err := json.Marshal(&properties) if err != nil { t.Fatal(err) } @@ -35,8 +40,7 @@ func TestThroughputResponseParsing(t *testing.T) { if err != nil { t.Fatal(err) } - - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) parsedResponse, err := newThroughputResponse(resp, nil) if err != nil { @@ -59,8 +63,8 @@ func TestThroughputResponseParsing(t *testing.T) { t.Fatalf("parsedResponse.ThroughputProperties.offerResourceId is %s, expected %s", parsedResponse.ThroughputProperties.offerResourceId, properties.offerResourceId) } - if parsedResponse.ThroughputProperties.ETag != properties.ETag { - t.Fatalf("parsedResponse.ThroughputProperties.ETag is %s, expected %s", parsedResponse.ThroughputProperties.ETag, properties.ETag) + if *parsedResponse.ThroughputProperties.ETag != *properties.ETag { + t.Fatalf("parsedResponse.ThroughputProperties.ETag is %s, expected %s", *parsedResponse.ThroughputProperties.ETag, *properties.ETag) } if parsedResponse.ActivityId != "someActivityId" { @@ -79,11 +83,12 @@ func TestThroughputResponseParsing(t *testing.T) { func TestThroughputResponseParsingWithPreviousRU(t *testing.T) { var queryRequestCharge float32 = 10.0 + etag := azcore.ETag("\"00000000-0000-0000-9b8c-8ea3e19601d7\"") properties := NewManualThroughputProperties(400) properties.offerId = "HFln" properties.offerResourceId = "4SRTANCD3Dw=" - properties.ETag = "\"00000000-0000-0000-9b8c-8ea3e19601d7\"" - jsonString, err := json.Marshal(properties) + properties.ETag = &etag + jsonString, err := json.Marshal(&properties) if err != nil { t.Fatal(err) } @@ -101,7 +106,7 @@ func TestThroughputResponseParsingWithPreviousRU(t *testing.T) { t.Fatal(err) } - pl := azruntime.NewPipeline(srv) + pl := azruntime.NewPipeline("azcosmostest", "v1.0.0", []policy.Policy{}, []policy.Policy{}, &policy.ClientOptions{Transport: srv}) resp, _ := pl.Do(req) parsedResponse, err := newThroughputResponse(resp, &queryRequestCharge) if err != nil { @@ -124,8 +129,8 @@ func TestThroughputResponseParsingWithPreviousRU(t *testing.T) { t.Fatalf("parsedResponse.ThroughputProperties.offerResourceId is %s, expected %s", parsedResponse.ThroughputProperties.offerResourceId, properties.offerResourceId) } - if parsedResponse.ThroughputProperties.ETag != properties.ETag { - t.Fatalf("parsedResponse.ThroughputProperties.ETag is %s, expected %s", parsedResponse.ThroughputProperties.ETag, properties.ETag) + if *parsedResponse.ThroughputProperties.ETag != *properties.ETag { + t.Fatalf("parsedResponse.ThroughputProperties.ETag is %s, expected %s", *parsedResponse.ThroughputProperties.ETag, *properties.ETag) } if parsedResponse.ActivityId != "someActivityId" { diff --git a/sdk/data/azcosmos/unixtime.go b/sdk/data/azcosmos/unixtime.go deleted file mode 100644 index d0c9a000185e..000000000000 --- a/sdk/data/azcosmos/unixtime.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azcosmos - -import ( - "encoding/json" - "strconv" - "time" -) - -type UnixTime struct { - time.Time -} - -func (u *UnixTime) UnmarshalJSON(b []byte) error { - var timestamp int64 - err := json.Unmarshal(b, ×tamp) - if err != nil { - return err - } - u.Time = time.Unix(timestamp, 0) - return nil -} - -func (u *UnixTime) MarshalJSON() ([]byte, error) { - return []byte(strconv.FormatInt(u.Time.Unix(), 10)), nil -} diff --git a/sdk/messaging/azservicebus/CHANGELOG.md b/sdk/messaging/azservicebus/CHANGELOG.md index 9c256f72e093..1dac65f96a7e 100644 --- a/sdk/messaging/azservicebus/CHANGELOG.md +++ b/sdk/messaging/azservicebus/CHANGELOG.md @@ -11,6 +11,8 @@ enough to fit into a single batch. - Receiving from sessions using a SessionReceiver, created using Client.AcceptSessionFor(Queue|Subscription) or Client.AcceptNextSessionFor(Queue|Subscription). +- Can now renew a message lock for a ReceivedMessage using Receiver.RenewMessageLock() +- Can now renew a session lock for a SessionReceiver using SessionReceiver.RenewSessionLock() ### Breaking Changes diff --git a/sdk/messaging/azservicebus/README.md b/sdk/messaging/azservicebus/README.md index 996b5adec0e6..88d0e40f3710 100644 --- a/sdk/messaging/azservicebus/README.md +++ b/sdk/messaging/azservicebus/README.md @@ -157,72 +157,8 @@ if !added { ### Receive messages -Once you've created a [Client][godoc_client] you can create a [Processor][godoc_processor], which will allow you to receive messages. - -The [Processor][godoc_processor] handles error recovery internally, making it a good fit for -applications where the intention is to stream and process events for an extended period -of time. - -> NOTE: Creating a `client` is covered in the ["Authenticate the client"](#authenticate-the-client) section of the readme. - -```go -processor, err := client.NewProcessorForQueue( - "", - &azservicebus.ProcessorOptions{ - // NOTE: this is a parameter you'll want to tune. It controls the number of - // active message `handleMessage` calls that the processor will allow at any time. - MaxConcurrentCalls: 1, - ReceiveMode: azservicebus.PeekLock, - ManualComplete: false, - }, -) -// or -// client.NewProcessorForSubscription("", "") - -if err != nil { - log.Fatalf("Failed to create the processor: %s", err.Error()) -} - -handleMessage := func(message *azservicebus.ReceivedMessage) error { - // This is where your logic for handling messages goes - yourLogicForProcessing(message) - return nil -} - -handleError := func(err error) { - // handleError will be called on errors that are noteworthy - // but the Processor internally will continue to attempt to - // recover. - - // NOTE: errors returned from `handleMessage` above will also be - // sent here, but do not affect the running of the Processor - // itself. - - // We'll just print these out, as they're informational and - // can indicate if there are longer lived problems that we might - // want to resolve manually (for instance, longer term network - // outages, or issues affecting your `handleMessage` handler) - log.Printf("Error: %s", err.Error()) -} - -err := processor.Start(context.TODO(), handleMessage, handleError) - -if err != nil { - log.Printf("Processor loop has exited: %s", err.Error()) -} - -err := processor.Close(context.TODO()) - -if err != nil { - log.Printf("Processor failed to close: %s", err.Error()) -} -``` - Once you've created a [Client][godoc_client] you can create a [Receiver][godoc_receiver], which will allow you to receive messages. -The [Receiver][godoc_receiver] is a good fit for applications that want to receive messages in fixed increments, rather than -continually streaming messages, as the [Processor][godoc_processor] does. - > NOTE: Creating a `client` is covered in the ["Authenticate the client"](#authenticate-the-client) section of the readme. ```go @@ -256,7 +192,7 @@ messages, err := receiver.ReceiveMessages(context.TODO(), ) if err != nil { - log.Fatalf("Failed to get messages: %s", err.Error()) + panic(err) } for _, message := range messages { @@ -266,7 +202,7 @@ for _, message := range messages { // For more information about settling messages: // https://docs.microsoft.com/azure/service-bus-messaging/message-transfers-locks-settlement#settling-receive-operations if err := receiver.CompleteMessage(message); err != nil { - log.Printf("Error completing message: %s", err.Error()) + panic(err) } } ``` @@ -274,25 +210,13 @@ for _, message := range messages { ### Dead letter queue The dead letter queue is a **sub-queue**. Each queue or subscription has its own dead letter queue. Dead letter queues store -messages that have been explicitly dead lettered via the [Processor.DeadLetterMessage][godoc_processor_deadlettermessage] -or [Receiver.DeadLetterMessage][godoc_receiver_deadlettermessage] functions. +messages that have been explicitly dead lettered using the [Receiver.DeadLetterMessage][godoc_receiver_deadlettermessage] function. -Opening a dead letter queue is just a configuration option when creating a [Processor][godoc_processor] or [Receiver][godoc_receiver]. +Opening a dead letter queue is just a configuration option when creating a [Receiver][godoc_receiver]. > NOTE: Creating a `client` is covered in the ["Authenticate the client"](#authenticate-the-client) section of the readme. ```go - -deadLetterReceiver, err := client.NewProcessorForQueue("", - &azservicebus.ProcessorOptions{ - SubQueue: azservicebus.SubQueueDeadLetter, - }) -// or -// client.NewProcessorForSubscription("", "", -// &azservicebus.ProcessorOptions{ -// SubQueue: azservicebus.SubQueueDeadLetter, -// }) - deadLetterReceiver, err := client.NewReceiverForQueue("", &azservicebus.ReceiverOptions{ SubQueue: azservicebus.SubQueueDeadLetter, @@ -304,7 +228,7 @@ deadLetterReceiver, err := client.NewReceiverForQueue("", // }) ``` -To see some example code for receiving messages using the Processor or Receiver see the ["Receive messages"](#receive-messages) sample. +To see some example code for receiving messages using the Receiver see the ["Receive messages"](#receive-messages) sample. ## Next steps @@ -332,8 +256,6 @@ If you'd like to contribute to this library, please read the [contributing guide [godoc_receiver]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Receiver [godoc_receiver_completemessage]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Receiver.CompleteMessage [godoc_receiver_deadlettermessage]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Receiver.DeadLetterMessage -[godoc_processor]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Processor -[godoc_processor_deadlettermessage]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Processor.DeadLetterMessage [godoc_newsender]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Client.NewSender [godoc_newreceiver_queue]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Client.NewReceiverForQueue [godoc_newreceiver_subscription]: https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/#Client.NewReceiverForSubscription diff --git a/sdk/messaging/azservicebus/admin_client_test.go b/sdk/messaging/azservicebus/admin_client_test.go index dd45681dcced..2cd2a639693d 100644 --- a/sdk/messaging/azservicebus/admin_client_test.go +++ b/sdk/messaging/azservicebus/admin_client_test.go @@ -198,7 +198,7 @@ func TestAdminClient_Queue_Forwarding(t *testing.T) { receiver, err := client.NewReceiverForQueue(forwardToQueueName, nil) require.NoError(t, err) - forwardedMessage, err := receiver.ReceiveMessage(context.Background(), nil) + forwardedMessage, err := receiver.receiveMessage(context.Background(), nil) require.NoError(t, err) require.EqualValues(t, "this message will be auto-forwarded", string(forwardedMessage.Body)) diff --git a/sdk/messaging/azservicebus/client.go b/sdk/messaging/azservicebus/client.go index 047699db35e0..82a1157bec59 100644 --- a/sdk/messaging/azservicebus/client.go +++ b/sdk/messaging/azservicebus/client.go @@ -16,7 +16,7 @@ import ( "github.com/devigned/tab" ) -// Client provides methods to create Sender, Receiver and Processor +// Client provides methods to create Sender and Receiver // instances to send and receive messages from Service Bus. type Client struct { config clientConfig @@ -120,34 +120,6 @@ func newClientImpl(config clientConfig, options *ClientOptions) (*Client, error) return client, err } -// NewProcessor creates a Processor for a queue. -func (client *Client) NewProcessorForQueue(queue string, options *ProcessorOptions) (*Processor, error) { - id, cleanupOnClose := client.getCleanupForCloseable() - - processor, err := newProcessor(client.namespace, &entity{Queue: queue}, cleanupOnClose, options) - - if err != nil { - return nil, err - } - - client.addCloseable(id, processor) - return processor, nil -} - -// NewProcessor creates a Processor for a subscription. -func (client *Client) NewProcessorForSubscription(topic string, subscription string, options *ProcessorOptions) (*Processor, error) { - id, cleanupOnClose := client.getCleanupForCloseable() - - processor, err := newProcessor(client.namespace, &entity{Topic: topic, Subscription: subscription}, cleanupOnClose, options) - - if err != nil { - return nil, err - } - - client.addCloseable(id, processor) - return processor, nil -} - // NewReceiver creates a Receiver for a queue. A receiver allows you to receive messages. func (client *Client) NewReceiverForQueue(queue string, options *ReceiverOptions) (*Receiver, error) { id, cleanupOnClose := client.getCleanupForCloseable() @@ -192,6 +164,7 @@ func (client *Client) NewSender(queueOrTopic string) (*Sender, error) { func (client *Client) AcceptSessionForQueue(ctx context.Context, queue string, sessionID string, options *SessionReceiverOptions) (*SessionReceiver, error) { id, cleanupOnClose := client.getCleanupForCloseable() sessionReceiver, err := newSessionReceiver( + ctx, &sessionID, client.namespace, &entity{Queue: queue}, @@ -215,6 +188,7 @@ func (client *Client) AcceptSessionForQueue(ctx context.Context, queue string, s func (client *Client) AcceptSessionForSubscription(ctx context.Context, topic string, subscription string, sessionID string, options *SessionReceiverOptions) (*SessionReceiver, error) { id, cleanupOnClose := client.getCleanupForCloseable() sessionReceiver, err := newSessionReceiver( + ctx, &sessionID, client.namespace, &entity{Topic: topic, Subscription: subscription}, @@ -238,6 +212,7 @@ func (client *Client) AcceptSessionForSubscription(ctx context.Context, topic st func (client *Client) AcceptNextSessionForQueue(ctx context.Context, queue string, options *SessionReceiverOptions) (*SessionReceiver, error) { id, cleanupOnClose := client.getCleanupForCloseable() sessionReceiver, err := newSessionReceiver( + ctx, nil, client.namespace, &entity{Queue: queue}, @@ -261,6 +236,7 @@ func (client *Client) AcceptNextSessionForQueue(ctx context.Context, queue strin func (client *Client) AcceptNextSessionForSubscription(ctx context.Context, topic string, subscription string, options *SessionReceiverOptions) (*SessionReceiver, error) { id, cleanupOnClose := client.getCleanupForCloseable() sessionReceiver, err := newSessionReceiver( + ctx, nil, client.namespace, &entity{Topic: topic, Subscription: subscription}, @@ -279,7 +255,7 @@ func (client *Client) AcceptNextSessionForSubscription(ctx context.Context, topi return sessionReceiver, nil } -// Close closes the current connection Service Bus as well as any Sender, Receiver or Processors created +// Close closes the current connection Service Bus as well as any Senders or Receivers created // using this client. func (client *Client) Close(ctx context.Context) error { var lastError error diff --git a/sdk/messaging/azservicebus/client_test.go b/sdk/messaging/azservicebus/client_test.go index b4a55f99fcbb..3510a5bec19d 100644 --- a/sdk/messaging/azservicebus/client_test.go +++ b/sdk/messaging/azservicebus/client_test.go @@ -139,7 +139,7 @@ func TestNewClientUnitTests(t *testing.T) { require.EqualValues(t, 1, ns.AMQPLinks.Closed) client, ns = setupClient() - _, err = client.NewProcessorForQueue("hello", nil) + _, err = newProcessorForQueue(client, "hello", nil) require.NoError(t, err) require.EqualValues(t, 1, len(client.links)) @@ -149,7 +149,7 @@ func TestNewClientUnitTests(t *testing.T) { require.EqualValues(t, 1, ns.AMQPLinks.Closed) client, ns = setupClient() - _, err = client.NewProcessorForSubscription("hello", "world", nil) + _, err = newProcessorForSubscription(client, "hello", "world", nil) require.NoError(t, err) require.EqualValues(t, 1, len(client.links)) diff --git a/sdk/messaging/azservicebus/example_processor_test.go b/sdk/messaging/azservicebus/example_processor_test.go deleted file mode 100644 index ac146a5918ae..000000000000 --- a/sdk/messaging/azservicebus/example_processor_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package azservicebus_test - -import ( - "context" - "log" - - "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus" -) - -var processor *azservicebus.Processor - -func ExampleClient_NewProcessorForSubscription() { - processor, err = client.NewProcessorForSubscription( - "exampleTopic", - "exampleSubscription", - &azservicebus.ProcessorOptions{ - // NOTE: this is a parameter you'll want to tune. It controls the number of - // active message `handleMessage` calls that the processor will allow at any time. - MaxConcurrentCalls: 1, - ReceiveMode: azservicebus.PeekLock, - ManualComplete: false, - }, - ) - exitOnError("Failed to create Processor", err) -} - -func ExampleClient_NewProcessorForQueue() { - processor, err = client.NewProcessorForQueue( - "exampleQueue", - &azservicebus.ProcessorOptions{ - // NOTE: this is a parameter you'll want to tune. It controls the number of - // active message `handleMessage` calls that the processor will allow at any time. - MaxConcurrentCalls: 1, - ReceiveMode: azservicebus.PeekLock, - ManualComplete: false, - }, - ) - - exitOnError("Failed to create Processor", err) -} - -func ExampleProcessor_Start() { - handleMessage := func(message *azservicebus.ReceivedMessage) error { - // This is where your logic for handling messages goes - yourLogicForProcessing(message) - - // 'AutoComplete' (enabled by default, and controlled by `ProcessorWithAutoComplete`) - // will use this return value to determine how it should settle your message. - // - // Non-nil errors will cause your message to be Abandon()'d. - // Nil errors will cause your message to be Complete'd. - return nil - } - - handleError := func(err error) { - // handleError will be called on errors that are noteworthy - // but the Processor internally will continue to attempt to - // recover. - - // NOTE: errors returned from `handleMessage` above will also be - // sent here, but do not affect the running of the Processor - // itself. - - // We'll just print these out, as they're informational and - // can indicate if there are longer lived problems that we might - // want to resolve manually (for instance, longer term network - // outages, or issues affecting your `handleMessage` handler) - log.Printf("Error: %s", err.Error()) - } - - err = processor.Start(context.TODO(), handleMessage, handleError) - exitOnError("Failed to start Processor", err) -} - -func ExampleProcessor_Close() { - err = processor.Close(context.TODO()) - exitOnError("Processor failed to close", err) -} diff --git a/sdk/messaging/azservicebus/example_session_receiver_test.go b/sdk/messaging/azservicebus/example_session_receiver_test.go index a6e2e3fb0835..69cfef0eafe0 100644 --- a/sdk/messaging/azservicebus/example_session_receiver_test.go +++ b/sdk/messaging/azservicebus/example_session_receiver_test.go @@ -13,13 +13,15 @@ func ExampleClient_AcceptSessionForQueue() { exitOnError("Failed to create session receiver", err) // session receivers function the same as any other receiver - message, err := sessionReceiver.ReceiveMessage(context.TODO(), nil) + messages, err := sessionReceiver.ReceiveMessages(context.TODO(), 5, nil) exitOnError("Failed to receive a message", err) - err = sessionReceiver.CompleteMessage(context.TODO(), message) - exitOnError("Failed to complete message", err) + for _, message := range messages { + err = sessionReceiver.CompleteMessage(context.TODO(), message) + exitOnError("Failed to complete message", err) - fmt.Printf("Received message from session ID \"%s\" and completed it", *message.SessionID) + fmt.Printf("Received message from session ID \"%s\" and completed it", *message.SessionID) + } } func ExampleClient_AcceptNextSessionForQueue() { diff --git a/sdk/messaging/azservicebus/example_shared_test.go b/sdk/messaging/azservicebus/example_shared_test.go index ad9d3da62a48..ded982a85986 100644 --- a/sdk/messaging/azservicebus/example_shared_test.go +++ b/sdk/messaging/azservicebus/example_shared_test.go @@ -21,10 +21,6 @@ func exitOnError(message string, err error) { log.Panicf("(error in example): %s: %s", message, err.Error()) } -func yourLogicForProcessing(message *azservicebus.ReceivedMessage) { - log.Printf("Message received") -} - // these just make it so our examples don't have to have a bunch of extra declarations // for unrelated entities. var connectionString string diff --git a/sdk/messaging/azservicebus/internal/constants.go b/sdk/messaging/azservicebus/internal/constants.go index 9d50d45af9db..0982a5502024 100644 --- a/sdk/messaging/azservicebus/internal/constants.go +++ b/sdk/messaging/azservicebus/internal/constants.go @@ -9,7 +9,7 @@ type ReceiveMode int const ( // PeekLock will lock messages as they are received and can be settled - // using the Receiver or Processor's (Complete|Abandon|DeadLetter|Defer)Message + // using the Receiver's (Complete|Abandon|DeadLetter|Defer)Message // functions. PeekLock ReceiveMode = 0 // ReceiveAndDelete will delete messages as they are received. diff --git a/sdk/messaging/azservicebus/internal/mgmt.go b/sdk/messaging/azservicebus/internal/mgmt.go index 2a4cd859b9b2..06780994688e 100644 --- a/sdk/messaging/azservicebus/internal/mgmt.go +++ b/sdk/messaging/azservicebus/internal/mgmt.go @@ -55,6 +55,9 @@ type MgmtClient interface { ScheduleMessages(ctx context.Context, enqueueTime time.Time, messages ...*amqp.Message) ([]int64, error) CancelScheduled(ctx context.Context, seq ...int64) error + + RenewLocks(ctx context.Context, linkName string, lockTokens []amqp.UUID) ([]time.Time, error) + RenewSessionLock(ctx context.Context, sessionID string) (time.Time, error) } func newMgmtClient(ctx context.Context, links AMQPLinks, ns NamespaceForMgmtClient) (MgmtClient, error) { @@ -391,14 +394,10 @@ func (mc *mgmtClient) PeekMessages(ctx context.Context, fromSequenceNumber int64 // RenewLocks renews the locks in a single 'com.microsoft:renew-lock' operation. // NOTE: this function assumes all the messages received on the same link. -func (mc *mgmtClient) RenewLocks(ctx context.Context, linkName string, lockTokens ...*amqp.UUID) (err error) { +func (mc *mgmtClient) RenewLocks(ctx context.Context, linkName string, lockTokens []amqp.UUID) ([]time.Time, error) { ctx, span := tracing.StartConsumerSpanFromContext(ctx, tracing.SpanRenewLock, Version) defer span.End() - if len(lockTokens) == 0 { - return nil - } - renewRequestMsg := &amqp.Message{ ApplicationProperties: map[string]interface{}{ "operation": "com.microsoft:renew-lock", @@ -413,18 +412,73 @@ func (mc *mgmtClient) RenewLocks(ctx context.Context, linkName string, lockToken } response, err := mc.doRPCWithRetry(ctx, renewRequestMsg, 3, 1*time.Second) + if err != nil { tab.For(ctx).Error(err) - return err + return nil, err } if response.Code != 200 { err := fmt.Errorf("error renewing locks: %v", response.Description) tab.For(ctx).Error(err) - return err + return nil, err } - return nil + // extract the new lock renewal times from the response + // response.Message. + + val, ok := response.Message.Value.(map[string]interface{}) + if !ok { + return nil, NewErrIncorrectType("Message.Value", map[string]interface{}{}, response.Message.Value) + } + + expirations, ok := val["expirations"] + + if !ok { + return nil, NewErrIncorrectType("Message.Value[\"expirations\"]", map[string]interface{}{}, response.Message.Value) + } + + asTimes, ok := expirations.([]time.Time) + + if !ok { + return nil, NewErrIncorrectType("Message.Value[\"expirations\"] as times", map[string]interface{}{}, response.Message.Value) + } + + return asTimes, nil +} + +// RenewSessionLocks renews a session lock. +func (mc *mgmtClient) RenewSessionLock(ctx context.Context, sessionID string) (time.Time, error) { + body := map[string]interface{}{ + "session-id": sessionID, + } + + msg := &amqp.Message{ + Value: body, + ApplicationProperties: map[string]interface{}{ + "operation": "com.microsoft:renew-session-lock", + }, + } + + resp, err := mc.doRPCWithRetry(ctx, msg, 5, 5*time.Second) + + if err != nil { + return time.Time{}, err + } + + m, ok := resp.Message.Value.(map[string]interface{}) + + if !ok { + return time.Time{}, NewErrIncorrectType("Message.Value", map[string]interface{}{}, resp.Message.Value) + } + + lockedUntil, ok := m["expiration"].(time.Time) + + if !ok { + return time.Time{}, NewErrIncorrectType("Message.Value[\"expiration\"] as times", time.Time{}, resp.Message.Value) + } + + return lockedUntil, nil } // SendDisposition allows you settle a message using the management link, rather than via your diff --git a/sdk/messaging/azservicebus/message.go b/sdk/messaging/azservicebus/message.go index 23c0af06bcfb..7365c5e0ed30 100644 --- a/sdk/messaging/azservicebus/message.go +++ b/sdk/messaging/azservicebus/message.go @@ -15,7 +15,7 @@ import ( ) type ( - // ReceivedMessage is a received message from a Client.NewReceiver() or Client.NewProcessor(). + // ReceivedMessage is a received message from a Client.NewReceiver(). ReceivedMessage struct { Message diff --git a/sdk/messaging/azservicebus/messageSettler_test.go b/sdk/messaging/azservicebus/messageSettler_test.go index 2b760a74a1c3..96aba645c4cb 100644 --- a/sdk/messaging/azservicebus/messageSettler_test.go +++ b/sdk/messaging/azservicebus/messageSettler_test.go @@ -23,7 +23,7 @@ func TestMessageSettlementUsingReceiver(t *testing.T) { require.NoError(t, err) var msg *ReceivedMessage - msg, err = receiver.ReceiveMessage(ctx, nil) + msg, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 1, msg.DeliveryCount) @@ -31,7 +31,7 @@ func TestMessageSettlementUsingReceiver(t *testing.T) { err = receiver.AbandonMessage(context.Background(), msg) require.NoError(t, err) - msg, err = receiver.ReceiveMessage(ctx, nil) + msg, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 2, msg.DeliveryCount) @@ -39,7 +39,7 @@ func TestMessageSettlementUsingReceiver(t *testing.T) { err = receiver.DeadLetterMessage(ctx, msg, nil) require.NoError(t, err) - msg, err = deadLetterReceiver.ReceiveMessage(ctx, nil) + msg, err = deadLetterReceiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 2, msg.DeliveryCount) @@ -55,7 +55,7 @@ func TestMessageSettlementUsingReceiver(t *testing.T) { err = deadLetterReceiver.AbandonMessage(ctx, msg) require.NoError(t, err) - msg, err = deadLetterReceiver.ReceiveMessage(ctx, nil) + msg, err = deadLetterReceiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 2, msg.DeliveryCount) @@ -85,7 +85,7 @@ func TestDeferredMessages(t *testing.T) { // BUG: we're timing out here, even though our abandon should have put the message // back into the queue. It appears that settlement methods don't work on messages // that have been received as deferred. - msg, err = receiver.ReceiveMessage(ctx, nil) + msg, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.NotNil(t, msg) }) @@ -106,7 +106,7 @@ func TestDeferredMessages(t *testing.T) { err := receiver.DeferMessage(ctx, msg) require.NoError(t, err) - msg, err = receiver.ReceiveDeferredMessage(ctx, *msg.SequenceNumber) + msg, err = receiver.receiveDeferredMessage(ctx, *msg.SequenceNumber) require.NoError(t, err) err = receiver.CompleteMessage(ctx, msg) @@ -131,7 +131,7 @@ func TestDeferredMessage_DeadLettering(t *testing.T) { require.NoError(t, err) // check that the message made it to the dead letter queue - msg, err = deadLetterReceiver.ReceiveMessage(context.Background(), nil) + msg, err = deadLetterReceiver.receiveMessage(context.Background(), nil) require.NoError(t, err) require.NotNil(t, msg) @@ -165,21 +165,21 @@ func TestMessageSettlementUsingOnlyBackupSettlement(t *testing.T) { actualSettler.onlyDoBackupSettlement = true var msg *ReceivedMessage - msg, err = receiver.ReceiveMessage(ctx, nil) + msg, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 1, msg.DeliveryCount) err = receiver.AbandonMessage(context.Background(), msg) require.NoError(t, err) - msg, err = receiver.ReceiveMessage(ctx, nil) + msg, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 2, msg.DeliveryCount) err = receiver.DeadLetterMessage(ctx, msg, nil) require.NoError(t, err) - msg, err = deadLetterReceiver.ReceiveMessage(ctx, nil) + msg, err = deadLetterReceiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, 2, msg.DeliveryCount) @@ -250,7 +250,7 @@ func (testStuff *testStuff) deferMessageForTest(t *testing.T) *ReceivedMessage { require.NoError(t, err) var msg *ReceivedMessage - msg, err = testStuff.Receiver.ReceiveMessage(context.Background(), nil) + msg, err = testStuff.Receiver.receiveMessage(context.Background(), nil) require.NoError(t, err) require.NotNil(t, msg) @@ -259,7 +259,7 @@ func (testStuff *testStuff) deferMessageForTest(t *testing.T) *ReceivedMessage { err = testStuff.Receiver.DeferMessage(context.Background(), msg) require.NoError(t, err) - msg, err = testStuff.Receiver.ReceiveDeferredMessage(context.Background(), *msg.SequenceNumber) + msg, err = testStuff.Receiver.receiveDeferredMessage(context.Background(), *msg.SequenceNumber) require.NoError(t, err) return msg diff --git a/sdk/messaging/azservicebus/migrationguide.md b/sdk/messaging/azservicebus/migrationguide.md index dfde98fee6c4..fbc6a3af1e90 100644 --- a/sdk/messaging/azservicebus/migrationguide.md +++ b/sdk/messaging/azservicebus/migrationguide.md @@ -67,63 +67,22 @@ sender.SendMessage(ctx, batch) ### Processing and receiving messages -Receiving has split into two types: -- the [Processor](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus#Processor), for continuously streaming messages to a user provided callback (similar to `Listen`). -- the [Receiver](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus#Receiver), for receiving of messages in batches. +Receiving has been changed to be pull-based, rather than using callbacks. -The `Processor` replaces the `Listen` functions on the previous Receiver type that could be created from a `Queue` or `Subscription`. It also adds in more robust error handling, which means that previous errors (like a link detaching) do not cause the Processor to exit. - -The Processor will only exit when you call `Close`. - -```go -// NOTE: there is also NewProcessorForSubscription for subscriptions. -processor, err = client.NewProcessorForQueue( - queueName, - nil) - -handleMessage := func(message *azservicebus.ReceivedMessage) error { - log.Printf("Message arrived: %s", message.) - processor.CompleteMessage(ctx, message) -} - -handleError := func(err error) { - // called whenever errors occur. Note, that unlike the - // Listen, errors are automatically recovered. -} - -// blocks until the Processor is closed. -processor.Start(ctx, handleMessage, handleError, nil) - -// close at a time of your choosing -processor.Close(ctx) -``` +You can receive messages using the [Receiver](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus#Receiver), for receiving of messages in batches. ### Receivers -Receivers allow you to request messages in batches, or easily receive a single message. This can be useful -for programs that need more control over when messages are received and when they are processed. +Receivers allow you to request messages in batches, or easily receive a single message. ```go receiver, err := client.NewReceiverForQueue(queue) // or for a subscription receiver, err := client.NewReceiverForSubscription(topicName, subscriptionName) -``` - -`ReceiveOne` has been split into two functions to allow for receiving -multiple messages at a time (`ReceiveMessages`) or a single message (`ReceiveMessage`). - -```go -// new code // receiving multiple messages at a time, with a configurable timeout. var messages []*azservicebus.ReceivedMessage messages, err = receiver.ReceiveMessages(ctx, numMessages, nil) - -// receiving a single message time, with a configurable timeout. -var message *azservicebus.ReceivedMessage - -// this is similar to the `ReceiveOne` -message, err = receiver.ReceiveMessage(ctx, nil) ``` ### Using dead letter queues @@ -192,12 +151,7 @@ Now, using `azservicebus`: ```go // new code -// with the Processor -processor.Start(ctx, func(msg *azservicebus.ReceivedMessage) { - processor.CompleteMessage(ctx, msg) -}) - -// or with a Receiver +// with a Receiver message, err := receiver.ReceiveMessage(ctx) // or ReceiveMessages() receiver.CompleteMessage(ctx, message) ``` diff --git a/sdk/messaging/azservicebus/processor.go b/sdk/messaging/azservicebus/processor.go index d647a5939bbe..505874fc9c09 100644 --- a/sdk/messaging/azservicebus/processor.go +++ b/sdk/messaging/azservicebus/processor.go @@ -17,9 +17,11 @@ import ( "github.com/devigned/tab" ) -// ProcessorOptions contains options for the `Client.NewProcessorForQueue` or +// NOTE: this type is experimental + +// processorOptions contains options for the `Client.NewProcessorForQueue` or // `Client.NewProcessorForSubscription` functions. -type ProcessorOptions struct { +type processorOptions struct { // ReceiveMode controls when a message is deleted from Service Bus. // // `azservicebus.PeekLock` is the default. The message is locked, preventing multiple @@ -38,16 +40,16 @@ type ProcessorOptions struct { // of the queue or subscription. SubQueue SubQueue - // ManualComplete controls whether messages must be settled explicitly via the - // settlement methods (ie, Complete, Abandon) or if the - // processor will automatically settle messages. + // DisableAutoComplete controls whether messages must be settled explicitly via the + // settlement methods (ie, Complete, Abandon) or if the processor will automatically + // settle messages. // // If true, no automatic settlement is done. // If false, the return value of your `handleMessage` function will control if the // message is abandoned (non-nil error return) or completed (nil error return). // - // This option is enabled, by default. - ManualComplete bool + // This option is false, by default. + DisableAutoComplete bool // MaxConcurrentCalls controls the maximum number of message processing // goroutines that are active at any time. @@ -55,8 +57,8 @@ type ProcessorOptions struct { MaxConcurrentCalls int } -// Processor is a push-based receiver for Service Bus. -type Processor struct { +// processor is a push-based receiver for Service Bus. +type processor struct { receiveMode ReceiveMode autoComplete bool maxConcurrentCalls int @@ -78,36 +80,36 @@ type Processor struct { cleanupOnClose func() } -func applyProcessorOptions(processor *Processor, entity *entity, options *ProcessorOptions) error { +func applyProcessorOptions(p *processor, entity *entity, options *processorOptions) error { if options == nil { - processor.maxConcurrentCalls = 1 - processor.receiveMode = PeekLock - processor.autoComplete = true + p.maxConcurrentCalls = 1 + p.receiveMode = PeekLock + p.autoComplete = true return nil } - processor.autoComplete = !options.ManualComplete + p.autoComplete = !options.DisableAutoComplete if err := checkReceiverMode(options.ReceiveMode); err != nil { return err } - processor.receiveMode = options.ReceiveMode + p.receiveMode = options.ReceiveMode if err := entity.SetSubQueue(options.SubQueue); err != nil { return err } if options.MaxConcurrentCalls > 0 { - processor.maxConcurrentCalls = options.MaxConcurrentCalls + p.maxConcurrentCalls = options.MaxConcurrentCalls } return nil } -func newProcessor(ns internal.NamespaceWithNewAMQPLinks, entity *entity, cleanupOnClose func(), options *ProcessorOptions) (*Processor, error) { - processor := &Processor{ +func newProcessor(ns internal.NamespaceWithNewAMQPLinks, entity *entity, cleanupOnClose func(), options *processorOptions) (*processor, error) { + processor := &processor{ // TODO: make this configurable baseRetrier: internal.NewBackoffRetrier(internal.BackoffRetrierParams{ Factor: 1.5, @@ -160,7 +162,7 @@ func newProcessor(ns internal.NamespaceWithNewAMQPLinks, entity *entity, cleanup // Any errors that occur (such as network disconnects, failures in handleMessage) will be // sent to your handleError function. The processor will retry and restart as needed - // no user intervention is required. -func (p *Processor) Start(ctx context.Context, handleMessage func(message *ReceivedMessage) error, handleError func(err error)) error { +func (p *processor) Start(ctx context.Context, handleMessage func(message *ReceivedMessage) error, handleError func(err error)) error { ctx, span := tab.StartSpan(ctx, tracing.SpanProcessorLoop) defer span.End() @@ -214,7 +216,7 @@ func (p *Processor) Start(ctx context.Context, handleMessage func(message *Recei // NOTE: Close() cannot be called synchronously in a message // or error handler. You must run it asynchronously using // `go processor.Close(ctx)` or similar. -func (p *Processor) Close(ctx context.Context) error { +func (p *processor) Close(ctx context.Context) error { p.mu.Lock() defer p.mu.Unlock() @@ -251,33 +253,33 @@ func (p *Processor) Close(ctx context.Context) error { } // CompleteMessage completes a message, deleting it from the queue or subscription. -func (p *Processor) CompleteMessage(ctx context.Context, message *ReceivedMessage) error { +func (p *processor) CompleteMessage(ctx context.Context, message *ReceivedMessage) error { return p.settler.CompleteMessage(ctx, message) } // AbandonMessage will cause a message to be returned to the queue or subscription. // This will increment its delivery count, and potentially cause it to be dead lettered // depending on your queue or subscription's configuration. -func (p *Processor) AbandonMessage(ctx context.Context, message *ReceivedMessage) error { +func (p *processor) AbandonMessage(ctx context.Context, message *ReceivedMessage) error { return p.settler.AbandonMessage(ctx, message) } // DeferMessage will cause a message to be deferred. Deferred messages // can be received using `Receiver.ReceiveDeferredMessages`. -func (p *Processor) DeferMessage(ctx context.Context, message *ReceivedMessage) error { +func (p *processor) DeferMessage(ctx context.Context, message *ReceivedMessage) error { return p.settler.DeferMessage(ctx, message) } // DeadLetterMessage settles a message by moving it to the dead letter queue for a // queue or subscription. To receive these messages create a processor with `Client.NewProcessorForQueue()` // or `Client.NewProcessorForSubscription()` using the `ProcessorOptions.SubQueue` option. -func (p *Processor) DeadLetterMessage(ctx context.Context, message *ReceivedMessage, options *DeadLetterOptions) error { +func (p *processor) DeadLetterMessage(ctx context.Context, message *ReceivedMessage, options *DeadLetterOptions) error { return p.settler.DeadLetterMessage(ctx, message, options) } // subscribe continually receives messages from Service Bus, stopping // if a fatal link/connection error occurs. -func (p *Processor) subscribe() error { +func (p *processor) subscribe() error { p.wg.Add(1) defer p.wg.Done() @@ -327,7 +329,7 @@ func (p *Processor) subscribe() error { } } -func (p *Processor) processMessage(ctx context.Context, receiver internal.AMQPReceiver, amqpMessage *amqp.Message) error { +func (p *processor) processMessage(ctx context.Context, receiver internal.AMQPReceiver, amqpMessage *amqp.Message) error { ctx, span := tab.StartSpan(ctx, tracing.SpanProcessorMessage) defer span.End() @@ -376,3 +378,31 @@ func checkReceiverMode(receiveMode ReceiveMode) error { return fmt.Errorf("Invalid receive mode %d, must be either azservicebus.PeekLock or azservicebus.ReceiveAndDelete", receiveMode) } } + +// newProcessorForQueue creates a Processor for a queue. +func newProcessorForQueue(client *Client, queue string, options *processorOptions) (*processor, error) { + id, cleanupOnClose := client.getCleanupForCloseable() + + processor, err := newProcessor(client.namespace, &entity{Queue: queue}, cleanupOnClose, options) + + if err != nil { + return nil, err + } + + client.addCloseable(id, processor) + return processor, nil +} + +// newProcessorForQueue creates a Processor for a subscription. +func newProcessorForSubscription(client *Client, topic string, subscription string, options *processorOptions) (*processor, error) { + id, cleanupOnClose := client.getCleanupForCloseable() + + processor, err := newProcessor(client.namespace, &entity{Topic: topic, Subscription: subscription}, cleanupOnClose, options) + + if err != nil { + return nil, err + } + + client.addCloseable(id, processor) + return processor, nil +} diff --git a/sdk/messaging/azservicebus/processor_test.go b/sdk/messaging/azservicebus/processor_test.go index d7115d2318c0..be8db04063c7 100644 --- a/sdk/messaging/azservicebus/processor_test.go +++ b/sdk/messaging/azservicebus/processor_test.go @@ -37,7 +37,7 @@ func TestProcessorReceiveWithDefaults(t *testing.T) { require.NoError(t, err) }() - processor, err := serviceBusClient.NewProcessorForQueue(queueName, nil) + processor, err := newProcessorForQueue(serviceBusClient, queueName, nil) require.NoError(t, err) defer processor.Close(context.Background()) // multiple close is fine @@ -112,9 +112,10 @@ func TestProcessorReceiveWith100MessagesWithMaxConcurrency(t *testing.T) { require.NoError(t, sender.SendMessageBatch(context.Background(), batch)) }() - processor, err := serviceBusClient.NewProcessorForQueue( + processor, err := newProcessorForQueue( + serviceBusClient, queueName, - &ProcessorOptions{ + &processorOptions{ MaxConcurrentCalls: 20, }) @@ -158,7 +159,7 @@ func TestProcessorReceiveWith100MessagesWithMaxConcurrency(t *testing.T) { } func TestProcessorUnitTests(t *testing.T) { - p := &Processor{} + p := &processor{} e := &entity{} require.NoError(t, applyProcessorOptions(p, e, nil)) @@ -166,16 +167,16 @@ func TestProcessorUnitTests(t *testing.T) { require.EqualValues(t, 1, p.maxConcurrentCalls) require.EqualValues(t, PeekLock, p.receiveMode) - p = &Processor{} + p = &processor{} e = &entity{ Queue: "queue", } - require.NoError(t, applyProcessorOptions(p, e, &ProcessorOptions{ - ReceiveMode: ReceiveAndDelete, - SubQueue: SubQueueDeadLetter, - ManualComplete: true, - MaxConcurrentCalls: 101, + require.NoError(t, applyProcessorOptions(p, e, &processorOptions{ + ReceiveMode: ReceiveAndDelete, + SubQueue: SubQueueDeadLetter, + DisableAutoComplete: true, + MaxConcurrentCalls: 101, })) require.False(t, p.autoComplete) diff --git a/sdk/messaging/azservicebus/receiver.go b/sdk/messaging/azservicebus/receiver.go index 7695dff2491a..65b9bfe03f07 100644 --- a/sdk/messaging/azservicebus/receiver.go +++ b/sdk/messaging/azservicebus/receiver.go @@ -21,7 +21,7 @@ type ReceiveMode = internal.ReceiveMode const ( // PeekLock will lock messages as they are received and can be settled - // using the Receiver or Processor's (Complete|Abandon|DeadLetter|Defer)Message + // using the Receiver's (Complete|Abandon|DeadLetter|Defer)Message // functions. PeekLock ReceiveMode = internal.PeekLock // ReceiveAndDelete will delete messages as they are received. @@ -42,7 +42,6 @@ const ( ) // Receiver receives messages using pull based functions (ReceiveMessages). -// For push-based receiving via callbacks look at the `Processor` type. type Receiver struct { receiveMode ReceiveMode @@ -64,8 +63,8 @@ type ReceiverOptions struct { // // `azservicebus.PeekLock` is the default. The message is locked, preventing multiple // receivers from processing the message at once. You control the lock state of the message - // using one of the message settlement functions like processor.CompleteMessage(), which removes - // it from Service Bus, or processor.AbandonMessage(), which makes it available again. + // using one of the message settlement functions like Receiver.CompleteMessage(), which removes + // it from Service Bus, or Receiver.AbandonMessage(), which makes it available again. // // `azservicebus.ReceiveAndDelete` causes Service Bus to remove the message as soon // as it's received. @@ -390,8 +389,8 @@ func (r *Receiver) PeekMessages(ctx context.Context, maxMessageCount int, option return receivedMessages, nil } -// ReceiveDeferredMessage receives a single message that was deferred using `Receiver.DeferMessage`. -func (r *Receiver) ReceiveDeferredMessage(ctx context.Context, sequenceNumber int64) (*ReceivedMessage, error) { +// receiveDeferredMessage receives a single message that was deferred using `Receiver.DeferMessage`. +func (r *Receiver) receiveDeferredMessage(ctx context.Context, sequenceNumber int64) (*ReceivedMessage, error) { messages, err := r.ReceiveDeferredMessages(ctx, []int64{sequenceNumber}) if err != nil { @@ -405,8 +404,8 @@ func (r *Receiver) ReceiveDeferredMessage(ctx context.Context, sequenceNumber in return messages[0], nil } -// ReceiveMessage receives a single message, waiting up to `ReceiveOptions.MaxWaitTime` (default: 60 seconds) -func (r *Receiver) ReceiveMessage(ctx context.Context, options *ReceiveOptions) (*ReceivedMessage, error) { +// receiveMessage receives a single message, waiting up to `ReceiveOptions.MaxWaitTime` (default: 60 seconds) +func (r *Receiver) receiveMessage(ctx context.Context, options *ReceiveOptions) (*ReceivedMessage, error) { messages, err := r.ReceiveMessages(ctx, 1, options) if err != nil { @@ -420,6 +419,26 @@ func (r *Receiver) ReceiveMessage(ctx context.Context, options *ReceiveOptions) return messages[0], nil } +// RenewLock renews the lock on a message, updating the `LockedUntil` field on `msg`. +func (r *Receiver) RenewMessageLock(ctx context.Context, msg *ReceivedMessage) error { + _, _, mgmt, _, err := r.amqpLinks.Get(ctx) + + if err != nil { + return err + } + + newExpirationTime, err := mgmt.RenewLocks(ctx, msg.rawAMQPMessage.LinkName(), []amqp.UUID{ + (amqp.UUID)(msg.LockToken), + }) + + if err != nil { + return err + } + + msg.LockedUntil = &newExpirationTime[0] + return nil +} + // Close permanently closes the receiver. func (r *Receiver) Close(ctx context.Context) error { r.cleanupOnClose() diff --git a/sdk/messaging/azservicebus/receiver_test.go b/sdk/messaging/azservicebus/receiver_test.go index d1fc33b8997f..c75d3aa41ab5 100644 --- a/sdk/messaging/azservicebus/receiver_test.go +++ b/sdk/messaging/azservicebus/receiver_test.go @@ -291,6 +291,45 @@ func TestReceiverPeek(t *testing.T) { require.Empty(t, noMessagesExpected) } +func TestReceiver_RenewMessageLock(t *testing.T) { + client, cleanup, queueName := setupLiveTest(t, nil) + defer cleanup() + + sender, err := client.NewSender(queueName) + require.NoError(t, err) + + err = sender.SendMessage(context.Background(), &Message{ + Body: []byte("hello world"), + }) + require.NoError(t, err) + + receiver, err := client.NewReceiverForQueue(queueName, nil) + require.NoError(t, err) + + messages, err := receiver.ReceiveMessages(context.Background(), 1, nil) + require.NoError(t, err) + + time.Sleep(2 * time.Second) + lockedUntilOld := messages[0].LockedUntil + require.NoError(t, receiver.RenewMessageLock(context.Background(), messages[0])) + + // these should hopefully be unaffected by clock drift since both values come from + // the service's times, not ours. + require.Greater(t, messages[0].LockedUntil.UnixNano(), lockedUntilOld.UnixNano()) + + // try renewing a bogus token + for i := 0; i < len(messages[0].LockToken); i++ { + messages[0].LockToken[i] = 0 + } + + expectedLockBadError := receiver.RenewMessageLock(context.Background(), messages[0]) + // String matching can go away once we fix #15644 + // For now it at least provides the user with good context that something is incorrect about their lock token. + require.Contains(t, expectedLockBadError.Error(), + "status code 410 and description: The lock supplied is invalid. Either the lock expired, or the message has already been removed from the queue", + "error message from SB comes through") +} + func TestReceiverOptions(t *testing.T) { // defaults receiver := &Receiver{} diff --git a/sdk/messaging/azservicebus/samples/processor/processor_sample.go b/sdk/messaging/azservicebus/samples/processor/processor_sample.go deleted file mode 100644 index b1167f004d46..000000000000 --- a/sdk/messaging/azservicebus/samples/processor/processor_sample.go +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package main - -import ( - "context" - "errors" - "log" - "os" - "time" - - "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus" - "github.com/joho/godotenv" -) - -func main() { - _ = godotenv.Load() - - cs := os.Getenv("SERVICEBUS_CONNECTION_STRING") - queue := os.Getenv("QUEUE_NAME") - - if cs == "" || queue == "" { - log.Fatalf("SERVICEBUS_CONNECTION_STRING and QUEUE_NAME must be defined in the environment for this sample") - } - - serviceBusClient, err := azservicebus.NewClientFromConnectionString(cs, nil) - - if err != nil { - log.Fatalf("Failed to create service bus client: %s", err.Error()) - } - - defer serviceBusClient.Close(context.TODO()) - - // - // Send some sample messages - // - - sender, err := serviceBusClient.NewSender(queue) - - if err != nil { - log.Fatalf("Failed to create the sender: %s", err.Error()) - } - - err = sender.SendMessage(context.TODO(), &azservicebus.Message{ - Body: []byte("hello, from the processor sample!"), - }) - - if err != nil { - log.Fatalf("Failed to send sample message to queue: %s", queue) - } - - // - // receive the messages we've sent using the processor - // - - processor, err := serviceBusClient.NewProcessorForQueue( - // or: azservicebus.NewProcessorForSubscription - queue, - &azservicebus.ProcessorOptions{ - // Will auto-complete or auto-abandon messages, based on the result from you callback - // (this is true, by default) - ManualComplete: false, - // or for a subscription - ReceiveMode: azservicebus.PeekLock, - }, - ) - - if err != nil { - log.Fatalf("Failed to create processor: %s", err.Error()) - } - - err = processor.Start(context.Background(), func(message *azservicebus.ReceivedMessage) error { - log.Printf("Received message %s", string(message.Body)) - - // with auto-complete on (which it is, by default): - // - a nil will cause us to Complete the message on the user's behalf. - // - a non-nil error will cause to Abandon the message. The error will also be forwarded - // to their error handler below. - return nil - }, func(err error) { - // a customer can reasonably expect to see some errors here when the processor recovers - // from connection errors, or if some automated operations failed (like autocomplete - // settlement failure) - if errors.Is(err, context.Canceled) { - // filter out errors that we expect or are not concerned about. - return - } - - log.Printf("Error: %s", err.Error()) - }) - - if err != nil { - log.Fatalf("Failed to start processor : %s", err.Error()) - } - - log.Printf("Waiting for 30 seconds for any messages to arrive") - time.Sleep(30 * time.Second) - - if err := processor.Close(context.TODO()); err != nil { - log.Fatalf("Failed to close processor: %s", err.Error()) - } - - log.Printf("Finished listening") -} diff --git a/sdk/messaging/azservicebus/sender_test.go b/sdk/messaging/azservicebus/sender_test.go index 7cb342ca4c56..014e0f51da77 100644 --- a/sdk/messaging/azservicebus/sender_test.go +++ b/sdk/messaging/azservicebus/sender_test.go @@ -171,7 +171,7 @@ func Test_Sender_SendMessages_resend(t *testing.T) { err = sender.SendMessage(ctx, msg) require.NoError(t, err) - message, err := receiver.ReceiveMessage(ctx, nil) + message, err := receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, "first send", msg.ApplicationProperties["Status"]) require.EqualValues(t, "ResendableMessage", string(msg.Body)) @@ -184,7 +184,7 @@ func Test_Sender_SendMessages_resend(t *testing.T) { err = sender.SendMessage(ctx, msg) require.NoError(t, err) - message, err = receiver.ReceiveMessage(ctx, nil) + message, err = receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, "resend", msg.ApplicationProperties["Status"]) require.EqualValues(t, "ResendableMessage", string(msg.Body)) diff --git a/sdk/messaging/azservicebus/session_receiver.go b/sdk/messaging/azservicebus/session_receiver.go index d69ef5916422..cc58866d3835 100644 --- a/sdk/messaging/azservicebus/session_receiver.go +++ b/sdk/messaging/azservicebus/session_receiver.go @@ -6,6 +6,7 @@ package azservicebus import ( "context" "fmt" + "time" "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal" "github.com/Azure/go-amqp" @@ -15,7 +16,8 @@ import ( type SessionReceiver struct { *Receiver - sessionID *string + sessionID *string + lockedUntil time.Time } // SessionReceiverOptions contains options for the `Client.AcceptSessionForQueue/Subscription` or `Client.AcceptNextSessionForQueue/Subscription` @@ -25,8 +27,8 @@ type SessionReceiverOptions struct { // // `azservicebus.PeekLock` is the default. The message is locked, preventing multiple // receivers from processing the message at once. You control the lock state of the message - // using one of the message settlement functions like processor.CompleteMessage(), which removes - // it from Service Bus, or processor.AbandonMessage(), which makes it available again. + // using one of the message settlement functions like SessionReceiver.CompleteMessage(), which removes + // it from Service Bus, or SessionReceiver..AbandonMessage(), which makes it available again. // // `azservicebus.ReceiveAndDelete` causes Service Bus to remove the message as soon // as it's received. @@ -46,12 +48,13 @@ func toReceiverOptions(sropts *SessionReceiverOptions) *ReceiverOptions { } } -func newSessionReceiver(sessionID *string, ns internal.NamespaceWithNewAMQPLinks, entity *entity, cleanupOnClose func(), options *ReceiverOptions) (*SessionReceiver, error) { +func newSessionReceiver(ctx context.Context, sessionID *string, ns internal.NamespaceWithNewAMQPLinks, entity *entity, cleanupOnClose func(), options *ReceiverOptions) (*SessionReceiver, error) { const sessionFilterName = "com.microsoft:session-filter" const code = uint64(0x00000137000000C) sessionReceiver := &SessionReceiver{ - sessionID: sessionID, + sessionID: sessionID, + lockedUntil: time.Time{}, } var err error @@ -89,15 +92,47 @@ func newSessionReceiver(sessionID *string, ns internal.NamespaceWithNewAMQPLinks return nil, err } + // temp workaround until we expose the session expiration time from the receiver in go-amqp + if err := sessionReceiver.RenewSessionLock(ctx); err != nil { + _ = sessionReceiver.Close(context.Background()) + return nil, err + } + return sessionReceiver, nil } +// SessionID is the session ID for this SessionReceiver. func (sr *SessionReceiver) SessionID() string { // return the ultimately assigned session ID for this link (anonymous will get it from the // link filter options, non-anonymous is set in newSessionReceiver) return *sr.sessionID } +// LockedUntil is the time the lock on this session expires. +// The lock can be renewed using `SessionReceiver.RenewSessionLock`. +func (sr *SessionReceiver) LockedUntil() time.Time { + return sr.lockedUntil +} + +// RenewSessionLock renews this session's lock. The new expiration time is available +// using `LockedUntil`. +func (sr *SessionReceiver) RenewSessionLock(ctx context.Context) error { + _, _, mgmt, _, err := sr.amqpLinks.Get(ctx) + + if err != nil { + return err + } + + newLockedUntil, err := mgmt.RenewSessionLock(ctx, *sr.sessionID) + + if err != nil { + return err + } + + sr.lockedUntil = newLockedUntil + return nil +} + // init ensures the link was created, guaranteeing that we get our expected session lock. func (sr *SessionReceiver) init(ctx context.Context) error { // initialize the links diff --git a/sdk/messaging/azservicebus/session_receiver_test.go b/sdk/messaging/azservicebus/session_receiver_test.go index c0c99f6e113d..649fddf4f19b 100644 --- a/sdk/messaging/azservicebus/session_receiver_test.go +++ b/sdk/messaging/azservicebus/session_receiver_test.go @@ -35,7 +35,7 @@ func TestSessionReceiver_acceptSession(t *testing.T) { receiver, err := client.AcceptSessionForQueue(ctx, queueName, "session-1", nil) require.NoError(t, err) - msg, err := receiver.ReceiveMessage(ctx, nil) + msg, err := receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, "session-based message", msg.Body) @@ -69,7 +69,7 @@ func TestSessionReceiver_blankSessionIDs(t *testing.T) { receiver, err := client.AcceptSessionForQueue(ctx, queueName, "", nil) require.NoError(t, err) - msg, err := receiver.ReceiveMessage(ctx, nil) + msg, err := receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, "session-based message", msg.Body) @@ -120,7 +120,7 @@ func TestSessionReceiver_acceptNextSession(t *testing.T) { receiver, err := client.AcceptNextSessionForQueue(ctx, queueName, nil) require.NoError(t, err) - msg, err := receiver.ReceiveMessage(ctx, nil) + msg, err := receiver.receiveMessage(ctx, nil) require.NoError(t, err) require.EqualValues(t, "session-based message", msg.Body) @@ -167,7 +167,7 @@ func TestSessionReceiver_nonSessionReceiver(t *testing.T) { // normal receivers are lazy initialized so we need to do _something_ to make sure // the link gets spun up (and thus fails) - message, err := receiver.ReceiveMessage(context.Background(), nil) + message, err := receiver.receiveMessage(context.Background(), nil) require.Nil(t, message) var amqpError *amqp.Error @@ -183,6 +183,43 @@ func TestSessionReceiver_nonSessionReceiver(t *testing.T) { require.Contains(t, amqpError.Description, "It is not possible for an entity that requires sessions to create a non-sessionful message receiver.") } +func TestSessionReceiver_RenewSessionLock(t *testing.T) { + client, cleanup, queueName := setupLiveTest(t, &QueueProperties{ + RequiresSession: to.BoolPtr(true), + }) + defer cleanup() + + sessionReceiver, err := client.AcceptSessionForQueue(context.Background(), queueName, "session-1", nil) + require.NoError(t, err) + + sender, err := client.NewSender(queueName) + require.NoError(t, err) + + err = sender.SendMessage(context.Background(), &Message{ + Body: []byte("hello world"), + SessionID: to.StringPtr("session-1"), + }) + require.NoError(t, err) + + messages, err := sessionReceiver.ReceiveMessages(context.Background(), 1, nil) + require.NoError(t, err) + require.NotNil(t, messages) + + // surprisingly this works. Not sure what it accomplishes though. C# has a manual check for it. + // err = sessionReceiver.RenewMessageLock(context.Background(), messages[0]) + // require.NoError(t, err) + + orig := sessionReceiver.LockedUntil() + require.NoError(t, sessionReceiver.RenewSessionLock(context.Background())) + require.Greater(t, sessionReceiver.LockedUntil().UnixNano(), orig.UnixNano()) + + // bogus renewal + sessionReceiver.sessionID = to.StringPtr("bogus") + + err = sessionReceiver.RenewSessionLock(context.Background()) + require.Contains(t, err.Error(), "status code 410 and description: The session lock has expired on the MessageSession") +} + func Test_toReceiverOptions(t *testing.T) { require.Nil(t, toReceiverOptions(nil)) diff --git a/sdk/messaging/azservicebus/stress/stress.go b/sdk/messaging/azservicebus/stress/stress.go index f72d3d702f30..4c40f465e0e4 100644 --- a/sdk/messaging/azservicebus/stress/stress.go +++ b/sdk/messaging/azservicebus/stress/stress.go @@ -34,7 +34,6 @@ type stats struct { Errors int32 } -var processorStats stats var receiverStats stats var senderStats stats @@ -65,11 +64,9 @@ func runBasicSendAndReceiveTest() { ticker := time.NewTicker(5 * time.Second) for range ticker.C { - log.Printf("Received: (p:%d,r:%d), Sent: %d, Errors: (p:%d,r:%d,s:%d)", - atomic.LoadInt32(&processorStats.Received), + log.Printf("Received: (r:%d), Sent: %d, Errors: (r:%d,s:%d)", atomic.LoadInt32(&receiverStats.Received), atomic.LoadInt32(&senderStats.Sent), - atomic.LoadInt32(&processorStats.Errors), atomic.LoadInt32(&receiverStats.Errors), atomic.LoadInt32(&senderStats.Errors)) } @@ -98,7 +95,7 @@ func runBasicSendAndReceiveTest() { telemetryClient.Track(startEvent) - cleanup, err := createSubscriptions(telemetryClient, cs, topicName, []string{"processor", "batch"}) + cleanup, err := createSubscriptions(telemetryClient, cs, topicName, []string{"batch"}) defer cleanup() if err != nil { @@ -123,9 +120,10 @@ func runBasicSendAndReceiveTest() { tab.Register(&utils.StderrTracer{ Include: map[string]bool{ - tracing.SpanProcessorClose: true, - tracing.SpanProcessorLoop: true, - //tracing.SpanProcessorMessage: true, + // internal.SpanProcessorClose: true, + // internal.SpanProcessorLoop: true, + + //internal.SpanProcessorMessage: true, tracing.SpanRecover: true, tracing.SpanNegotiateClaim: true, tracing.SpanRecoverClient: true, @@ -133,21 +131,11 @@ func runBasicSendAndReceiveTest() { }, }) - runProcessorTest := true - - if runProcessorTest { - go func() { - for { - runProcessor(ctx, serviceBusClient, topicName, "processor", telemetryClient) - } - }() - } else { - go func() { - for { - runBatchReceiver(ctx, serviceBusClient, topicName, "batch", telemetryClient) - } - }() - } + go func() { + for { + runBatchReceiver(ctx, serviceBusClient, topicName, "batch", telemetryClient) + } + }() go func() { for { @@ -185,38 +173,6 @@ func runBatchReceiver(ctx context.Context, serviceBusClient *azservicebus.Client } } -func runProcessor(ctx context.Context, client *azservicebus.Client, topicName string, subscriptionName string, telemetryClient appinsights.TelemetryClient) { - log.Printf("Starting processor...") - processor, err := client.NewProcessorForSubscription( - topicName, subscriptionName, - &azservicebus.ProcessorOptions{MaxConcurrentCalls: 10}) - - if err != nil { - trackException(&processorStats, telemetryClient, "Failed when creating processor", err) - return - } - - err = processor.Start(ctx, func(msg *azservicebus.ReceivedMessage) error { - atomic.AddInt32(&processorStats.Received, 1) - telemetryClient.TrackMetric("MessageReceived", 1) - return nil - }, func(err error) { - log.Printf("Exception in processor: %s", err.Error()) - trackException(&processorStats, telemetryClient, "Processor.HandleError", err) - }) - - if err != nil { - log.Printf("Exception when starting processor: %s", err.Error()) - trackException(&processorStats, telemetryClient, "Processor.Start", err) - return - } - - <-ctx.Done() - - telemetryClient.TrackEvent("ProcessorStopped") - log.Print("Processor was stopped!") -} - func continuallySend(ctx context.Context, client *azservicebus.Client, queueName string, telemetryClient appinsights.TelemetryClient) { sender, err := client.NewSender(queueName) diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/LICENSE.txt b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md new file mode 100644 index 000000000000..e9653d1e2db2 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/README.md @@ -0,0 +1,76 @@ +# Azure Alerts Management Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement) + +The `armalertsmanagement` module provides operations for working with Azure Alerts Management. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/alertsmanagement/armalertsmanagement) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Alerts Management module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Alerts Management. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Alerts Management + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Alerts Management modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armalertsmanagement.NewAlertsClient(conn,"") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Alerts Management` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md new file mode 100644 index 000000000000..30cff12f9137 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/autorest.md @@ -0,0 +1,14 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/alertsmanagement/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/alertsmanagement/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +modelerfour: + lenient-model-deduplication: true +``` \ No newline at end of file diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go new file mode 100644 index 000000000000..771b03a15719 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/alertsmanagement/armalertsmanagement + +package armalertsmanagement diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/ci.yml b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/ci.yml new file mode 100644 index 000000000000..8cf9a019b72e --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/alertsmanagement/armalertsmanagement/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/alertsmanagement/armalertsmanagement/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/alertsmanagement/armalertsmanagement' diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.mod b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.mod new file mode 100644 index 000000000000..7e3d5c8c0a29 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/alertsmanagement/armalertsmanagement + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.sum b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go_mod_tidy_hack.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go_mod_tidy_hack.go new file mode 100644 index 000000000000..76461c035342 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armalertsmanagement + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_actionrules_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_actionrules_client.go new file mode 100644 index 000000000000..4b63632357ca --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_actionrules_client.go @@ -0,0 +1,484 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strings" +) + +// ActionRulesClient contains the methods for the ActionRules group. +// Don't use this type directly, use NewActionRulesClient() instead. +type ActionRulesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewActionRulesClient creates a new instance of ActionRulesClient with the specified values. +func NewActionRulesClient(con *arm.Connection, subscriptionID string) *ActionRulesClient { + return &ActionRulesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateUpdate - Creates/Updates a specific action rule +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) CreateUpdate(ctx context.Context, resourceGroupName string, actionRuleName string, actionRule ActionRule, options *ActionRulesCreateUpdateOptions) (ActionRulesCreateUpdateResponse, error) { + req, err := client.createUpdateCreateRequest(ctx, resourceGroupName, actionRuleName, actionRule, options) + if err != nil { + return ActionRulesCreateUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ActionRulesCreateUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ActionRulesCreateUpdateResponse{}, client.createUpdateHandleError(resp) + } + return client.createUpdateHandleResponse(resp) +} + +// createUpdateCreateRequest creates the CreateUpdate request. +func (client *ActionRulesClient) createUpdateCreateRequest(ctx context.Context, resourceGroupName string, actionRuleName string, actionRule ActionRule, options *ActionRulesCreateUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if actionRuleName == "" { + return nil, errors.New("parameter actionRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{actionRuleName}", url.PathEscape(actionRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, actionRule) +} + +// createUpdateHandleResponse handles the CreateUpdate response. +func (client *ActionRulesClient) createUpdateHandleResponse(resp *http.Response) (ActionRulesCreateUpdateResponse, error) { + result := ActionRulesCreateUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ActionRule); err != nil { + return ActionRulesCreateUpdateResponse{}, err + } + return result, nil +} + +// createUpdateHandleError handles the CreateUpdate error response. +func (client *ActionRulesClient) createUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a given action rule +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) Delete(ctx context.Context, resourceGroupName string, actionRuleName string, options *ActionRulesDeleteOptions) (ActionRulesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, actionRuleName, options) + if err != nil { + return ActionRulesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ActionRulesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ActionRulesDeleteResponse{}, client.deleteHandleError(resp) + } + return client.deleteHandleResponse(resp) +} + +// deleteCreateRequest creates the Delete request. +func (client *ActionRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, actionRuleName string, options *ActionRulesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if actionRuleName == "" { + return nil, errors.New("parameter actionRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{actionRuleName}", url.PathEscape(actionRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleResponse handles the Delete response. +func (client *ActionRulesClient) deleteHandleResponse(resp *http.Response) (ActionRulesDeleteResponse, error) { + result := ActionRulesDeleteResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Value); err != nil { + return ActionRulesDeleteResponse{}, err + } + return result, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ActionRulesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetByName - Get a specific action rule +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) GetByName(ctx context.Context, resourceGroupName string, actionRuleName string, options *ActionRulesGetByNameOptions) (ActionRulesGetByNameResponse, error) { + req, err := client.getByNameCreateRequest(ctx, resourceGroupName, actionRuleName, options) + if err != nil { + return ActionRulesGetByNameResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ActionRulesGetByNameResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ActionRulesGetByNameResponse{}, client.getByNameHandleError(resp) + } + return client.getByNameHandleResponse(resp) +} + +// getByNameCreateRequest creates the GetByName request. +func (client *ActionRulesClient) getByNameCreateRequest(ctx context.Context, resourceGroupName string, actionRuleName string, options *ActionRulesGetByNameOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if actionRuleName == "" { + return nil, errors.New("parameter actionRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{actionRuleName}", url.PathEscape(actionRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getByNameHandleResponse handles the GetByName response. +func (client *ActionRulesClient) getByNameHandleResponse(resp *http.Response) (ActionRulesGetByNameResponse, error) { + result := ActionRulesGetByNameResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ActionRule); err != nil { + return ActionRulesGetByNameResponse{}, err + } + return result, nil +} + +// getByNameHandleError handles the GetByName error response. +func (client *ActionRulesClient) getByNameHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - List all action rules of the subscription, created in given resource group and given input filters +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) ListByResourceGroup(resourceGroupName string, options *ActionRulesListByResourceGroupOptions) *ActionRulesListByResourceGroupPager { + return &ActionRulesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp ActionRulesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ActionRulesList.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ActionRulesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ActionRulesListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } + if options != nil && options.ImpactedScope != nil { + reqQP.Set("impactedScope", *options.ImpactedScope) + } + if options != nil && options.Description != nil { + reqQP.Set("description", *options.Description) + } + if options != nil && options.AlertRuleID != nil { + reqQP.Set("alertRuleId", *options.AlertRuleID) + } + if options != nil && options.ActionGroup != nil { + reqQP.Set("actionGroup", *options.ActionGroup) + } + if options != nil && options.Name != nil { + reqQP.Set("name", *options.Name) + } + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ActionRulesClient) listByResourceGroupHandleResponse(resp *http.Response) (ActionRulesListByResourceGroupResponse, error) { + result := ActionRulesListByResourceGroupResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ActionRulesList); err != nil { + return ActionRulesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *ActionRulesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscription - List all action rules of the subscription and given input filters +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) ListBySubscription(options *ActionRulesListBySubscriptionOptions) *ActionRulesListBySubscriptionPager { + return &ActionRulesListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp ActionRulesListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ActionRulesList.NextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ActionRulesClient) listBySubscriptionCreateRequest(ctx context.Context, options *ActionRulesListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/actionRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } + if options != nil && options.ImpactedScope != nil { + reqQP.Set("impactedScope", *options.ImpactedScope) + } + if options != nil && options.Description != nil { + reqQP.Set("description", *options.Description) + } + if options != nil && options.AlertRuleID != nil { + reqQP.Set("alertRuleId", *options.AlertRuleID) + } + if options != nil && options.ActionGroup != nil { + reqQP.Set("actionGroup", *options.ActionGroup) + } + if options != nil && options.Name != nil { + reqQP.Set("name", *options.Name) + } + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ActionRulesClient) listBySubscriptionHandleResponse(resp *http.Response) (ActionRulesListBySubscriptionResponse, error) { + result := ActionRulesListBySubscriptionResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ActionRulesList); err != nil { + return ActionRulesListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *ActionRulesClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Update enabled flag and/or tags for the given action rule +// If the operation fails it returns the *ErrorResponse error type. +func (client *ActionRulesClient) Update(ctx context.Context, resourceGroupName string, actionRuleName string, actionRulePatch PatchObject, options *ActionRulesUpdateOptions) (ActionRulesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, actionRuleName, actionRulePatch, options) + if err != nil { + return ActionRulesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ActionRulesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ActionRulesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *ActionRulesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, actionRuleName string, actionRulePatch PatchObject, options *ActionRulesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AlertsManagement/actionRules/{actionRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if actionRuleName == "" { + return nil, errors.New("parameter actionRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{actionRuleName}", url.PathEscape(actionRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, actionRulePatch) +} + +// updateHandleResponse handles the Update response. +func (client *ActionRulesClient) updateHandleResponse(resp *http.Response) (ActionRulesUpdateResponse, error) { + result := ActionRulesUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.ActionRule); err != nil { + return ActionRulesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *ActionRulesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_alerts_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_alerts_client.go new file mode 100644 index 000000000000..a0ae16dd536a --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_alerts_client.go @@ -0,0 +1,470 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// AlertsClient contains the methods for the Alerts group. +// Don't use this type directly, use NewAlertsClient() instead. +type AlertsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAlertsClient creates a new instance of AlertsClient with the specified values. +func NewAlertsClient(con *arm.Connection, subscriptionID string) *AlertsClient { + return &AlertsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// ChangeState - Change the state of an alert. +// If the operation fails it returns the *ErrorResponseAutoGenerated error type. +func (client *AlertsClient) ChangeState(ctx context.Context, alertID string, newState AlertState, options *AlertsChangeStateOptions) (AlertsChangeStateResponse, error) { + req, err := client.changeStateCreateRequest(ctx, alertID, newState, options) + if err != nil { + return AlertsChangeStateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AlertsChangeStateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AlertsChangeStateResponse{}, client.changeStateHandleError(resp) + } + return client.changeStateHandleResponse(resp) +} + +// changeStateCreateRequest creates the ChangeState request. +func (client *AlertsClient) changeStateCreateRequest(ctx context.Context, alertID string, newState AlertState, options *AlertsChangeStateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/changestate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if alertID == "" { + return nil, errors.New("parameter alertID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertId}", url.PathEscape(alertID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + reqQP.Set("newState", string(newState)) + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// changeStateHandleResponse handles the ChangeState response. +func (client *AlertsClient) changeStateHandleResponse(resp *http.Response) (AlertsChangeStateResponse, error) { + result := AlertsChangeStateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Alert); err != nil { + return AlertsChangeStateResponse{}, err + } + return result, nil +} + +// changeStateHandleError handles the ChangeState error response. +func (client *AlertsClient) changeStateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetAll - List all existing alerts, where the results can be filtered on the basis of multiple parameters (e.g. time range). The results can then be sorted +// on the basis specific fields, with the default being +// lastModifiedDateTime. +// If the operation fails it returns the *ErrorResponseAutoGenerated error type. +func (client *AlertsClient) GetAll(options *AlertsGetAllOptions) *AlertsGetAllPager { + return &AlertsGetAllPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.getAllCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp AlertsGetAllResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AlertsList.NextLink) + }, + } +} + +// getAllCreateRequest creates the GetAll request. +func (client *AlertsClient) getAllCreateRequest(ctx context.Context, options *AlertsGetAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.AlertState != nil { + reqQP.Set("alertState", string(*options.AlertState)) + } + if options != nil && options.AlertRule != nil { + reqQP.Set("alertRule", *options.AlertRule) + } + if options != nil && options.SmartGroupID != nil { + reqQP.Set("smartGroupId", *options.SmartGroupID) + } + if options != nil && options.IncludeContext != nil { + reqQP.Set("includeContext", strconv.FormatBool(*options.IncludeContext)) + } + if options != nil && options.IncludeEgressConfig != nil { + reqQP.Set("includeEgressConfig", strconv.FormatBool(*options.IncludeEgressConfig)) + } + if options != nil && options.PageCount != nil { + reqQP.Set("pageCount", strconv.FormatInt(int64(*options.PageCount), 10)) + } + if options != nil && options.SortBy != nil { + reqQP.Set("sortBy", string(*options.SortBy)) + } + if options != nil && options.SortOrder != nil { + reqQP.Set("sortOrder", string(*options.SortOrder)) + } + if options != nil && options.Select != nil { + reqQP.Set("select", *options.Select) + } + if options != nil && options.TimeRange != nil { + reqQP.Set("timeRange", string(*options.TimeRange)) + } + if options != nil && options.CustomTimeRange != nil { + reqQP.Set("customTimeRange", *options.CustomTimeRange) + } + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *AlertsClient) getAllHandleResponse(resp *http.Response) (AlertsGetAllResponse, error) { + result := AlertsGetAllResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertsList); err != nil { + return AlertsGetAllResponse{}, err + } + return result, nil +} + +// getAllHandleError handles the GetAll error response. +func (client *AlertsClient) getAllHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetByID - Get information related to a specific alert +// If the operation fails it returns the *ErrorResponseAutoGenerated error type. +func (client *AlertsClient) GetByID(ctx context.Context, alertID string, options *AlertsGetByIDOptions) (AlertsGetByIDResponse, error) { + req, err := client.getByIDCreateRequest(ctx, alertID, options) + if err != nil { + return AlertsGetByIDResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AlertsGetByIDResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AlertsGetByIDResponse{}, client.getByIDHandleError(resp) + } + return client.getByIDHandleResponse(resp) +} + +// getByIDCreateRequest creates the GetByID request. +func (client *AlertsClient) getByIDCreateRequest(ctx context.Context, alertID string, options *AlertsGetByIDOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if alertID == "" { + return nil, errors.New("parameter alertID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertId}", url.PathEscape(alertID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getByIDHandleResponse handles the GetByID response. +func (client *AlertsClient) getByIDHandleResponse(resp *http.Response) (AlertsGetByIDResponse, error) { + result := AlertsGetByIDResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Alert); err != nil { + return AlertsGetByIDResponse{}, err + } + return result, nil +} + +// getByIDHandleError handles the GetByID error response. +func (client *AlertsClient) getByIDHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetHistory - Get the history of an alert, which captures any monitor condition changes (Fired/Resolved) and alert state changes (New/Acknowledged/Closed). +// If the operation fails it returns the *ErrorResponseAutoGenerated error type. +func (client *AlertsClient) GetHistory(ctx context.Context, alertID string, options *AlertsGetHistoryOptions) (AlertsGetHistoryResponse, error) { + req, err := client.getHistoryCreateRequest(ctx, alertID, options) + if err != nil { + return AlertsGetHistoryResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AlertsGetHistoryResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AlertsGetHistoryResponse{}, client.getHistoryHandleError(resp) + } + return client.getHistoryHandleResponse(resp) +} + +// getHistoryCreateRequest creates the GetHistory request. +func (client *AlertsClient) getHistoryCreateRequest(ctx context.Context, alertID string, options *AlertsGetHistoryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alerts/{alertId}/history" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if alertID == "" { + return nil, errors.New("parameter alertID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertId}", url.PathEscape(alertID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHistoryHandleResponse handles the GetHistory response. +func (client *AlertsClient) getHistoryHandleResponse(resp *http.Response) (AlertsGetHistoryResponse, error) { + result := AlertsGetHistoryResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertModification); err != nil { + return AlertsGetHistoryResponse{}, err + } + return result, nil +} + +// getHistoryHandleError handles the GetHistory error response. +func (client *AlertsClient) getHistoryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetSummary - Get a summarized count of your alerts grouped by various parameters (e.g. grouping by 'Severity' returns the count of alerts for each severity). +// If the operation fails it returns the *ErrorResponseAutoGenerated error type. +func (client *AlertsClient) GetSummary(ctx context.Context, groupby AlertsSummaryGroupByFields, options *AlertsGetSummaryOptions) (AlertsGetSummaryResponse, error) { + req, err := client.getSummaryCreateRequest(ctx, groupby, options) + if err != nil { + return AlertsGetSummaryResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AlertsGetSummaryResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AlertsGetSummaryResponse{}, client.getSummaryHandleError(resp) + } + return client.getSummaryHandleResponse(resp) +} + +// getSummaryCreateRequest creates the GetSummary request. +func (client *AlertsClient) getSummaryCreateRequest(ctx context.Context, groupby AlertsSummaryGroupByFields, options *AlertsGetSummaryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/alertsSummary" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("groupby", string(groupby)) + if options != nil && options.IncludeSmartGroupsCount != nil { + reqQP.Set("includeSmartGroupsCount", strconv.FormatBool(*options.IncludeSmartGroupsCount)) + } + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.AlertState != nil { + reqQP.Set("alertState", string(*options.AlertState)) + } + if options != nil && options.AlertRule != nil { + reqQP.Set("alertRule", *options.AlertRule) + } + if options != nil && options.TimeRange != nil { + reqQP.Set("timeRange", string(*options.TimeRange)) + } + if options != nil && options.CustomTimeRange != nil { + reqQP.Set("customTimeRange", *options.CustomTimeRange) + } + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getSummaryHandleResponse handles the GetSummary response. +func (client *AlertsClient) getSummaryHandleResponse(resp *http.Response) (AlertsGetSummaryResponse, error) { + result := AlertsGetSummaryResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertsSummary); err != nil { + return AlertsGetSummaryResponse{}, err + } + return result, nil +} + +// getSummaryHandleError handles the GetSummary error response. +func (client *AlertsClient) getSummaryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// MetaData - List alerts meta data information based on value of identifier parameter. +// If the operation fails it returns a generic error. +func (client *AlertsClient) MetaData(ctx context.Context, identifier Identifier, options *AlertsMetaDataOptions) (AlertsMetaDataResponse, error) { + req, err := client.metaDataCreateRequest(ctx, identifier, options) + if err != nil { + return AlertsMetaDataResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AlertsMetaDataResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AlertsMetaDataResponse{}, client.metaDataHandleError(resp) + } + return client.metaDataHandleResponse(resp) +} + +// metaDataCreateRequest creates the MetaData request. +func (client *AlertsClient) metaDataCreateRequest(ctx context.Context, identifier Identifier, options *AlertsMetaDataOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.AlertsManagement/alertsMetaData" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + reqQP.Set("identifier", string(identifier)) + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// metaDataHandleResponse handles the MetaData response. +func (client *AlertsClient) metaDataHandleResponse(resp *http.Response) (AlertsMetaDataResponse, error) { + result := AlertsMetaDataResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertsMetaData); err != nil { + return AlertsMetaDataResponse{}, err + } + return result, nil +} + +// metaDataHandleError handles the MetaData error response. +func (client *AlertsClient) metaDataHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_constants.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_constants.go new file mode 100644 index 000000000000..aca6205f77c2 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_constants.go @@ -0,0 +1,543 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +const ( + module = "armalertsmanagement" + version = "v0.1.1" +) + +// ActionRuleStatus - Indicates if the given action rule is enabled or disabled +type ActionRuleStatus string + +const ( + ActionRuleStatusDisabled ActionRuleStatus = "Disabled" + ActionRuleStatusEnabled ActionRuleStatus = "Enabled" +) + +// PossibleActionRuleStatusValues returns the possible values for the ActionRuleStatus const type. +func PossibleActionRuleStatusValues() []ActionRuleStatus { + return []ActionRuleStatus{ + ActionRuleStatusDisabled, + ActionRuleStatusEnabled, + } +} + +// ToPtr returns a *ActionRuleStatus pointing to the current value. +func (c ActionRuleStatus) ToPtr() *ActionRuleStatus { + return &c +} + +// ActionRuleType - Indicates type of action rule +type ActionRuleType string + +const ( + ActionRuleTypeActionGroup ActionRuleType = "ActionGroup" + ActionRuleTypeDiagnostics ActionRuleType = "Diagnostics" + ActionRuleTypeSuppression ActionRuleType = "Suppression" +) + +// PossibleActionRuleTypeValues returns the possible values for the ActionRuleType const type. +func PossibleActionRuleTypeValues() []ActionRuleType { + return []ActionRuleType{ + ActionRuleTypeActionGroup, + ActionRuleTypeDiagnostics, + ActionRuleTypeSuppression, + } +} + +// ToPtr returns a *ActionRuleType pointing to the current value. +func (c ActionRuleType) ToPtr() *ActionRuleType { + return &c +} + +// AlertModificationEvent - Reason for the modification +type AlertModificationEvent string + +const ( + AlertModificationEventAlertCreated AlertModificationEvent = "AlertCreated" + AlertModificationEventStateChange AlertModificationEvent = "StateChange" + AlertModificationEventMonitorConditionChange AlertModificationEvent = "MonitorConditionChange" + AlertModificationEventSeverityChange AlertModificationEvent = "SeverityChange" + AlertModificationEventActionRuleTriggered AlertModificationEvent = "ActionRuleTriggered" + AlertModificationEventActionRuleSuppressed AlertModificationEvent = "ActionRuleSuppressed" + AlertModificationEventActionsTriggered AlertModificationEvent = "ActionsTriggered" + AlertModificationEventActionsSuppressed AlertModificationEvent = "ActionsSuppressed" + AlertModificationEventActionsFailed AlertModificationEvent = "ActionsFailed" +) + +// PossibleAlertModificationEventValues returns the possible values for the AlertModificationEvent const type. +func PossibleAlertModificationEventValues() []AlertModificationEvent { + return []AlertModificationEvent{ + AlertModificationEventAlertCreated, + AlertModificationEventStateChange, + AlertModificationEventMonitorConditionChange, + AlertModificationEventSeverityChange, + AlertModificationEventActionRuleTriggered, + AlertModificationEventActionRuleSuppressed, + AlertModificationEventActionsTriggered, + AlertModificationEventActionsSuppressed, + AlertModificationEventActionsFailed, + } +} + +// ToPtr returns a *AlertModificationEvent pointing to the current value. +func (c AlertModificationEvent) ToPtr() *AlertModificationEvent { + return &c +} + +// AlertRuleState - The alert rule state. +type AlertRuleState string + +const ( + AlertRuleStateDisabled AlertRuleState = "Disabled" + AlertRuleStateEnabled AlertRuleState = "Enabled" +) + +// PossibleAlertRuleStateValues returns the possible values for the AlertRuleState const type. +func PossibleAlertRuleStateValues() []AlertRuleState { + return []AlertRuleState{ + AlertRuleStateDisabled, + AlertRuleStateEnabled, + } +} + +// ToPtr returns a *AlertRuleState pointing to the current value. +func (c AlertRuleState) ToPtr() *AlertRuleState { + return &c +} + +type AlertState string + +const ( + AlertStateAcknowledged AlertState = "Acknowledged" + AlertStateClosed AlertState = "Closed" + AlertStateNew AlertState = "New" +) + +// PossibleAlertStateValues returns the possible values for the AlertState const type. +func PossibleAlertStateValues() []AlertState { + return []AlertState{ + AlertStateAcknowledged, + AlertStateClosed, + AlertStateNew, + } +} + +// ToPtr returns a *AlertState pointing to the current value. +func (c AlertState) ToPtr() *AlertState { + return &c +} + +type AlertsSortByFields string + +const ( + AlertsSortByFieldsAlertState AlertsSortByFields = "alertState" + AlertsSortByFieldsLastModifiedDateTime AlertsSortByFields = "lastModifiedDateTime" + AlertsSortByFieldsMonitorCondition AlertsSortByFields = "monitorCondition" + AlertsSortByFieldsName AlertsSortByFields = "name" + AlertsSortByFieldsSeverity AlertsSortByFields = "severity" + AlertsSortByFieldsStartDateTime AlertsSortByFields = "startDateTime" + AlertsSortByFieldsTargetResource AlertsSortByFields = "targetResource" + AlertsSortByFieldsTargetResourceGroup AlertsSortByFields = "targetResourceGroup" + AlertsSortByFieldsTargetResourceName AlertsSortByFields = "targetResourceName" + AlertsSortByFieldsTargetResourceType AlertsSortByFields = "targetResourceType" +) + +// PossibleAlertsSortByFieldsValues returns the possible values for the AlertsSortByFields const type. +func PossibleAlertsSortByFieldsValues() []AlertsSortByFields { + return []AlertsSortByFields{ + AlertsSortByFieldsAlertState, + AlertsSortByFieldsLastModifiedDateTime, + AlertsSortByFieldsMonitorCondition, + AlertsSortByFieldsName, + AlertsSortByFieldsSeverity, + AlertsSortByFieldsStartDateTime, + AlertsSortByFieldsTargetResource, + AlertsSortByFieldsTargetResourceGroup, + AlertsSortByFieldsTargetResourceName, + AlertsSortByFieldsTargetResourceType, + } +} + +// ToPtr returns a *AlertsSortByFields pointing to the current value. +func (c AlertsSortByFields) ToPtr() *AlertsSortByFields { + return &c +} + +type AlertsSummaryGroupByFields string + +const ( + AlertsSummaryGroupByFieldsAlertRule AlertsSummaryGroupByFields = "alertRule" + AlertsSummaryGroupByFieldsAlertState AlertsSummaryGroupByFields = "alertState" + AlertsSummaryGroupByFieldsMonitorCondition AlertsSummaryGroupByFields = "monitorCondition" + AlertsSummaryGroupByFieldsMonitorService AlertsSummaryGroupByFields = "monitorService" + AlertsSummaryGroupByFieldsSeverity AlertsSummaryGroupByFields = "severity" + AlertsSummaryGroupByFieldsSignalType AlertsSummaryGroupByFields = "signalType" +) + +// PossibleAlertsSummaryGroupByFieldsValues returns the possible values for the AlertsSummaryGroupByFields const type. +func PossibleAlertsSummaryGroupByFieldsValues() []AlertsSummaryGroupByFields { + return []AlertsSummaryGroupByFields{ + AlertsSummaryGroupByFieldsAlertRule, + AlertsSummaryGroupByFieldsAlertState, + AlertsSummaryGroupByFieldsMonitorCondition, + AlertsSummaryGroupByFieldsMonitorService, + AlertsSummaryGroupByFieldsSeverity, + AlertsSummaryGroupByFieldsSignalType, + } +} + +// ToPtr returns a *AlertsSummaryGroupByFields pointing to the current value. +func (c AlertsSummaryGroupByFields) ToPtr() *AlertsSummaryGroupByFields { + return &c +} + +type Enum11 string + +const ( + Enum11Asc Enum11 = "asc" + Enum11Desc Enum11 = "desc" +) + +// PossibleEnum11Values returns the possible values for the Enum11 const type. +func PossibleEnum11Values() []Enum11 { + return []Enum11{ + Enum11Asc, + Enum11Desc, + } +} + +// ToPtr returns a *Enum11 pointing to the current value. +func (c Enum11) ToPtr() *Enum11 { + return &c +} + +type Identifier string + +const ( + IdentifierMonitorServiceList Identifier = "MonitorServiceList" +) + +// PossibleIdentifierValues returns the possible values for the Identifier const type. +func PossibleIdentifierValues() []Identifier { + return []Identifier{ + IdentifierMonitorServiceList, + } +} + +// ToPtr returns a *Identifier pointing to the current value. +func (c Identifier) ToPtr() *Identifier { + return &c +} + +// MetadataIdentifier - Identification of the information to be retrieved by API call +type MetadataIdentifier string + +const ( + MetadataIdentifierMonitorServiceList MetadataIdentifier = "MonitorServiceList" +) + +// PossibleMetadataIdentifierValues returns the possible values for the MetadataIdentifier const type. +func PossibleMetadataIdentifierValues() []MetadataIdentifier { + return []MetadataIdentifier{ + MetadataIdentifierMonitorServiceList, + } +} + +// ToPtr returns a *MetadataIdentifier pointing to the current value. +func (c MetadataIdentifier) ToPtr() *MetadataIdentifier { + return &c +} + +type MonitorCondition string + +const ( + MonitorConditionFired MonitorCondition = "Fired" + MonitorConditionResolved MonitorCondition = "Resolved" +) + +// PossibleMonitorConditionValues returns the possible values for the MonitorCondition const type. +func PossibleMonitorConditionValues() []MonitorCondition { + return []MonitorCondition{ + MonitorConditionFired, + MonitorConditionResolved, + } +} + +// ToPtr returns a *MonitorCondition pointing to the current value. +func (c MonitorCondition) ToPtr() *MonitorCondition { + return &c +} + +type MonitorService string + +const ( + MonitorServiceActivityLogAdministrative MonitorService = "ActivityLog Administrative" + MonitorServiceActivityLogAutoscale MonitorService = "ActivityLog Autoscale" + MonitorServiceActivityLogPolicy MonitorService = "ActivityLog Policy" + MonitorServiceActivityLogRecommendation MonitorService = "ActivityLog Recommendation" + MonitorServiceActivityLogSecurity MonitorService = "ActivityLog Security" + MonitorServiceApplicationInsights MonitorService = "Application Insights" + MonitorServiceLogAnalytics MonitorService = "Log Analytics" + MonitorServiceNagios MonitorService = "Nagios" + MonitorServicePlatform MonitorService = "Platform" + MonitorServiceSCOM MonitorService = "SCOM" + MonitorServiceServiceHealth MonitorService = "ServiceHealth" + MonitorServiceSmartDetector MonitorService = "SmartDetector" + MonitorServiceVMInsights MonitorService = "VM Insights" + MonitorServiceZabbix MonitorService = "Zabbix" +) + +// PossibleMonitorServiceValues returns the possible values for the MonitorService const type. +func PossibleMonitorServiceValues() []MonitorService { + return []MonitorService{ + MonitorServiceActivityLogAdministrative, + MonitorServiceActivityLogAutoscale, + MonitorServiceActivityLogPolicy, + MonitorServiceActivityLogRecommendation, + MonitorServiceActivityLogSecurity, + MonitorServiceApplicationInsights, + MonitorServiceLogAnalytics, + MonitorServiceNagios, + MonitorServicePlatform, + MonitorServiceSCOM, + MonitorServiceServiceHealth, + MonitorServiceSmartDetector, + MonitorServiceVMInsights, + MonitorServiceZabbix, + } +} + +// ToPtr returns a *MonitorService pointing to the current value. +func (c MonitorService) ToPtr() *MonitorService { + return &c +} + +// Operator - operator for a given condition +type Operator string + +const ( + OperatorContains Operator = "Contains" + OperatorDoesNotContain Operator = "DoesNotContain" + OperatorEquals Operator = "Equals" + OperatorNotEquals Operator = "NotEquals" +) + +// PossibleOperatorValues returns the possible values for the Operator const type. +func PossibleOperatorValues() []Operator { + return []Operator{ + OperatorContains, + OperatorDoesNotContain, + OperatorEquals, + OperatorNotEquals, + } +} + +// ToPtr returns a *Operator pointing to the current value. +func (c Operator) ToPtr() *Operator { + return &c +} + +// ScopeType - type of target scope +type ScopeType string + +const ( + ScopeTypeResource ScopeType = "Resource" + ScopeTypeResourceGroup ScopeType = "ResourceGroup" + ScopeTypeSubscription ScopeType = "Subscription" +) + +// PossibleScopeTypeValues returns the possible values for the ScopeType const type. +func PossibleScopeTypeValues() []ScopeType { + return []ScopeType{ + ScopeTypeResource, + ScopeTypeResourceGroup, + ScopeTypeSubscription, + } +} + +// ToPtr returns a *ScopeType pointing to the current value. +func (c ScopeType) ToPtr() *ScopeType { + return &c +} + +type Severity string + +const ( + SeveritySev0 Severity = "Sev0" + SeveritySev1 Severity = "Sev1" + SeveritySev2 Severity = "Sev2" + SeveritySev3 Severity = "Sev3" + SeveritySev4 Severity = "Sev4" +) + +// PossibleSeverityValues returns the possible values for the Severity const type. +func PossibleSeverityValues() []Severity { + return []Severity{ + SeveritySev0, + SeveritySev1, + SeveritySev2, + SeveritySev3, + SeveritySev4, + } +} + +// ToPtr returns a *Severity pointing to the current value. +func (c Severity) ToPtr() *Severity { + return &c +} + +// SignalType - The type of signal the alert is based on, which could be metrics, logs or activity logs. +type SignalType string + +const ( + SignalTypeLog SignalType = "Log" + SignalTypeMetric SignalType = "Metric" + SignalTypeUnknown SignalType = "Unknown" +) + +// PossibleSignalTypeValues returns the possible values for the SignalType const type. +func PossibleSignalTypeValues() []SignalType { + return []SignalType{ + SignalTypeLog, + SignalTypeMetric, + SignalTypeUnknown, + } +} + +// ToPtr returns a *SignalType pointing to the current value. +func (c SignalType) ToPtr() *SignalType { + return &c +} + +// SmartGroupModificationEvent - Reason for the modification +type SmartGroupModificationEvent string + +const ( + SmartGroupModificationEventSmartGroupCreated SmartGroupModificationEvent = "SmartGroupCreated" + SmartGroupModificationEventStateChange SmartGroupModificationEvent = "StateChange" + SmartGroupModificationEventAlertAdded SmartGroupModificationEvent = "AlertAdded" + SmartGroupModificationEventAlertRemoved SmartGroupModificationEvent = "AlertRemoved" +) + +// PossibleSmartGroupModificationEventValues returns the possible values for the SmartGroupModificationEvent const type. +func PossibleSmartGroupModificationEventValues() []SmartGroupModificationEvent { + return []SmartGroupModificationEvent{ + SmartGroupModificationEventSmartGroupCreated, + SmartGroupModificationEventStateChange, + SmartGroupModificationEventAlertAdded, + SmartGroupModificationEventAlertRemoved, + } +} + +// ToPtr returns a *SmartGroupModificationEvent pointing to the current value. +func (c SmartGroupModificationEvent) ToPtr() *SmartGroupModificationEvent { + return &c +} + +type SmartGroupsSortByFields string + +const ( + SmartGroupsSortByFieldsAlertsCount SmartGroupsSortByFields = "alertsCount" + SmartGroupsSortByFieldsLastModifiedDateTime SmartGroupsSortByFields = "lastModifiedDateTime" + SmartGroupsSortByFieldsSeverity SmartGroupsSortByFields = "severity" + SmartGroupsSortByFieldsStartDateTime SmartGroupsSortByFields = "startDateTime" + SmartGroupsSortByFieldsState SmartGroupsSortByFields = "state" +) + +// PossibleSmartGroupsSortByFieldsValues returns the possible values for the SmartGroupsSortByFields const type. +func PossibleSmartGroupsSortByFieldsValues() []SmartGroupsSortByFields { + return []SmartGroupsSortByFields{ + SmartGroupsSortByFieldsAlertsCount, + SmartGroupsSortByFieldsLastModifiedDateTime, + SmartGroupsSortByFieldsSeverity, + SmartGroupsSortByFieldsStartDateTime, + SmartGroupsSortByFieldsState, + } +} + +// ToPtr returns a *SmartGroupsSortByFields pointing to the current value. +func (c SmartGroupsSortByFields) ToPtr() *SmartGroupsSortByFields { + return &c +} + +// State - Smart group state +type State string + +const ( + StateAcknowledged State = "Acknowledged" + StateClosed State = "Closed" + StateNew State = "New" +) + +// PossibleStateValues returns the possible values for the State const type. +func PossibleStateValues() []State { + return []State{ + StateAcknowledged, + StateClosed, + StateNew, + } +} + +// ToPtr returns a *State pointing to the current value. +func (c State) ToPtr() *State { + return &c +} + +// SuppressionType - Specifies when the suppression should be applied +type SuppressionType string + +const ( + SuppressionTypeAlways SuppressionType = "Always" + SuppressionTypeDaily SuppressionType = "Daily" + SuppressionTypeMonthly SuppressionType = "Monthly" + SuppressionTypeOnce SuppressionType = "Once" + SuppressionTypeWeekly SuppressionType = "Weekly" +) + +// PossibleSuppressionTypeValues returns the possible values for the SuppressionType const type. +func PossibleSuppressionTypeValues() []SuppressionType { + return []SuppressionType{ + SuppressionTypeAlways, + SuppressionTypeDaily, + SuppressionTypeMonthly, + SuppressionTypeOnce, + SuppressionTypeWeekly, + } +} + +// ToPtr returns a *SuppressionType pointing to the current value. +func (c SuppressionType) ToPtr() *SuppressionType { + return &c +} + +type TimeRange string + +const ( + TimeRangeOneD TimeRange = "1d" + TimeRangeOneH TimeRange = "1h" + TimeRangeSevenD TimeRange = "7d" + TimeRangeThirtyD TimeRange = "30d" +) + +// PossibleTimeRangeValues returns the possible values for the TimeRange const type. +func PossibleTimeRangeValues() []TimeRange { + return []TimeRange{ + TimeRangeOneD, + TimeRangeOneH, + TimeRangeSevenD, + TimeRangeThirtyD, + } +} + +// ToPtr returns a *TimeRange pointing to the current value. +func (c TimeRange) ToPtr() *TimeRange { + return &c +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_models.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_models.go new file mode 100644 index 000000000000..11479ad259db --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_models.go @@ -0,0 +1,1928 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "encoding/json" + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "reflect" + "time" +) + +// ActionGroup - Action rule with action group configuration +type ActionGroup struct { + ActionRuleProperties + // REQUIRED; Action group to trigger if action rule matches + ActionGroupID *string `json:"actionGroupId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ActionGroup. +func (a ActionGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ActionRuleProperties.marshalInternal(objectMap, ActionRuleTypeActionGroup) + populate(objectMap, "actionGroupId", a.ActionGroupID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionGroup. +func (a *ActionGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "actionGroupId": + err = unpopulate(val, &a.ActionGroupID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.ActionRuleProperties.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ActionGroupsInformation - The Action Groups information, used by the alert rule. +type ActionGroupsInformation struct { + // REQUIRED; The Action Group resource IDs. + GroupIDs []*string `json:"groupIds,omitempty"` + + // An optional custom email subject to use in email notifications. + CustomEmailSubject *string `json:"customEmailSubject,omitempty"` + + // An optional custom web-hook payload to use in web-hook notifications. + CustomWebhookPayload *string `json:"customWebhookPayload,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ActionGroupsInformation. +func (a ActionGroupsInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "customEmailSubject", a.CustomEmailSubject) + populate(objectMap, "customWebhookPayload", a.CustomWebhookPayload) + populate(objectMap, "groupIds", a.GroupIDs) + return json.Marshal(objectMap) +} + +// ActionRule - Action rule object containing target scope, conditions and suppression logic +type ActionRule struct { + ManagedResource + // action rule properties + Properties ActionRulePropertiesClassification `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ActionRule. +func (a ActionRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ManagedResource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionRule. +func (a *ActionRule) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + a.Properties, err = unmarshalActionRulePropertiesClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.ManagedResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ActionRulePropertiesClassification provides polymorphic access to related types. +// Call the interface's GetActionRuleProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ActionGroup, *ActionRuleProperties, *Diagnostics, *Suppression +type ActionRulePropertiesClassification interface { + // GetActionRuleProperties returns the ActionRuleProperties content of the underlying type. + GetActionRuleProperties() *ActionRuleProperties +} + +// ActionRuleProperties - Action rule properties defining scope, conditions, suppression logic for action rule +type ActionRuleProperties struct { + // REQUIRED; Indicates type of action rule + Type *ActionRuleType `json:"type,omitempty"` + + // conditions on which alerts will be filtered + Conditions *Conditions `json:"conditions,omitempty"` + + // Description of action rule + Description *string `json:"description,omitempty"` + + // scope on which action rule will apply + Scope *Scope `json:"scope,omitempty"` + + // Indicates if the given action rule is enabled or disabled + Status *ActionRuleStatus `json:"status,omitempty"` + + // READ-ONLY; Creation time of action rule. Date-Time in ISO-8601 format. + CreatedAt *time.Time `json:"createdAt,omitempty" azure:"ro"` + + // READ-ONLY; Created by user name. + CreatedBy *string `json:"createdBy,omitempty" azure:"ro"` + + // READ-ONLY; Last updated time of action rule. Date-Time in ISO-8601 format. + LastModifiedAt *time.Time `json:"lastModifiedAt,omitempty" azure:"ro"` + + // READ-ONLY; Last modified by user name. + LastModifiedBy *string `json:"lastModifiedBy,omitempty" azure:"ro"` +} + +// GetActionRuleProperties implements the ActionRulePropertiesClassification interface for type ActionRuleProperties. +func (a *ActionRuleProperties) GetActionRuleProperties() *ActionRuleProperties { return a } + +// UnmarshalJSON implements the json.Unmarshaller interface for type ActionRuleProperties. +func (a *ActionRuleProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return a.unmarshalInternal(rawMsg) +} + +func (a ActionRuleProperties) marshalInternal(objectMap map[string]interface{}, discValue ActionRuleType) { + populate(objectMap, "conditions", a.Conditions) + populate(objectMap, "createdAt", (*timeRFC3339)(a.CreatedAt)) + populate(objectMap, "createdBy", a.CreatedBy) + populate(objectMap, "description", a.Description) + populate(objectMap, "lastModifiedAt", (*timeRFC3339)(a.LastModifiedAt)) + populate(objectMap, "lastModifiedBy", a.LastModifiedBy) + populate(objectMap, "scope", a.Scope) + populate(objectMap, "status", a.Status) + a.Type = &discValue + objectMap["type"] = a.Type +} + +func (a *ActionRuleProperties) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "conditions": + err = unpopulate(val, &a.Conditions) + delete(rawMsg, key) + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, &a.CreatedBy) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &a.Description) + delete(rawMsg, key) + case "lastModifiedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.LastModifiedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, &a.LastModifiedBy) + delete(rawMsg, key) + case "scope": + err = unpopulate(val, &a.Scope) + delete(rawMsg, key) + case "status": + err = unpopulate(val, &a.Status) + delete(rawMsg, key) + case "type": + err = unpopulate(val, &a.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ActionRulesCreateUpdateOptions contains the optional parameters for the ActionRules.CreateUpdate method. +type ActionRulesCreateUpdateOptions struct { + // placeholder for future optional parameters +} + +// ActionRulesDeleteOptions contains the optional parameters for the ActionRules.Delete method. +type ActionRulesDeleteOptions struct { + // placeholder for future optional parameters +} + +// ActionRulesGetByNameOptions contains the optional parameters for the ActionRules.GetByName method. +type ActionRulesGetByNameOptions struct { + // placeholder for future optional parameters +} + +// ActionRulesList - List of action rules +type ActionRulesList struct { + // URL to fetch the next set of action rules + NextLink *string `json:"nextLink,omitempty"` + + // List of action rules + Value []*ActionRule `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ActionRulesList. +func (a ActionRulesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// ActionRulesListByResourceGroupOptions contains the optional parameters for the ActionRules.ListByResourceGroup method. +type ActionRulesListByResourceGroupOptions struct { + // filter by action group configured as part of action rule + ActionGroup *string + // filter by alert rule id + AlertRuleID *string + // filter by alert rule description + Description *string + // filter by impacted/target scope (provide comma separated list for multiple scopes). The value should be an well constructed ARM id of the scope. + ImpactedScope *string + // Filter by monitor service which generates the alert instance. Default value is select all. + MonitorService *MonitorService + // filter by action rule name + Name *string + // Filter by severity. Default value is select all. + Severity *Severity + // Filter by target resource( which is full ARM ID) Default value is select all. + TargetResource *string + // Filter by target resource group name. Default value is select all. + TargetResourceGroup *string + // Filter by target resource type. Default value is select all. + TargetResourceType *string +} + +// ActionRulesListBySubscriptionOptions contains the optional parameters for the ActionRules.ListBySubscription method. +type ActionRulesListBySubscriptionOptions struct { + // filter by action group configured as part of action rule + ActionGroup *string + // filter by alert rule id + AlertRuleID *string + // filter by alert rule description + Description *string + // filter by impacted/target scope (provide comma separated list for multiple scopes). The value should be an well constructed ARM id of the scope. + ImpactedScope *string + // Filter by monitor service which generates the alert instance. Default value is select all. + MonitorService *MonitorService + // filter by action rule name + Name *string + // Filter by severity. Default value is select all. + Severity *Severity + // Filter by target resource( which is full ARM ID) Default value is select all. + TargetResource *string + // Filter by target resource group name. Default value is select all. + TargetResourceGroup *string + // Filter by target resource type. Default value is select all. + TargetResourceType *string +} + +// ActionRulesUpdateOptions contains the optional parameters for the ActionRules.Update method. +type ActionRulesUpdateOptions struct { + // placeholder for future optional parameters +} + +// Alert - An alert created in alert management service. +type Alert struct { + Resource + // Alert property bag + Properties *AlertProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Alert. +func (a Alert) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Alert. +func (a *Alert) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AlertModification - Alert Modification details +type AlertModification struct { + Resource + // Properties of the alert modification item. + Properties *AlertModificationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertModification. +func (a AlertModification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertModification. +func (a *AlertModification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AlertModificationItem - Alert modification item. +type AlertModificationItem struct { + // Modification comments + Comments *string `json:"comments,omitempty"` + + // Description of the modification + Description *string `json:"description,omitempty"` + + // Reason for the modification + ModificationEvent *AlertModificationEvent `json:"modificationEvent,omitempty"` + + // Modified date and time + ModifiedAt *string `json:"modifiedAt,omitempty"` + + // Modified user details (Principal client name) + ModifiedBy *string `json:"modifiedBy,omitempty"` + + // New value + NewValue *string `json:"newValue,omitempty"` + + // Old value + OldValue *string `json:"oldValue,omitempty"` +} + +// AlertModificationProperties - Properties of the alert modification item. +type AlertModificationProperties struct { + // Modification details + Modifications []*AlertModificationItem `json:"modifications,omitempty"` + + // READ-ONLY; Unique Id of the alert for which the history is being retrieved + AlertID *string `json:"alertId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertModificationProperties. +func (a AlertModificationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "alertId", a.AlertID) + populate(objectMap, "modifications", a.Modifications) + return json.Marshal(objectMap) +} + +// AlertProperties - Alert property bag +type AlertProperties struct { + // This object contains consistent fields across different monitor services. + Essentials *Essentials `json:"essentials,omitempty"` + + // READ-ONLY; Any object + Context map[string]interface{} `json:"context,omitempty" azure:"ro"` + + // READ-ONLY; Any object + EgressConfig map[string]interface{} `json:"egressConfig,omitempty" azure:"ro"` +} + +// AlertRule - The alert rule information +type AlertRule struct { + AzureResource + // The properties of the alert rule. + Properties *AlertRuleProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRule. +func (a AlertRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.AzureResource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// AlertRulePatchObject - The alert rule patch information +type AlertRulePatchObject struct { + // The properties of the alert rule. + Properties *AlertRulePatchProperties `json:"properties,omitempty"` + + // The resource tags. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; The resource ID. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRulePatchObject. +func (a AlertRulePatchObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", a.ID) + populate(objectMap, "name", a.Name) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) + return json.Marshal(objectMap) +} + +// AlertRulePatchProperties - The alert rule properties. +type AlertRulePatchProperties struct { + // The alert rule actions. + ActionGroups *ActionGroupsInformation `json:"actionGroups,omitempty"` + + // The alert rule description. + Description *string `json:"description,omitempty"` + + // The alert rule frequency in ISO8601 format. The time granularity must be in minutes and minimum value is 5 minutes. + Frequency *string `json:"frequency,omitempty"` + + // The alert rule severity. + Severity *Severity `json:"severity,omitempty"` + + // The alert rule state. + State *AlertRuleState `json:"state,omitempty"` + + // The alert rule throttling information. + Throttling *ThrottlingInformation `json:"throttling,omitempty"` +} + +// AlertRuleProperties - The alert rule properties. +type AlertRuleProperties struct { + // REQUIRED; The alert rule actions. + ActionGroups *ActionGroupsInformation `json:"actionGroups,omitempty"` + + // REQUIRED; The alert rule's detector. + Detector *Detector `json:"detector,omitempty"` + + // REQUIRED; The alert rule frequency in ISO8601 format. The time granularity must be in minutes and minimum value is 5 minutes. + Frequency *string `json:"frequency,omitempty"` + + // REQUIRED; The alert rule resources scope. + Scope []*string `json:"scope,omitempty"` + + // REQUIRED; The alert rule severity. + Severity *Severity `json:"severity,omitempty"` + + // REQUIRED; The alert rule state. + State *AlertRuleState `json:"state,omitempty"` + + // The alert rule description. + Description *string `json:"description,omitempty"` + + // The alert rule throttling information. + Throttling *ThrottlingInformation `json:"throttling,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRuleProperties. +func (a AlertRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "actionGroups", a.ActionGroups) + populate(objectMap, "description", a.Description) + populate(objectMap, "detector", a.Detector) + populate(objectMap, "frequency", a.Frequency) + populate(objectMap, "scope", a.Scope) + populate(objectMap, "severity", a.Severity) + populate(objectMap, "state", a.State) + populate(objectMap, "throttling", a.Throttling) + return json.Marshal(objectMap) +} + +// AlertRulesList - List of Smart Detector alert rules. +type AlertRulesList struct { + // The URL to get the next set of results. + NextLink *string `json:"nextLink,omitempty"` + + // List of Smart Detector alert rules. + Value []*AlertRule `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertRulesList. +func (a AlertRulesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AlertsChangeStateOptions contains the optional parameters for the Alerts.ChangeState method. +type AlertsChangeStateOptions struct { + // placeholder for future optional parameters +} + +// AlertsGetAllOptions contains the optional parameters for the Alerts.GetAll method. +type AlertsGetAllOptions struct { + // Filter by specific alert rule. Default value is to select all. + AlertRule *string + // Filter by state of the alert instance. Default value is to select all. + AlertState *AlertState + // Filter by custom time range in the format / where time is in (ISO-8601 format)'. Permissible values is within 30 days from query + // time. Either timeRange or customTimeRange could be used but not both. Default is none. + CustomTimeRange *string + // Include context which has contextual data specific to the monitor service. Default value is false' + IncludeContext *bool + // Include egress config which would be used for displaying the content in portal. Default value is 'false'. + IncludeEgressConfig *bool + // Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. + MonitorCondition *MonitorCondition + // Filter by monitor service which generates the alert instance. Default value is select all. + MonitorService *MonitorService + // Determines number of alerts returned per page in response. Permissible value is between 1 to 250. When the "includeContent" filter is selected, maximum + // value allowed is 25. Default value is 25. + PageCount *int32 + // This filter allows to selection of the fields(comma separated) which would be part of the essential section. This would allow to project only the required + // fields rather than getting entire content. Default is to fetch all the fields in the essentials section. + Select *string + // Filter by severity. Default value is select all. + Severity *Severity + // Filter the alerts list by the Smart Group Id. Default value is none. + SmartGroupID *string + // Sort the query results by input field, Default value is 'lastModifiedDateTime'. + SortBy *AlertsSortByFields + // Sort the query results order in either ascending or descending. Default value is 'desc' for time fields and 'asc' for others. + SortOrder *Enum11 + // Filter by target resource( which is full ARM ID) Default value is select all. + TargetResource *string + // Filter by target resource group name. Default value is select all. + TargetResourceGroup *string + // Filter by target resource type. Default value is select all. + TargetResourceType *string + // Filter by time range by below listed values. Default value is 1 day. + TimeRange *TimeRange +} + +// AlertsGetByIDOptions contains the optional parameters for the Alerts.GetByID method. +type AlertsGetByIDOptions struct { + // placeholder for future optional parameters +} + +// AlertsGetHistoryOptions contains the optional parameters for the Alerts.GetHistory method. +type AlertsGetHistoryOptions struct { + // placeholder for future optional parameters +} + +// AlertsGetSummaryOptions contains the optional parameters for the Alerts.GetSummary method. +type AlertsGetSummaryOptions struct { + // Filter by specific alert rule. Default value is to select all. + AlertRule *string + // Filter by state of the alert instance. Default value is to select all. + AlertState *AlertState + // Filter by custom time range in the format / where time is in (ISO-8601 format)'. Permissible values is within 30 days from query + // time. Either timeRange or customTimeRange could be used but not both. Default is none. + CustomTimeRange *string + // Include count of the SmartGroups as part of the summary. Default value is 'false'. + IncludeSmartGroupsCount *bool + // Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. + MonitorCondition *MonitorCondition + // Filter by monitor service which generates the alert instance. Default value is select all. + MonitorService *MonitorService + // Filter by severity. Default value is select all. + Severity *Severity + // Filter by target resource( which is full ARM ID) Default value is select all. + TargetResource *string + // Filter by target resource group name. Default value is select all. + TargetResourceGroup *string + // Filter by target resource type. Default value is select all. + TargetResourceType *string + // Filter by time range by below listed values. Default value is 1 day. + TimeRange *TimeRange +} + +// AlertsList - List the alerts. +type AlertsList struct { + // URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` + + // List of alerts + Value []*Alert `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertsList. +func (a AlertsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AlertsMetaData - alert meta data information. +type AlertsMetaData struct { + // alert meta data property bag + Properties AlertsMetaDataPropertiesClassification `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertsMetaData. +func (a AlertsMetaData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertsMetaData. +func (a *AlertsMetaData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + a.Properties, err = unmarshalAlertsMetaDataPropertiesClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AlertsMetaDataOptions contains the optional parameters for the Alerts.MetaData method. +type AlertsMetaDataOptions struct { + // placeholder for future optional parameters +} + +// AlertsMetaDataPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetAlertsMetaDataProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AlertsMetaDataProperties, *MonitorServiceList +type AlertsMetaDataPropertiesClassification interface { + // GetAlertsMetaDataProperties returns the AlertsMetaDataProperties content of the underlying type. + GetAlertsMetaDataProperties() *AlertsMetaDataProperties +} + +// AlertsMetaDataProperties - alert meta data property bag +type AlertsMetaDataProperties struct { + // REQUIRED; Identification of the information to be retrieved by API call + MetadataIdentifier *MetadataIdentifier `json:"metadataIdentifier,omitempty"` +} + +// GetAlertsMetaDataProperties implements the AlertsMetaDataPropertiesClassification interface for type AlertsMetaDataProperties. +func (a *AlertsMetaDataProperties) GetAlertsMetaDataProperties() *AlertsMetaDataProperties { return a } + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertsMetaDataProperties. +func (a *AlertsMetaDataProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return a.unmarshalInternal(rawMsg) +} + +func (a AlertsMetaDataProperties) marshalInternal(objectMap map[string]interface{}, discValue MetadataIdentifier) { + a.MetadataIdentifier = &discValue + objectMap["metadataIdentifier"] = a.MetadataIdentifier +} + +func (a *AlertsMetaDataProperties) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "metadataIdentifier": + err = unpopulate(val, &a.MetadataIdentifier) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AlertsSummary - Summary of alerts based on the input filters and 'groupby' parameters. +type AlertsSummary struct { + Resource + // Group the result set. + Properties *AlertsSummaryGroup `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertsSummary. +func (a AlertsSummary) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AlertsSummary. +func (a *AlertsSummary) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AlertsSummaryGroup - Group the result set. +type AlertsSummaryGroup struct { + // Name of the field aggregated + Groupedby *string `json:"groupedby,omitempty"` + + // Total count of the smart groups. + SmartGroupsCount *int32 `json:"smartGroupsCount,omitempty"` + + // Total count of the result set. + Total *int32 `json:"total,omitempty"` + + // List of the items + Values []*AlertsSummaryGroupItem `json:"values,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertsSummaryGroup. +func (a AlertsSummaryGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupedby", a.Groupedby) + populate(objectMap, "smartGroupsCount", a.SmartGroupsCount) + populate(objectMap, "total", a.Total) + populate(objectMap, "values", a.Values) + return json.Marshal(objectMap) +} + +// AlertsSummaryGroupItem - Alerts summary group item +type AlertsSummaryGroupItem struct { + // Count of the aggregated field + Count *int32 `json:"count,omitempty"` + + // Name of the field aggregated + Groupedby *string `json:"groupedby,omitempty"` + + // Value of the aggregated field + Name *string `json:"name,omitempty"` + + // List of the items + Values []*AlertsSummaryGroupItem `json:"values,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AlertsSummaryGroupItem. +func (a AlertsSummaryGroupItem) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", a.Count) + populate(objectMap, "groupedby", a.Groupedby) + populate(objectMap, "name", a.Name) + populate(objectMap, "values", a.Values) + return json.Marshal(objectMap) +} + +// AzureResource - An Azure resource object +type AzureResource struct { + // The resource location. + Location *string `json:"location,omitempty"` + + // The resource tags. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; The resource ID. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureResource. +func (a AzureResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (a AzureResource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", a.ID) + populate(objectMap, "location", a.Location) + populate(objectMap, "name", a.Name) + populate(objectMap, "tags", a.Tags) + populate(objectMap, "type", a.Type) +} + +// Condition - condition to trigger an action rule +type Condition struct { + // operator for a given condition + Operator *Operator `json:"operator,omitempty"` + + // list of values to match for a given condition. + Values []*string `json:"values,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Condition. +func (c Condition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "operator", c.Operator) + populate(objectMap, "values", c.Values) + return json.Marshal(objectMap) +} + +// Conditions in alert instance to be matched for a given action rule. Default value is all. Multiple values could be provided with comma separation. +type Conditions struct { + // filter alerts by alert context (payload) + AlertContext *Condition `json:"alertContext,omitempty"` + + // filter alerts by alert rule id + AlertRuleID *Condition `json:"alertRuleId,omitempty"` + + // filter alerts by alert rule description + Description *Condition `json:"description,omitempty"` + + // filter alerts by monitor condition + MonitorCondition *Condition `json:"monitorCondition,omitempty"` + + // filter alerts by monitor service + MonitorService *Condition `json:"monitorService,omitempty"` + + // filter alerts by severity + Severity *Condition `json:"severity,omitempty"` + + // filter alerts by target resource type + TargetResourceType *Condition `json:"targetResourceType,omitempty"` +} + +// Detector - The detector information. By default this is not populated, unless it's specified in expandDetector +type Detector struct { + // REQUIRED; The detector id. + ID *string `json:"id,omitempty"` + + // The Smart Detector description. By default this is not populated, unless it's specified in expandDetector + Description *string `json:"description,omitempty"` + + // The Smart Detector image path. By default this is not populated, unless it's specified in expandDetector + ImagePaths []*string `json:"imagePaths,omitempty"` + + // The Smart Detector name. By default this is not populated, unless it's specified in expandDetector + Name *string `json:"name,omitempty"` + + // The detector's parameters.' + Parameters map[string]map[string]interface{} `json:"parameters,omitempty"` + + // The Smart Detector supported resource types. By default this is not populated, unless it's specified in expandDetector + SupportedResourceTypes []*string `json:"supportedResourceTypes,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Detector. +func (d Detector) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "description", d.Description) + populate(objectMap, "id", d.ID) + populate(objectMap, "imagePaths", d.ImagePaths) + populate(objectMap, "name", d.Name) + populate(objectMap, "parameters", d.Parameters) + populate(objectMap, "supportedResourceTypes", d.SupportedResourceTypes) + return json.Marshal(objectMap) +} + +// Diagnostics - Action rule with diagnostics configuration +type Diagnostics struct { + ActionRuleProperties +} + +// MarshalJSON implements the json.Marshaller interface for type Diagnostics. +func (d Diagnostics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.ActionRuleProperties.marshalInternal(objectMap, ActionRuleTypeDiagnostics) + return json.Marshal(objectMap) +} + +// ErrorResponse - An error response from the service. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // Details of error response. + InnerError *ErrorResponseBody `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// ErrorResponseAutoGenerated - An error response from the service. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponseAutoGenerated struct { + raw string + // Details of error response. + InnerError *ErrorResponseBodyAutoGenerated `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponseAutoGenerated. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponseAutoGenerated) Error() string { + return e.raw +} + +// ErrorResponseAutoGenerated2 - An error response from the service. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponseAutoGenerated2 struct { + raw string + // Details of error response. + InnerError *ErrorResponseBodyAutoGenerated2 `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponseAutoGenerated2. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponseAutoGenerated2) Error() string { + return e.raw +} + +// ErrorResponseBody - Details of error response. +type ErrorResponseBody struct { + // Error code, intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + + // A list of additional details about the error. + Details []*ErrorResponseBody `json:"details,omitempty"` + + // Description of the error, intended for display in user interface. + Message *string `json:"message,omitempty"` + + // Target of the particular error, for example name of the property. + Target *string `json:"target,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBody. +func (e ErrorResponseBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponseBodyAutoGenerated - Details of error response. +type ErrorResponseBodyAutoGenerated struct { + // Error code, intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + + // A list of additional details about the error. + Details []*ErrorResponseBodyAutoGenerated `json:"details,omitempty"` + + // Description of the error, intended for display in user interface. + Message *string `json:"message,omitempty"` + + // Target of the particular error, for example name of the property. + Target *string `json:"target,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBodyAutoGenerated. +func (e ErrorResponseBodyAutoGenerated) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponseBodyAutoGenerated2 - Details of error response. +type ErrorResponseBodyAutoGenerated2 struct { + // Error code, intended to be consumed programmatically. + Code *string `json:"code,omitempty"` + + // A list of additional details about the error. + Details []*ErrorResponseBodyAutoGenerated2 `json:"details,omitempty"` + + // Description of the error, intended for display in user interface. + Message *string `json:"message,omitempty"` + + // Target of the particular error, for example name of the property. + Target *string `json:"target,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorResponseBodyAutoGenerated2. +func (e ErrorResponseBodyAutoGenerated2) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// Essentials - This object contains consistent fields across different monitor services. +type Essentials struct { + // Target ARM resource, on which alert got created. + TargetResource *string `json:"targetResource,omitempty"` + + // Resource group of target ARM resource, on which alert got created. + TargetResourceGroup *string `json:"targetResourceGroup,omitempty"` + + // Name of the target ARM resource name, on which alert got created. + TargetResourceName *string `json:"targetResourceName,omitempty"` + + // Resource type of target ARM resource, on which alert got created. + TargetResourceType *string `json:"targetResourceType,omitempty"` + + // READ-ONLY; Rule(monitor) which fired alert instance. Depending on the monitor service, this would be ARM id or name of the rule. + AlertRule *string `json:"alertRule,omitempty" azure:"ro"` + + // READ-ONLY; Alert object state, which can be modified by the user. + AlertState *AlertState `json:"alertState,omitempty" azure:"ro"` + + // READ-ONLY; Last modification time(ISO-8601 format) of alert instance. + LastModifiedDateTime *time.Time `json:"lastModifiedDateTime,omitempty" azure:"ro"` + + // READ-ONLY; User who last modified the alert, in case of monitor service updates user would be 'system', otherwise name of the user. + LastModifiedUserName *string `json:"lastModifiedUserName,omitempty" azure:"ro"` + + // READ-ONLY; Condition of the rule at the monitor service. It represents whether the underlying conditions have crossed the defined alert rule thresholds. + MonitorCondition *MonitorCondition `json:"monitorCondition,omitempty" azure:"ro"` + + // READ-ONLY; Resolved time(ISO-8601 format) of alert instance. This will be updated when monitor service resolves the alert instance because the rule condition + // is no longer met. + MonitorConditionResolvedDateTime *time.Time `json:"monitorConditionResolvedDateTime,omitempty" azure:"ro"` + + // READ-ONLY; Monitor service on which the rule(monitor) is set. + MonitorService *MonitorService `json:"monitorService,omitempty" azure:"ro"` + + // READ-ONLY; Severity of alert Sev0 being highest and Sev4 being lowest. + Severity *Severity `json:"severity,omitempty" azure:"ro"` + + // READ-ONLY; The type of signal the alert is based on, which could be metrics, logs or activity logs. + SignalType *SignalType `json:"signalType,omitempty" azure:"ro"` + + // READ-ONLY; Unique Id of the smart group + SmartGroupID *string `json:"smartGroupId,omitempty" azure:"ro"` + + // READ-ONLY; Verbose reason describing the reason why this alert instance is added to a smart group + SmartGroupingReason *string `json:"smartGroupingReason,omitempty" azure:"ro"` + + // READ-ONLY; Unique Id created by monitor service for each alert instance. This could be used to track the issue at the monitor service, in case of Nagios, + // Zabbix, SCOM etc. + SourceCreatedID *string `json:"sourceCreatedId,omitempty" azure:"ro"` + + // READ-ONLY; Creation time(ISO-8601 format) of alert instance. + StartDateTime *time.Time `json:"startDateTime,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Essentials. +func (e Essentials) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "alertRule", e.AlertRule) + populate(objectMap, "alertState", e.AlertState) + populate(objectMap, "lastModifiedDateTime", (*timeRFC3339)(e.LastModifiedDateTime)) + populate(objectMap, "lastModifiedUserName", e.LastModifiedUserName) + populate(objectMap, "monitorCondition", e.MonitorCondition) + populate(objectMap, "monitorConditionResolvedDateTime", (*timeRFC3339)(e.MonitorConditionResolvedDateTime)) + populate(objectMap, "monitorService", e.MonitorService) + populate(objectMap, "severity", e.Severity) + populate(objectMap, "signalType", e.SignalType) + populate(objectMap, "smartGroupId", e.SmartGroupID) + populate(objectMap, "smartGroupingReason", e.SmartGroupingReason) + populate(objectMap, "sourceCreatedId", e.SourceCreatedID) + populate(objectMap, "startDateTime", (*timeRFC3339)(e.StartDateTime)) + populate(objectMap, "targetResource", e.TargetResource) + populate(objectMap, "targetResourceGroup", e.TargetResourceGroup) + populate(objectMap, "targetResourceName", e.TargetResourceName) + populate(objectMap, "targetResourceType", e.TargetResourceType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Essentials. +func (e *Essentials) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "alertRule": + err = unpopulate(val, &e.AlertRule) + delete(rawMsg, key) + case "alertState": + err = unpopulate(val, &e.AlertState) + delete(rawMsg, key) + case "lastModifiedDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + e.LastModifiedDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedUserName": + err = unpopulate(val, &e.LastModifiedUserName) + delete(rawMsg, key) + case "monitorCondition": + err = unpopulate(val, &e.MonitorCondition) + delete(rawMsg, key) + case "monitorConditionResolvedDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + e.MonitorConditionResolvedDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "monitorService": + err = unpopulate(val, &e.MonitorService) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, &e.Severity) + delete(rawMsg, key) + case "signalType": + err = unpopulate(val, &e.SignalType) + delete(rawMsg, key) + case "smartGroupId": + err = unpopulate(val, &e.SmartGroupID) + delete(rawMsg, key) + case "smartGroupingReason": + err = unpopulate(val, &e.SmartGroupingReason) + delete(rawMsg, key) + case "sourceCreatedId": + err = unpopulate(val, &e.SourceCreatedID) + delete(rawMsg, key) + case "startDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + e.StartDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "targetResource": + err = unpopulate(val, &e.TargetResource) + delete(rawMsg, key) + case "targetResourceGroup": + err = unpopulate(val, &e.TargetResourceGroup) + delete(rawMsg, key) + case "targetResourceName": + err = unpopulate(val, &e.TargetResourceName) + delete(rawMsg, key) + case "targetResourceType": + err = unpopulate(val, &e.TargetResourceType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ManagedResource - An azure managed resource object +type ManagedResource struct { + Resource + // REQUIRED; Resource location + Location *string `json:"location,omitempty"` + + // Resource tags + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ManagedResource. +func (m ManagedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + m.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagedResource. +func (m *ManagedResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return m.unmarshalInternal(rawMsg) +} + +func (m ManagedResource) marshalInternal(objectMap map[string]interface{}) { + m.Resource.marshalInternal(objectMap) + populate(objectMap, "location", m.Location) + populate(objectMap, "tags", m.Tags) +} + +func (m *ManagedResource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "location": + err = unpopulate(val, &m.Location) + delete(rawMsg, key) + case "tags": + err = unpopulate(val, &m.Tags) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := m.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// MonitorServiceDetails - Details of a monitor service +type MonitorServiceDetails struct { + // Monitor service display name + DisplayName *string `json:"displayName,omitempty"` + + // Monitor service name + Name *string `json:"name,omitempty"` +} + +// MonitorServiceList - Monitor service details +type MonitorServiceList struct { + AlertsMetaDataProperties + // REQUIRED; Array of operations + Data []*MonitorServiceDetails `json:"data,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type MonitorServiceList. +func (m MonitorServiceList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + m.AlertsMetaDataProperties.marshalInternal(objectMap, MetadataIdentifierMonitorServiceList) + populate(objectMap, "data", m.Data) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MonitorServiceList. +func (m *MonitorServiceList) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "data": + err = unpopulate(val, &m.Data) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := m.AlertsMetaDataProperties.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// Operation provided by provider +type Operation struct { + // Properties of the operation + Display *OperationDisplay `json:"display,omitempty"` + + // Name of the operation + Name *string `json:"name,omitempty"` +} + +// OperationDisplay - Properties of the operation +type OperationDisplay struct { + // Description of the operation + Description *string `json:"description,omitempty"` + + // Operation name + Operation *string `json:"operation,omitempty"` + + // Provider name + Provider *string `json:"provider,omitempty"` + + // Resource name + Resource *string `json:"resource,omitempty"` +} + +// OperationsList - Lists the operations available in the AlertsManagement RP. +type OperationsList struct { + // REQUIRED; Array of operations + Value []*Operation `json:"value,omitempty"` + + // URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationsList. +func (o OperationsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// PatchObject - Data contract for patch +type PatchObject struct { + // properties supported by patch operation + Properties *PatchProperties `json:"properties,omitempty"` + + // tags to be updated + Tags map[string]interface{} `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PatchObject. +func (p PatchObject) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "tags", p.Tags) + return json.Marshal(objectMap) +} + +// PatchProperties - Action rule properties supported by patch +type PatchProperties struct { + // Indicates if the given action rule is enabled or disabled + Status *ActionRuleStatus `json:"status,omitempty"` +} + +// Resource - An azure resource object +type Resource struct { + // READ-ONLY; Azure resource Id + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Azure resource name + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Azure resource type + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Resource. +func (r *Resource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return r.unmarshalInternal(rawMsg) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +func (r *Resource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, &r.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, &r.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, &r.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// Scope - Target scope for a given action rule. By default scope will be the subscription. User can also provide list of resource groups or list of resources +// from the scope subscription as well. +type Scope struct { + // type of target scope + ScopeType *ScopeType `json:"scopeType,omitempty"` + + // list of ARM IDs of the given scope type which will be the target of the given action rule. + Values []*string `json:"values,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Scope. +func (s Scope) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "scopeType", s.ScopeType) + populate(objectMap, "values", s.Values) + return json.Marshal(objectMap) +} + +// SmartDetectorAlertRulesCreateOrUpdateOptions contains the optional parameters for the SmartDetectorAlertRules.CreateOrUpdate method. +type SmartDetectorAlertRulesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SmartDetectorAlertRulesDeleteOptions contains the optional parameters for the SmartDetectorAlertRules.Delete method. +type SmartDetectorAlertRulesDeleteOptions struct { + // placeholder for future optional parameters +} + +// SmartDetectorAlertRulesGetOptions contains the optional parameters for the SmartDetectorAlertRules.Get method. +type SmartDetectorAlertRulesGetOptions struct { + // Indicates if Smart Detector should be expanded. + ExpandDetector *bool +} + +// SmartDetectorAlertRulesListByResourceGroupOptions contains the optional parameters for the SmartDetectorAlertRules.ListByResourceGroup method. +type SmartDetectorAlertRulesListByResourceGroupOptions struct { + // Indicates if Smart Detector should be expanded. + ExpandDetector *bool +} + +// SmartDetectorAlertRulesListOptions contains the optional parameters for the SmartDetectorAlertRules.List method. +type SmartDetectorAlertRulesListOptions struct { + // Indicates if Smart Detector should be expanded. + ExpandDetector *bool +} + +// SmartDetectorAlertRulesPatchOptions contains the optional parameters for the SmartDetectorAlertRules.Patch method. +type SmartDetectorAlertRulesPatchOptions struct { + // placeholder for future optional parameters +} + +// SmartDetectorErrorResponse - Describe the format of an Error response. +// Implements the error and azcore.HTTPResponse interfaces. +type SmartDetectorErrorResponse struct { + raw string + // Error code + Code *string `json:"code,omitempty"` + + // Error message indicating why the operation failed. + Message *string `json:"message,omitempty"` +} + +// Error implements the error interface for type SmartDetectorErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e SmartDetectorErrorResponse) Error() string { + return e.raw +} + +// SmartGroup - Set of related alerts grouped together smartly by AMS. +type SmartGroup struct { + Resource + // Properties of smart group. + Properties *SmartGroupProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SmartGroup. +func (s SmartGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SmartGroup. +func (s *SmartGroup) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SmartGroupAggregatedProperty - Aggregated property of each type +type SmartGroupAggregatedProperty struct { + // Total number of items of type. + Count *int32 `json:"count,omitempty"` + + // Name of the type. + Name *string `json:"name,omitempty"` +} + +// SmartGroupModification - Alert Modification details +type SmartGroupModification struct { + Resource + // Properties of the smartGroup modification item. + Properties *SmartGroupModificationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SmartGroupModification. +func (s SmartGroupModification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SmartGroupModification. +func (s *SmartGroupModification) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.Resource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SmartGroupModificationItem - smartGroup modification item. +type SmartGroupModificationItem struct { + // Modification comments + Comments *string `json:"comments,omitempty"` + + // Description of the modification + Description *string `json:"description,omitempty"` + + // Reason for the modification + ModificationEvent *SmartGroupModificationEvent `json:"modificationEvent,omitempty"` + + // Modified date and time + ModifiedAt *string `json:"modifiedAt,omitempty"` + + // Modified user details (Principal client name) + ModifiedBy *string `json:"modifiedBy,omitempty"` + + // New value + NewValue *string `json:"newValue,omitempty"` + + // Old value + OldValue *string `json:"oldValue,omitempty"` +} + +// SmartGroupModificationProperties - Properties of the smartGroup modification item. +type SmartGroupModificationProperties struct { + // Modification details + Modifications []*SmartGroupModificationItem `json:"modifications,omitempty"` + + // URL to fetch the next set of results. + NextLink *string `json:"nextLink,omitempty"` + + // READ-ONLY; Unique Id of the smartGroup for which the history is being retrieved + SmartGroupID *string `json:"smartGroupId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SmartGroupModificationProperties. +func (s SmartGroupModificationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "modifications", s.Modifications) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "smartGroupId", s.SmartGroupID) + return json.Marshal(objectMap) +} + +// SmartGroupProperties - Properties of smart group. +type SmartGroupProperties struct { + // Summary of alertSeverities in the smart group + AlertSeverities []*SmartGroupAggregatedProperty `json:"alertSeverities,omitempty"` + + // Summary of alertStates in the smart group + AlertStates []*SmartGroupAggregatedProperty `json:"alertStates,omitempty"` + + // Total number of alerts in smart group + AlertsCount *int32 `json:"alertsCount,omitempty"` + + // Summary of monitorConditions in the smart group + MonitorConditions []*SmartGroupAggregatedProperty `json:"monitorConditions,omitempty"` + + // Summary of monitorServices in the smart group + MonitorServices []*SmartGroupAggregatedProperty `json:"monitorServices,omitempty"` + + // The URI to fetch the next page of alerts. Call ListNext() with this URI to fetch the next page alerts. + NextLink *string `json:"nextLink,omitempty"` + + // Summary of target resource groups in the smart group + ResourceGroups []*SmartGroupAggregatedProperty `json:"resourceGroups,omitempty"` + + // Summary of target resource types in the smart group + ResourceTypes []*SmartGroupAggregatedProperty `json:"resourceTypes,omitempty"` + + // Summary of target resources in the smart group + Resources []*SmartGroupAggregatedProperty `json:"resources,omitempty"` + + // READ-ONLY; Last updated time of smart group. Date-Time in ISO-8601 format. + LastModifiedDateTime *time.Time `json:"lastModifiedDateTime,omitempty" azure:"ro"` + + // READ-ONLY; Last modified by user name. + LastModifiedUserName *string `json:"lastModifiedUserName,omitempty" azure:"ro"` + + // READ-ONLY; Severity of smart group is the highest(Sev0 >… > Sev4) severity of all the alerts in the group. + Severity *Severity `json:"severity,omitempty" azure:"ro"` + + // READ-ONLY; Smart group state + SmartGroupState *State `json:"smartGroupState,omitempty" azure:"ro"` + + // READ-ONLY; Creation time of smart group. Date-Time in ISO-8601 format. + StartDateTime *time.Time `json:"startDateTime,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SmartGroupProperties. +func (s SmartGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "alertSeverities", s.AlertSeverities) + populate(objectMap, "alertStates", s.AlertStates) + populate(objectMap, "alertsCount", s.AlertsCount) + populate(objectMap, "lastModifiedDateTime", (*timeRFC3339)(s.LastModifiedDateTime)) + populate(objectMap, "lastModifiedUserName", s.LastModifiedUserName) + populate(objectMap, "monitorConditions", s.MonitorConditions) + populate(objectMap, "monitorServices", s.MonitorServices) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "resourceGroups", s.ResourceGroups) + populate(objectMap, "resourceTypes", s.ResourceTypes) + populate(objectMap, "resources", s.Resources) + populate(objectMap, "severity", s.Severity) + populate(objectMap, "smartGroupState", s.SmartGroupState) + populate(objectMap, "startDateTime", (*timeRFC3339)(s.StartDateTime)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SmartGroupProperties. +func (s *SmartGroupProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "alertSeverities": + err = unpopulate(val, &s.AlertSeverities) + delete(rawMsg, key) + case "alertStates": + err = unpopulate(val, &s.AlertStates) + delete(rawMsg, key) + case "alertsCount": + err = unpopulate(val, &s.AlertsCount) + delete(rawMsg, key) + case "lastModifiedDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedUserName": + err = unpopulate(val, &s.LastModifiedUserName) + delete(rawMsg, key) + case "monitorConditions": + err = unpopulate(val, &s.MonitorConditions) + delete(rawMsg, key) + case "monitorServices": + err = unpopulate(val, &s.MonitorServices) + delete(rawMsg, key) + case "nextLink": + err = unpopulate(val, &s.NextLink) + delete(rawMsg, key) + case "resourceGroups": + err = unpopulate(val, &s.ResourceGroups) + delete(rawMsg, key) + case "resourceTypes": + err = unpopulate(val, &s.ResourceTypes) + delete(rawMsg, key) + case "resources": + err = unpopulate(val, &s.Resources) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, &s.Severity) + delete(rawMsg, key) + case "smartGroupState": + err = unpopulate(val, &s.SmartGroupState) + delete(rawMsg, key) + case "startDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.StartDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// SmartGroupsChangeStateOptions contains the optional parameters for the SmartGroups.ChangeState method. +type SmartGroupsChangeStateOptions struct { + // placeholder for future optional parameters +} + +// SmartGroupsGetAllOptions contains the optional parameters for the SmartGroups.GetAll method. +type SmartGroupsGetAllOptions struct { + // Filter by monitor condition which is either 'Fired' or 'Resolved'. Default value is to select all. + MonitorCondition *MonitorCondition + // Filter by monitor service which generates the alert instance. Default value is select all. + MonitorService *MonitorService + // Determines number of alerts returned per page in response. Permissible value is between 1 to 250. When the "includeContent" filter is selected, maximum + // value allowed is 25. Default value is 25. + PageCount *int32 + // Filter by severity. Default value is select all. + Severity *Severity + // Filter by state of the smart group. Default value is to select all. + SmartGroupState *AlertState + // Sort the query results by input field. Default value is sort by 'lastModifiedDateTime'. + SortBy *SmartGroupsSortByFields + // Sort the query results order in either ascending or descending. Default value is 'desc' for time fields and 'asc' for others. + SortOrder *Enum11 + // Filter by target resource( which is full ARM ID) Default value is select all. + TargetResource *string + // Filter by target resource group name. Default value is select all. + TargetResourceGroup *string + // Filter by target resource type. Default value is select all. + TargetResourceType *string + // Filter by time range by below listed values. Default value is 1 day. + TimeRange *TimeRange +} + +// SmartGroupsGetByIDOptions contains the optional parameters for the SmartGroups.GetByID method. +type SmartGroupsGetByIDOptions struct { + // placeholder for future optional parameters +} + +// SmartGroupsGetHistoryOptions contains the optional parameters for the SmartGroups.GetHistory method. +type SmartGroupsGetHistoryOptions struct { + // placeholder for future optional parameters +} + +// SmartGroupsList - List the alerts. +type SmartGroupsList struct { + // URL to fetch the next set of alerts. + NextLink *string `json:"nextLink,omitempty"` + + // List of alerts + Value []*SmartGroup `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SmartGroupsList. +func (s SmartGroupsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// Suppression - Action rule with suppression configuration +type Suppression struct { + ActionRuleProperties + // REQUIRED; suppression configuration for the action rule + SuppressionConfig *SuppressionConfig `json:"suppressionConfig,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Suppression. +func (s Suppression) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ActionRuleProperties.marshalInternal(objectMap, ActionRuleTypeSuppression) + populate(objectMap, "suppressionConfig", s.SuppressionConfig) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Suppression. +func (s *Suppression) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "suppressionConfig": + err = unpopulate(val, &s.SuppressionConfig) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.ActionRuleProperties.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SuppressionConfig - Suppression logic for a given action rule +type SuppressionConfig struct { + // REQUIRED; Specifies when the suppression should be applied + RecurrenceType *SuppressionType `json:"recurrenceType,omitempty"` + + // suppression schedule configuration + Schedule *SuppressionSchedule `json:"schedule,omitempty"` +} + +// SuppressionSchedule - Schedule for a given suppression configuration. +type SuppressionSchedule struct { + // End date for suppression + EndDate *string `json:"endDate,omitempty"` + + // End date for suppression + EndTime *string `json:"endTime,omitempty"` + + // Specifies the values for recurrence pattern + RecurrenceValues []*int32 `json:"recurrenceValues,omitempty"` + + // Start date for suppression + StartDate *string `json:"startDate,omitempty"` + + // Start time for suppression + StartTime *string `json:"startTime,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SuppressionSchedule. +func (s SuppressionSchedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "endDate", s.EndDate) + populate(objectMap, "endTime", s.EndTime) + populate(objectMap, "recurrenceValues", s.RecurrenceValues) + populate(objectMap, "startDate", s.StartDate) + populate(objectMap, "startTime", s.StartTime) + return json.Marshal(objectMap) +} + +// ThrottlingInformation - Optional throttling information for the alert rule. +type ThrottlingInformation struct { + // The required duration (in ISO8601 format) to wait before notifying on the alert rule again. The time granularity must be in minutes and minimum value + // is 0 minutes + Duration *string `json:"duration,omitempty"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_operations_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_operations_client.go new file mode 100644 index 000000000000..b174c6953544 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_operations_client.go @@ -0,0 +1,79 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - List all operations available through Azure Alerts Management Resource Provider. +// If the operation fails it returns a generic error. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationsList.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.AlertsManagement/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationsList); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_pagers.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_pagers.go new file mode 100644 index 000000000000..6309e2717af4 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_pagers.go @@ -0,0 +1,395 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "reflect" +) + +// ActionRulesListByResourceGroupPager provides operations for iterating over paged responses. +type ActionRulesListByResourceGroupPager struct { + client *ActionRulesClient + current ActionRulesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ActionRulesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ActionRulesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ActionRulesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ActionRulesList.NextLink == nil || len(*p.current.ActionRulesList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ActionRulesListByResourceGroupResponse page. +func (p *ActionRulesListByResourceGroupPager) PageResponse() ActionRulesListByResourceGroupResponse { + return p.current +} + +// ActionRulesListBySubscriptionPager provides operations for iterating over paged responses. +type ActionRulesListBySubscriptionPager struct { + client *ActionRulesClient + current ActionRulesListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ActionRulesListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ActionRulesListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ActionRulesListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ActionRulesList.NextLink == nil || len(*p.current.ActionRulesList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ActionRulesListBySubscriptionResponse page. +func (p *ActionRulesListBySubscriptionPager) PageResponse() ActionRulesListBySubscriptionResponse { + return p.current +} + +// AlertsGetAllPager provides operations for iterating over paged responses. +type AlertsGetAllPager struct { + client *AlertsClient + current AlertsGetAllResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AlertsGetAllResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AlertsGetAllPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AlertsGetAllPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AlertsList.NextLink == nil || len(*p.current.AlertsList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.getAllHandleError(resp) + return false + } + result, err := p.client.getAllHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AlertsGetAllResponse page. +func (p *AlertsGetAllPager) PageResponse() AlertsGetAllResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationsList.NextLink == nil || len(*p.current.OperationsList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} + +// SmartDetectorAlertRulesListByResourceGroupPager provides operations for iterating over paged responses. +type SmartDetectorAlertRulesListByResourceGroupPager struct { + client *SmartDetectorAlertRulesClient + current SmartDetectorAlertRulesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, SmartDetectorAlertRulesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *SmartDetectorAlertRulesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *SmartDetectorAlertRulesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AlertRulesList.NextLink == nil || len(*p.current.AlertRulesList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current SmartDetectorAlertRulesListByResourceGroupResponse page. +func (p *SmartDetectorAlertRulesListByResourceGroupPager) PageResponse() SmartDetectorAlertRulesListByResourceGroupResponse { + return p.current +} + +// SmartDetectorAlertRulesListPager provides operations for iterating over paged responses. +type SmartDetectorAlertRulesListPager struct { + client *SmartDetectorAlertRulesClient + current SmartDetectorAlertRulesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, SmartDetectorAlertRulesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *SmartDetectorAlertRulesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *SmartDetectorAlertRulesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AlertRulesList.NextLink == nil || len(*p.current.AlertRulesList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current SmartDetectorAlertRulesListResponse page. +func (p *SmartDetectorAlertRulesListPager) PageResponse() SmartDetectorAlertRulesListResponse { + return p.current +} + +// SmartGroupsGetAllPager provides operations for iterating over paged responses. +type SmartGroupsGetAllPager struct { + client *SmartGroupsClient + current SmartGroupsGetAllResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, SmartGroupsGetAllResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *SmartGroupsGetAllPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *SmartGroupsGetAllPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SmartGroupsList.NextLink == nil || len(*p.current.SmartGroupsList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.getAllHandleError(resp) + return false + } + result, err := p.client.getAllHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current SmartGroupsGetAllResponse page. +func (p *SmartGroupsGetAllPager) PageResponse() SmartGroupsGetAllResponse { + return p.current +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_polymorphic_helpers.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_polymorphic_helpers.go new file mode 100644 index 000000000000..81bb2bb70b28 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_polymorphic_helpers.go @@ -0,0 +1,89 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import "encoding/json" + +func unmarshalActionRulePropertiesClassification(rawMsg json.RawMessage) (ActionRulePropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ActionRulePropertiesClassification + switch m["type"] { + case string(ActionRuleTypeActionGroup): + b = &ActionGroup{} + case string(ActionRuleTypeDiagnostics): + b = &Diagnostics{} + case string(ActionRuleTypeSuppression): + b = &Suppression{} + default: + b = &ActionRuleProperties{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalActionRulePropertiesClassificationArray(rawMsg json.RawMessage) ([]ActionRulePropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ActionRulePropertiesClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalActionRulePropertiesClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalAlertsMetaDataPropertiesClassification(rawMsg json.RawMessage) (AlertsMetaDataPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AlertsMetaDataPropertiesClassification + switch m["metadataIdentifier"] { + case string(MetadataIdentifierMonitorServiceList): + b = &MonitorServiceList{} + default: + b = &AlertsMetaDataProperties{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalAlertsMetaDataPropertiesClassificationArray(rawMsg json.RawMessage) ([]AlertsMetaDataPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]AlertsMetaDataPropertiesClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalAlertsMetaDataPropertiesClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_response_types.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_response_types.go new file mode 100644 index 000000000000..4d7003de37e1 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_response_types.go @@ -0,0 +1,298 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import "net/http" + +// ActionRulesCreateUpdateResponse contains the response from method ActionRules.CreateUpdate. +type ActionRulesCreateUpdateResponse struct { + ActionRulesCreateUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesCreateUpdateResult contains the result from method ActionRules.CreateUpdate. +type ActionRulesCreateUpdateResult struct { + ActionRule + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// ActionRulesDeleteResponse contains the response from method ActionRules.Delete. +type ActionRulesDeleteResponse struct { + ActionRulesDeleteResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesDeleteResult contains the result from method ActionRules.Delete. +type ActionRulesDeleteResult struct { + Value *bool + + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// ActionRulesGetByNameResponse contains the response from method ActionRules.GetByName. +type ActionRulesGetByNameResponse struct { + ActionRulesGetByNameResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesGetByNameResult contains the result from method ActionRules.GetByName. +type ActionRulesGetByNameResult struct { + ActionRule + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// ActionRulesListByResourceGroupResponse contains the response from method ActionRules.ListByResourceGroup. +type ActionRulesListByResourceGroupResponse struct { + ActionRulesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesListByResourceGroupResult contains the result from method ActionRules.ListByResourceGroup. +type ActionRulesListByResourceGroupResult struct { + ActionRulesList + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// ActionRulesListBySubscriptionResponse contains the response from method ActionRules.ListBySubscription. +type ActionRulesListBySubscriptionResponse struct { + ActionRulesListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesListBySubscriptionResult contains the result from method ActionRules.ListBySubscription. +type ActionRulesListBySubscriptionResult struct { + ActionRulesList + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// ActionRulesUpdateResponse contains the response from method ActionRules.Update. +type ActionRulesUpdateResponse struct { + ActionRulesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ActionRulesUpdateResult contains the result from method ActionRules.Update. +type ActionRulesUpdateResult struct { + ActionRule + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// AlertsChangeStateResponse contains the response from method Alerts.ChangeState. +type AlertsChangeStateResponse struct { + AlertsChangeStateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsChangeStateResult contains the result from method Alerts.ChangeState. +type AlertsChangeStateResult struct { + Alert +} + +// AlertsGetAllResponse contains the response from method Alerts.GetAll. +type AlertsGetAllResponse struct { + AlertsGetAllResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsGetAllResult contains the result from method Alerts.GetAll. +type AlertsGetAllResult struct { + AlertsList +} + +// AlertsGetByIDResponse contains the response from method Alerts.GetByID. +type AlertsGetByIDResponse struct { + AlertsGetByIDResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsGetByIDResult contains the result from method Alerts.GetByID. +type AlertsGetByIDResult struct { + Alert +} + +// AlertsGetHistoryResponse contains the response from method Alerts.GetHistory. +type AlertsGetHistoryResponse struct { + AlertsGetHistoryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsGetHistoryResult contains the result from method Alerts.GetHistory. +type AlertsGetHistoryResult struct { + AlertModification +} + +// AlertsGetSummaryResponse contains the response from method Alerts.GetSummary. +type AlertsGetSummaryResponse struct { + AlertsGetSummaryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsGetSummaryResult contains the result from method Alerts.GetSummary. +type AlertsGetSummaryResult struct { + AlertsSummary +} + +// AlertsMetaDataResponse contains the response from method Alerts.MetaData. +type AlertsMetaDataResponse struct { + AlertsMetaDataResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AlertsMetaDataResult contains the result from method Alerts.MetaData. +type AlertsMetaDataResult struct { + AlertsMetaData +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationsList +} + +// SmartDetectorAlertRulesCreateOrUpdateResponse contains the response from method SmartDetectorAlertRules.CreateOrUpdate. +type SmartDetectorAlertRulesCreateOrUpdateResponse struct { + SmartDetectorAlertRulesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesCreateOrUpdateResult contains the result from method SmartDetectorAlertRules.CreateOrUpdate. +type SmartDetectorAlertRulesCreateOrUpdateResult struct { + AlertRule +} + +// SmartDetectorAlertRulesDeleteResponse contains the response from method SmartDetectorAlertRules.Delete. +type SmartDetectorAlertRulesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesGetResponse contains the response from method SmartDetectorAlertRules.Get. +type SmartDetectorAlertRulesGetResponse struct { + SmartDetectorAlertRulesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesGetResult contains the result from method SmartDetectorAlertRules.Get. +type SmartDetectorAlertRulesGetResult struct { + AlertRule +} + +// SmartDetectorAlertRulesListByResourceGroupResponse contains the response from method SmartDetectorAlertRules.ListByResourceGroup. +type SmartDetectorAlertRulesListByResourceGroupResponse struct { + SmartDetectorAlertRulesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesListByResourceGroupResult contains the result from method SmartDetectorAlertRules.ListByResourceGroup. +type SmartDetectorAlertRulesListByResourceGroupResult struct { + AlertRulesList +} + +// SmartDetectorAlertRulesListResponse contains the response from method SmartDetectorAlertRules.List. +type SmartDetectorAlertRulesListResponse struct { + SmartDetectorAlertRulesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesListResult contains the result from method SmartDetectorAlertRules.List. +type SmartDetectorAlertRulesListResult struct { + AlertRulesList +} + +// SmartDetectorAlertRulesPatchResponse contains the response from method SmartDetectorAlertRules.Patch. +type SmartDetectorAlertRulesPatchResponse struct { + SmartDetectorAlertRulesPatchResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartDetectorAlertRulesPatchResult contains the result from method SmartDetectorAlertRules.Patch. +type SmartDetectorAlertRulesPatchResult struct { + AlertRule +} + +// SmartGroupsChangeStateResponse contains the response from method SmartGroups.ChangeState. +type SmartGroupsChangeStateResponse struct { + SmartGroupsChangeStateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartGroupsChangeStateResult contains the result from method SmartGroups.ChangeState. +type SmartGroupsChangeStateResult struct { + SmartGroup + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// SmartGroupsGetAllResponse contains the response from method SmartGroups.GetAll. +type SmartGroupsGetAllResponse struct { + SmartGroupsGetAllResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartGroupsGetAllResult contains the result from method SmartGroups.GetAll. +type SmartGroupsGetAllResult struct { + SmartGroupsList +} + +// SmartGroupsGetByIDResponse contains the response from method SmartGroups.GetByID. +type SmartGroupsGetByIDResponse struct { + SmartGroupsGetByIDResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartGroupsGetByIDResult contains the result from method SmartGroups.GetByID. +type SmartGroupsGetByIDResult struct { + SmartGroup + // XMSRequestID contains the information returned from the x-ms-request-id header response. + XMSRequestID *string +} + +// SmartGroupsGetHistoryResponse contains the response from method SmartGroups.GetHistory. +type SmartGroupsGetHistoryResponse struct { + SmartGroupsGetHistoryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SmartGroupsGetHistoryResult contains the result from method SmartGroups.GetHistory. +type SmartGroupsGetHistoryResult struct { + SmartGroupModification +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartdetectoralertrules_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartdetectoralertrules_client.go new file mode 100644 index 000000000000..80adf65b2601 --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartdetectoralertrules_client.go @@ -0,0 +1,407 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// SmartDetectorAlertRulesClient contains the methods for the SmartDetectorAlertRules group. +// Don't use this type directly, use NewSmartDetectorAlertRulesClient() instead. +type SmartDetectorAlertRulesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewSmartDetectorAlertRulesClient creates a new instance of SmartDetectorAlertRulesClient with the specified values. +func NewSmartDetectorAlertRulesClient(con *arm.Connection, subscriptionID string) *SmartDetectorAlertRulesClient { + return &SmartDetectorAlertRulesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Create or update a Smart Detector alert rule. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, alertRuleName string, parameters AlertRule, options *SmartDetectorAlertRulesCreateOrUpdateOptions) (SmartDetectorAlertRulesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, alertRuleName, parameters, options) + if err != nil { + return SmartDetectorAlertRulesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartDetectorAlertRulesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return SmartDetectorAlertRulesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SmartDetectorAlertRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, alertRuleName string, parameters AlertRule, options *SmartDetectorAlertRulesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.alertsManagement/smartDetectorAlertRules/{alertRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *SmartDetectorAlertRulesClient) createOrUpdateHandleResponse(resp *http.Response) (SmartDetectorAlertRulesCreateOrUpdateResponse, error) { + result := SmartDetectorAlertRulesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRule); err != nil { + return SmartDetectorAlertRulesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *SmartDetectorAlertRulesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Delete an existing Smart Detector alert rule. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) Delete(ctx context.Context, resourceGroupName string, alertRuleName string, options *SmartDetectorAlertRulesDeleteOptions) (SmartDetectorAlertRulesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, alertRuleName, options) + if err != nil { + return SmartDetectorAlertRulesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartDetectorAlertRulesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return SmartDetectorAlertRulesDeleteResponse{}, client.deleteHandleError(resp) + } + return SmartDetectorAlertRulesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SmartDetectorAlertRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, alertRuleName string, options *SmartDetectorAlertRulesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.alertsManagement/smartDetectorAlertRules/{alertRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *SmartDetectorAlertRulesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get a specific Smart Detector alert rule. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) Get(ctx context.Context, resourceGroupName string, alertRuleName string, options *SmartDetectorAlertRulesGetOptions) (SmartDetectorAlertRulesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, alertRuleName, options) + if err != nil { + return SmartDetectorAlertRulesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartDetectorAlertRulesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SmartDetectorAlertRulesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *SmartDetectorAlertRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, alertRuleName string, options *SmartDetectorAlertRulesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.alertsManagement/smartDetectorAlertRules/{alertRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + if options != nil && options.ExpandDetector != nil { + reqQP.Set("expandDetector", strconv.FormatBool(*options.ExpandDetector)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SmartDetectorAlertRulesClient) getHandleResponse(resp *http.Response) (SmartDetectorAlertRulesGetResponse, error) { + result := SmartDetectorAlertRulesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRule); err != nil { + return SmartDetectorAlertRulesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *SmartDetectorAlertRulesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List all the existing Smart Detector alert rules within the subscription. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) List(options *SmartDetectorAlertRulesListOptions) *SmartDetectorAlertRulesListPager { + return &SmartDetectorAlertRulesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp SmartDetectorAlertRulesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AlertRulesList.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *SmartDetectorAlertRulesClient) listCreateRequest(ctx context.Context, options *SmartDetectorAlertRulesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/microsoft.alertsManagement/smartDetectorAlertRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + if options != nil && options.ExpandDetector != nil { + reqQP.Set("expandDetector", strconv.FormatBool(*options.ExpandDetector)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *SmartDetectorAlertRulesClient) listHandleResponse(resp *http.Response) (SmartDetectorAlertRulesListResponse, error) { + result := SmartDetectorAlertRulesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRulesList); err != nil { + return SmartDetectorAlertRulesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *SmartDetectorAlertRulesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - List all the existing Smart Detector alert rules within the subscription and resource group. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) ListByResourceGroup(resourceGroupName string, options *SmartDetectorAlertRulesListByResourceGroupOptions) *SmartDetectorAlertRulesListByResourceGroupPager { + return &SmartDetectorAlertRulesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp SmartDetectorAlertRulesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AlertRulesList.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *SmartDetectorAlertRulesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SmartDetectorAlertRulesListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.alertsManagement/smartDetectorAlertRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + if options != nil && options.ExpandDetector != nil { + reqQP.Set("expandDetector", strconv.FormatBool(*options.ExpandDetector)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *SmartDetectorAlertRulesClient) listByResourceGroupHandleResponse(resp *http.Response) (SmartDetectorAlertRulesListByResourceGroupResponse, error) { + result := SmartDetectorAlertRulesListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRulesList); err != nil { + return SmartDetectorAlertRulesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *SmartDetectorAlertRulesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Patch - Patch a specific Smart Detector alert rule. +// If the operation fails it returns the *SmartDetectorErrorResponse error type. +func (client *SmartDetectorAlertRulesClient) Patch(ctx context.Context, resourceGroupName string, alertRuleName string, parameters AlertRulePatchObject, options *SmartDetectorAlertRulesPatchOptions) (SmartDetectorAlertRulesPatchResponse, error) { + req, err := client.patchCreateRequest(ctx, resourceGroupName, alertRuleName, parameters, options) + if err != nil { + return SmartDetectorAlertRulesPatchResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartDetectorAlertRulesPatchResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SmartDetectorAlertRulesPatchResponse{}, client.patchHandleError(resp) + } + return client.patchHandleResponse(resp) +} + +// patchCreateRequest creates the Patch request. +func (client *SmartDetectorAlertRulesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, alertRuleName string, parameters AlertRulePatchObject, options *SmartDetectorAlertRulesPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.alertsManagement/smartDetectorAlertRules/{alertRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if alertRuleName == "" { + return nil, errors.New("parameter alertRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{alertRuleName}", url.PathEscape(alertRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// patchHandleResponse handles the Patch response. +func (client *SmartDetectorAlertRulesClient) patchHandleResponse(resp *http.Response) (SmartDetectorAlertRulesPatchResponse, error) { + result := SmartDetectorAlertRulesPatchResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AlertRule); err != nil { + return SmartDetectorAlertRulesPatchResponse{}, err + } + return result, nil +} + +// patchHandleError handles the Patch error response. +func (client *SmartDetectorAlertRulesClient) patchHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := SmartDetectorErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartgroups_client.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartgroups_client.go new file mode 100644 index 000000000000..7aaab19c07dd --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_smartgroups_client.go @@ -0,0 +1,312 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "context" + "errors" + "fmt" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" + "net/http" + "net/url" + "strconv" + "strings" +) + +// SmartGroupsClient contains the methods for the SmartGroups group. +// Don't use this type directly, use NewSmartGroupsClient() instead. +type SmartGroupsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewSmartGroupsClient creates a new instance of SmartGroupsClient with the specified values. +func NewSmartGroupsClient(con *arm.Connection, subscriptionID string) *SmartGroupsClient { + return &SmartGroupsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// ChangeState - Change the state of a Smart Group. +// If the operation fails it returns the *ErrorResponseAutoGenerated2 error type. +func (client *SmartGroupsClient) ChangeState(ctx context.Context, smartGroupID string, newState AlertState, options *SmartGroupsChangeStateOptions) (SmartGroupsChangeStateResponse, error) { + req, err := client.changeStateCreateRequest(ctx, smartGroupID, newState, options) + if err != nil { + return SmartGroupsChangeStateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartGroupsChangeStateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SmartGroupsChangeStateResponse{}, client.changeStateHandleError(resp) + } + return client.changeStateHandleResponse(resp) +} + +// changeStateCreateRequest creates the ChangeState request. +func (client *SmartGroupsClient) changeStateCreateRequest(ctx context.Context, smartGroupID string, newState AlertState, options *SmartGroupsChangeStateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/changeState" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if smartGroupID == "" { + return nil, errors.New("parameter smartGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{smartGroupId}", url.PathEscape(smartGroupID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + reqQP.Set("newState", string(newState)) + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// changeStateHandleResponse handles the ChangeState response. +func (client *SmartGroupsClient) changeStateHandleResponse(resp *http.Response) (SmartGroupsChangeStateResponse, error) { + result := SmartGroupsChangeStateResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.SmartGroup); err != nil { + return SmartGroupsChangeStateResponse{}, err + } + return result, nil +} + +// changeStateHandleError handles the ChangeState error response. +func (client *SmartGroupsClient) changeStateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated2{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetAll - List all the Smart Groups within a specified subscription. +// If the operation fails it returns the *ErrorResponseAutoGenerated2 error type. +func (client *SmartGroupsClient) GetAll(options *SmartGroupsGetAllOptions) *SmartGroupsGetAllPager { + return &SmartGroupsGetAllPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.getAllCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp SmartGroupsGetAllResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SmartGroupsList.NextLink) + }, + } +} + +// getAllCreateRequest creates the GetAll request. +func (client *SmartGroupsClient) getAllCreateRequest(ctx context.Context, options *SmartGroupsGetAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.TargetResource != nil { + reqQP.Set("targetResource", *options.TargetResource) + } + if options != nil && options.TargetResourceGroup != nil { + reqQP.Set("targetResourceGroup", *options.TargetResourceGroup) + } + if options != nil && options.TargetResourceType != nil { + reqQP.Set("targetResourceType", *options.TargetResourceType) + } + if options != nil && options.MonitorService != nil { + reqQP.Set("monitorService", string(*options.MonitorService)) + } + if options != nil && options.MonitorCondition != nil { + reqQP.Set("monitorCondition", string(*options.MonitorCondition)) + } + if options != nil && options.Severity != nil { + reqQP.Set("severity", string(*options.Severity)) + } + if options != nil && options.SmartGroupState != nil { + reqQP.Set("smartGroupState", string(*options.SmartGroupState)) + } + if options != nil && options.TimeRange != nil { + reqQP.Set("timeRange", string(*options.TimeRange)) + } + if options != nil && options.PageCount != nil { + reqQP.Set("pageCount", strconv.FormatInt(int64(*options.PageCount), 10)) + } + if options != nil && options.SortBy != nil { + reqQP.Set("sortBy", string(*options.SortBy)) + } + if options != nil && options.SortOrder != nil { + reqQP.Set("sortOrder", string(*options.SortOrder)) + } + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAllHandleResponse handles the GetAll response. +func (client *SmartGroupsClient) getAllHandleResponse(resp *http.Response) (SmartGroupsGetAllResponse, error) { + result := SmartGroupsGetAllResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SmartGroupsList); err != nil { + return SmartGroupsGetAllResponse{}, err + } + return result, nil +} + +// getAllHandleError handles the GetAll error response. +func (client *SmartGroupsClient) getAllHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated2{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetByID - Get information related to a specific Smart Group. +// If the operation fails it returns the *ErrorResponseAutoGenerated2 error type. +func (client *SmartGroupsClient) GetByID(ctx context.Context, smartGroupID string, options *SmartGroupsGetByIDOptions) (SmartGroupsGetByIDResponse, error) { + req, err := client.getByIDCreateRequest(ctx, smartGroupID, options) + if err != nil { + return SmartGroupsGetByIDResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartGroupsGetByIDResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SmartGroupsGetByIDResponse{}, client.getByIDHandleError(resp) + } + return client.getByIDHandleResponse(resp) +} + +// getByIDCreateRequest creates the GetByID request. +func (client *SmartGroupsClient) getByIDCreateRequest(ctx context.Context, smartGroupID string, options *SmartGroupsGetByIDOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if smartGroupID == "" { + return nil, errors.New("parameter smartGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{smartGroupId}", url.PathEscape(smartGroupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getByIDHandleResponse handles the GetByID response. +func (client *SmartGroupsClient) getByIDHandleResponse(resp *http.Response) (SmartGroupsGetByIDResponse, error) { + result := SmartGroupsGetByIDResponse{RawResponse: resp} + if val := resp.Header.Get("x-ms-request-id"); val != "" { + result.XMSRequestID = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.SmartGroup); err != nil { + return SmartGroupsGetByIDResponse{}, err + } + return result, nil +} + +// getByIDHandleError handles the GetByID error response. +func (client *SmartGroupsClient) getByIDHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated2{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetHistory - Get the history a smart group, which captures any Smart Group state changes (New/Acknowledged/Closed) . +// If the operation fails it returns the *ErrorResponseAutoGenerated2 error type. +func (client *SmartGroupsClient) GetHistory(ctx context.Context, smartGroupID string, options *SmartGroupsGetHistoryOptions) (SmartGroupsGetHistoryResponse, error) { + req, err := client.getHistoryCreateRequest(ctx, smartGroupID, options) + if err != nil { + return SmartGroupsGetHistoryResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SmartGroupsGetHistoryResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SmartGroupsGetHistoryResponse{}, client.getHistoryHandleError(resp) + } + return client.getHistoryHandleResponse(resp) +} + +// getHistoryCreateRequest creates the GetHistory request. +func (client *SmartGroupsClient) getHistoryCreateRequest(ctx context.Context, smartGroupID string, options *SmartGroupsGetHistoryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.AlertsManagement/smartGroups/{smartGroupId}/history" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if smartGroupID == "" { + return nil, errors.New("parameter smartGroupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{smartGroupId}", url.PathEscape(smartGroupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-05-05-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHistoryHandleResponse handles the GetHistory response. +func (client *SmartGroupsClient) getHistoryHandleResponse(resp *http.Response) (SmartGroupsGetHistoryResponse, error) { + result := SmartGroupsGetHistoryResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SmartGroupModification); err != nil { + return SmartGroupsGetHistoryResponse{}, err + } + return result, nil +} + +// getHistoryHandleError handles the GetHistory error response. +func (client *SmartGroupsClient) getHistoryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponseAutoGenerated2{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_time_rfc3339.go b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..d14c88c6147b --- /dev/null +++ b/sdk/resourcemanager/alertsmanagement/armalertsmanagement/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armalertsmanagement + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/appplatform/armappplatform/CHANGELOG.md b/sdk/resourcemanager/appplatform/armappplatform/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/appplatform/armappplatform/CHANGELOG.md +++ b/sdk/resourcemanager/appplatform/armappplatform/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/appplatform/armappplatform/zz_generated_constants.go b/sdk/resourcemanager/appplatform/armappplatform/zz_generated_constants.go index 14d3e99f7e45..7797c82d8a84 100644 --- a/sdk/resourcemanager/appplatform/armappplatform/zz_generated_constants.go +++ b/sdk/resourcemanager/appplatform/armappplatform/zz_generated_constants.go @@ -10,7 +10,7 @@ package armappplatform const ( module = "armappplatform" - version = "v0.1.0" + version = "v0.1.1" ) // AppResourceProvisioningState - Provisioning state of the App diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/CHANGELOG.md b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/LICENSE.txt b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/README.md b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/README.md new file mode 100644 index 000000000000..56ee86537c2b --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/README.md @@ -0,0 +1,76 @@ +# Azure Cognitive Services Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices) + +The `armcognitiveservices` module provides operations for working with Azure Cognitive Services. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/cognitiveservices/armcognitiveservices) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Cognitive Services module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Cognitive Services. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Cognitive Services + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Cognitive Services modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armcognitiveservices.NewResourceSKUsClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Cognitive Services` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/autorest.md b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/autorest.md new file mode 100644 index 000000000000..dad8cdf5c096 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/762ca1046eedf2b2dba28784dd4aebffab2a9897/specification/cognitiveservices/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/762ca1046eedf2b2dba28784dd4aebffab2a9897/specification/cognitiveservices/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/build.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/build.go new file mode 100644 index 000000000000..1b14379df6a2 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/cognitiveservices/armcognitiveservices + +package armcognitiveservices diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/ci.yml b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/ci.yml new file mode 100644 index 000000000000..9ad58b7facfe --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/cognitiveservices/armcognitiveservices/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/cognitiveservices/armcognitiveservices/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/cognitiveservices/armcognitiveservices' diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.mod b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.mod new file mode 100644 index 000000000000..7ecf7161507b --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/cognitiveservices/armcognitiveservices + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.sum b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go_mod_tidy_hack.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go_mod_tidy_hack.go new file mode 100644 index 000000000000..7a8a1018ca9c --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armcognitiveservices + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_accounts_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_accounts_client.go new file mode 100644 index 000000000000..bf9d076cdaf1 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_accounts_client.go @@ -0,0 +1,706 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountsClient contains the methods for the Accounts group. +// Don't use this type directly, use NewAccountsClient() instead. +type AccountsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAccountsClient creates a new instance of AccountsClient with the specified values. +func NewAccountsClient(con *arm.Connection, subscriptionID string) *AccountsClient { + return &AccountsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreate - Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for developer to access intelligent +// APIs. It's also the resource type for billing. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginCreateOptions) (AccountsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return AccountsCreatePollerResponse{}, err + } + result := AccountsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return AccountsCreatePollerResponse{}, err + } + result.Poller = &AccountsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Create Cognitive Services Account. Accounts is a resource group wide resource type. It holds the keys for developer to access intelligent APIs. +// It's also the resource type for billing. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, account) +} + +// createHandleError handles the Create error response. +func (client *AccountsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (AccountsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsDeletePollerResponse{}, err + } + result := AccountsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return AccountsDeletePollerResponse{}, err + } + result.Poller = &AccountsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *AccountsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Returns a Cognitive Services account specified by the parameters. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *AccountsGetOptions) (AccountsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountsClient) getHandleResponse(resp *http.Response) (AccountsGetResponse, error) { + result := AccountsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return AccountsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AccountsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Returns all the resources of a particular type belonging to a subscription. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) List(options *AccountsListOptions) *AccountsListPager { + return &AccountsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp AccountsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AccountListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AccountsClient) listCreateRequest(ctx context.Context, options *AccountsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/accounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountsClient) listHandleResponse(resp *http.Response) (AccountsListResponse, error) { + result := AccountsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AccountsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Returns all the resources of a particular type belonging to a resource group +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) ListByResourceGroup(resourceGroupName string, options *AccountsListByResourceGroupOptions) *AccountsListByResourceGroupPager { + return &AccountsListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp AccountsListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AccountListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AccountsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *AccountsListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AccountsClient) listByResourceGroupHandleResponse(resp *http.Response) (AccountsListByResourceGroupResponse, error) { + result := AccountsListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return AccountsListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *AccountsClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListKeys - Lists the account keys for the specified Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) ListKeys(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListKeysOptions) (AccountsListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *AccountsClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *AccountsClient) listKeysHandleResponse(resp *http.Response) (AccountsListKeysResponse, error) { + result := AccountsListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.APIKeys); err != nil { + return AccountsListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *AccountsClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListSKUs - List available SKUs for the requested Cognitive Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) ListSKUs(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListSKUsOptions) (AccountsListSKUsResponse, error) { + req, err := client.listSKUsCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsListSKUsResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsListSKUsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsListSKUsResponse{}, client.listSKUsHandleError(resp) + } + return client.listSKUsHandleResponse(resp) +} + +// listSKUsCreateRequest creates the ListSKUs request. +func (client *AccountsClient) listSKUsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListSKUsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/skus" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listSKUsHandleResponse handles the ListSKUs response. +func (client *AccountsClient) listSKUsHandleResponse(resp *http.Response) (AccountsListSKUsResponse, error) { + result := AccountsListSKUsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountSKUListResult); err != nil { + return AccountsListSKUsResponse{}, err + } + return result, nil +} + +// listSKUsHandleError handles the ListSKUs error response. +func (client *AccountsClient) listSKUsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListUsages - Get usages for the requested Cognitive Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) ListUsages(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListUsagesOptions) (AccountsListUsagesResponse, error) { + req, err := client.listUsagesCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsListUsagesResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsListUsagesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsListUsagesResponse{}, client.listUsagesHandleError(resp) + } + return client.listUsagesHandleResponse(resp) +} + +// listUsagesCreateRequest creates the ListUsages request. +func (client *AccountsClient) listUsagesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsListUsagesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/usages" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listUsagesHandleResponse handles the ListUsages response. +func (client *AccountsClient) listUsagesHandleResponse(resp *http.Response) (AccountsListUsagesResponse, error) { + result := AccountsListUsagesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.UsageListResult); err != nil { + return AccountsListUsagesResponse{}, err + } + return result, nil +} + +// listUsagesHandleError handles the ListUsages error response. +func (client *AccountsClient) listUsagesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// RegenerateKey - Regenerates the specified account key for the specified Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) RegenerateKey(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters, options *AccountsRegenerateKeyOptions) (AccountsRegenerateKeyResponse, error) { + req, err := client.regenerateKeyCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsRegenerateKeyResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsRegenerateKeyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsRegenerateKeyResponse{}, client.regenerateKeyHandleError(resp) + } + return client.regenerateKeyHandleResponse(resp) +} + +// regenerateKeyCreateRequest creates the RegenerateKey request. +func (client *AccountsClient) regenerateKeyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters RegenerateKeyParameters, options *AccountsRegenerateKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/regenerateKey" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeyHandleResponse handles the RegenerateKey response. +func (client *AccountsClient) regenerateKeyHandleResponse(resp *http.Response) (AccountsRegenerateKeyResponse, error) { + result := AccountsRegenerateKeyResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.APIKeys); err != nil { + return AccountsRegenerateKeyResponse{}, err + } + return result, nil +} + +// regenerateKeyHandleError handles the RegenerateKey error response. +func (client *AccountsClient) regenerateKeyHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates a Cognitive Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginUpdateOptions) (AccountsUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return AccountsUpdatePollerResponse{}, err + } + result := AccountsUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return AccountsUpdatePollerResponse{}, err + } + result.Poller = &AccountsUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates a Cognitive Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) update(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, account, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, account Account, options *AccountsBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, account) +} + +// updateHandleError handles the Update error response. +func (client *AccountsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_cognitiveservicesmanagementclient_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_cognitiveservicesmanagementclient_client.go new file mode 100644 index 000000000000..655168c11edd --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_cognitiveservicesmanagementclient_client.go @@ -0,0 +1,153 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// CognitiveServicesManagementClient contains the methods for the CognitiveServicesManagementClient group. +// Don't use this type directly, use NewCognitiveServicesManagementClient() instead. +type CognitiveServicesManagementClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewCognitiveServicesManagementClient creates a new instance of CognitiveServicesManagementClient with the specified values. +func NewCognitiveServicesManagementClient(con *arm.Connection, subscriptionID string) *CognitiveServicesManagementClient { + return &CognitiveServicesManagementClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckDomainAvailability - Check whether a domain is available. +// If the operation fails it returns the *ErrorResponse error type. +func (client *CognitiveServicesManagementClient) CheckDomainAvailability(ctx context.Context, parameters CheckDomainAvailabilityParameter, options *CognitiveServicesManagementClientCheckDomainAvailabilityOptions) (CognitiveServicesManagementClientCheckDomainAvailabilityResponse, error) { + req, err := client.checkDomainAvailabilityCreateRequest(ctx, parameters, options) + if err != nil { + return CognitiveServicesManagementClientCheckDomainAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return CognitiveServicesManagementClientCheckDomainAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return CognitiveServicesManagementClientCheckDomainAvailabilityResponse{}, client.checkDomainAvailabilityHandleError(resp) + } + return client.checkDomainAvailabilityHandleResponse(resp) +} + +// checkDomainAvailabilityCreateRequest creates the CheckDomainAvailability request. +func (client *CognitiveServicesManagementClient) checkDomainAvailabilityCreateRequest(ctx context.Context, parameters CheckDomainAvailabilityParameter, options *CognitiveServicesManagementClientCheckDomainAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/checkDomainAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkDomainAvailabilityHandleResponse handles the CheckDomainAvailability response. +func (client *CognitiveServicesManagementClient) checkDomainAvailabilityHandleResponse(resp *http.Response) (CognitiveServicesManagementClientCheckDomainAvailabilityResponse, error) { + result := CognitiveServicesManagementClientCheckDomainAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DomainAvailability); err != nil { + return CognitiveServicesManagementClientCheckDomainAvailabilityResponse{}, err + } + return result, nil +} + +// checkDomainAvailabilityHandleError handles the CheckDomainAvailability error response. +func (client *CognitiveServicesManagementClient) checkDomainAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// CheckSKUAvailability - Check available SKUs. +// If the operation fails it returns the *ErrorResponse error type. +func (client *CognitiveServicesManagementClient) CheckSKUAvailability(ctx context.Context, location string, parameters CheckSKUAvailabilityParameter, options *CognitiveServicesManagementClientCheckSKUAvailabilityOptions) (CognitiveServicesManagementClientCheckSKUAvailabilityResponse, error) { + req, err := client.checkSKUAvailabilityCreateRequest(ctx, location, parameters, options) + if err != nil { + return CognitiveServicesManagementClientCheckSKUAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return CognitiveServicesManagementClientCheckSKUAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return CognitiveServicesManagementClientCheckSKUAvailabilityResponse{}, client.checkSKUAvailabilityHandleError(resp) + } + return client.checkSKUAvailabilityHandleResponse(resp) +} + +// checkSKUAvailabilityCreateRequest creates the CheckSKUAvailability request. +func (client *CognitiveServicesManagementClient) checkSKUAvailabilityCreateRequest(ctx context.Context, location string, parameters CheckSKUAvailabilityParameter, options *CognitiveServicesManagementClientCheckSKUAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/checkSkuAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkSKUAvailabilityHandleResponse handles the CheckSKUAvailability response. +func (client *CognitiveServicesManagementClient) checkSKUAvailabilityHandleResponse(resp *http.Response) (CognitiveServicesManagementClientCheckSKUAvailabilityResponse, error) { + result := CognitiveServicesManagementClientCheckSKUAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SKUAvailabilityListResult); err != nil { + return CognitiveServicesManagementClientCheckSKUAvailabilityResponse{}, err + } + return result, nil +} + +// checkSKUAvailabilityHandleError handles the CheckSKUAvailability error response. +func (client *CognitiveServicesManagementClient) checkSKUAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_constants.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_constants.go new file mode 100644 index 000000000000..5dc939f987b3 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_constants.go @@ -0,0 +1,395 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +const ( + module = "armcognitiveservices" + version = "v0.1.1" +) + +// ActionType - Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. +type ActionType string + +const ( + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// ToPtr returns a *ActionType pointing to the current value. +func (c ActionType) ToPtr() *ActionType { + return &c +} + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ToPtr returns a *CreatedByType pointing to the current value. +func (c CreatedByType) ToPtr() *CreatedByType { + return &c +} + +// KeyName - key name to generate (Key1|Key2) +type KeyName string + +const ( + KeyNameKey1 KeyName = "Key1" + KeyNameKey2 KeyName = "Key2" +) + +// PossibleKeyNameValues returns the possible values for the KeyName const type. +func PossibleKeyNameValues() []KeyName { + return []KeyName{ + KeyNameKey1, + KeyNameKey2, + } +} + +// ToPtr returns a *KeyName pointing to the current value. +func (c KeyName) ToPtr() *KeyName { + return &c +} + +// KeySource - Enumerates the possible value of keySource for Encryption +type KeySource string + +const ( + KeySourceMicrosoftCognitiveServices KeySource = "Microsoft.CognitiveServices" + KeySourceMicrosoftKeyVault KeySource = "Microsoft.KeyVault" +) + +// PossibleKeySourceValues returns the possible values for the KeySource const type. +func PossibleKeySourceValues() []KeySource { + return []KeySource{ + KeySourceMicrosoftCognitiveServices, + KeySourceMicrosoftKeyVault, + } +} + +// ToPtr returns a *KeySource pointing to the current value. +func (c KeySource) ToPtr() *KeySource { + return &c +} + +// NetworkRuleAction - The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property has +// been evaluated. +type NetworkRuleAction string + +const ( + NetworkRuleActionAllow NetworkRuleAction = "Allow" + NetworkRuleActionDeny NetworkRuleAction = "Deny" +) + +// PossibleNetworkRuleActionValues returns the possible values for the NetworkRuleAction const type. +func PossibleNetworkRuleActionValues() []NetworkRuleAction { + return []NetworkRuleAction{ + NetworkRuleActionAllow, + NetworkRuleActionDeny, + } +} + +// ToPtr returns a *NetworkRuleAction pointing to the current value. +func (c NetworkRuleAction) ToPtr() *NetworkRuleAction { + return &c +} + +// Origin - The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" +type Origin string + +const ( + OriginSystem Origin = "system" + OriginUser Origin = "user" + OriginUserSystem Origin = "user,system" +) + +// PossibleOriginValues returns the possible values for the Origin const type. +func PossibleOriginValues() []Origin { + return []Origin{ + OriginSystem, + OriginUser, + OriginUserSystem, + } +} + +// ToPtr returns a *Origin pointing to the current value. +func (c Origin) ToPtr() *Origin { + return &c +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + } +} + +// ToPtr returns a *PrivateEndpointConnectionProvisioningState pointing to the current value. +func (c PrivateEndpointConnectionProvisioningState) ToPtr() *PrivateEndpointConnectionProvisioningState { + return &c +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ToPtr returns a *PrivateEndpointServiceConnectionStatus pointing to the current value. +func (c PrivateEndpointServiceConnectionStatus) ToPtr() *PrivateEndpointServiceConnectionStatus { + return &c +} + +// ProvisioningState - Gets the status of the cognitive services account at the time the operation was called. +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateMoving ProvisioningState = "Moving" + ProvisioningStateResolvingDNS ProvisioningState = "ResolvingDNS" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCreating, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateMoving, + ProvisioningStateResolvingDNS, + ProvisioningStateSucceeded, + } +} + +// ToPtr returns a *ProvisioningState pointing to the current value. +func (c ProvisioningState) ToPtr() *ProvisioningState { + return &c +} + +// PublicNetworkAccess - Whether or not public endpoint access is allowed for this account. Value is optional but if passed in, must be 'Enabled' or 'Disabled' +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// ToPtr returns a *PublicNetworkAccess pointing to the current value. +func (c PublicNetworkAccess) ToPtr() *PublicNetworkAccess { + return &c +} + +// QuotaUsageStatus - Cognitive Services account quota usage status. +type QuotaUsageStatus string + +const ( + QuotaUsageStatusBlocked QuotaUsageStatus = "Blocked" + QuotaUsageStatusInOverage QuotaUsageStatus = "InOverage" + QuotaUsageStatusIncluded QuotaUsageStatus = "Included" + QuotaUsageStatusUnknown QuotaUsageStatus = "Unknown" +) + +// PossibleQuotaUsageStatusValues returns the possible values for the QuotaUsageStatus const type. +func PossibleQuotaUsageStatusValues() []QuotaUsageStatus { + return []QuotaUsageStatus{ + QuotaUsageStatusBlocked, + QuotaUsageStatusInOverage, + QuotaUsageStatusIncluded, + QuotaUsageStatusUnknown, + } +} + +// ToPtr returns a *QuotaUsageStatus pointing to the current value. +func (c QuotaUsageStatus) ToPtr() *QuotaUsageStatus { + return &c +} + +// ResourceIdentityType - The identity type. +type ResourceIdentityType string + +const ( + ResourceIdentityTypeNone ResourceIdentityType = "None" + ResourceIdentityTypeSystemAssigned ResourceIdentityType = "SystemAssigned" + ResourceIdentityTypeUserAssigned ResourceIdentityType = "UserAssigned" + ResourceIdentityTypeSystemAssignedUserAssigned ResourceIdentityType = "SystemAssigned, UserAssigned" +) + +// PossibleResourceIdentityTypeValues returns the possible values for the ResourceIdentityType const type. +func PossibleResourceIdentityTypeValues() []ResourceIdentityType { + return []ResourceIdentityType{ + ResourceIdentityTypeNone, + ResourceIdentityTypeSystemAssigned, + ResourceIdentityTypeUserAssigned, + ResourceIdentityTypeSystemAssignedUserAssigned, + } +} + +// ToPtr returns a *ResourceIdentityType pointing to the current value. +func (c ResourceIdentityType) ToPtr() *ResourceIdentityType { + return &c +} + +// ResourceSKURestrictionsReasonCode - The reason for restriction. +type ResourceSKURestrictionsReasonCode string + +const ( + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription ResourceSKURestrictionsReasonCode = "NotAvailableForSubscription" + ResourceSKURestrictionsReasonCodeQuotaID ResourceSKURestrictionsReasonCode = "QuotaId" +) + +// PossibleResourceSKURestrictionsReasonCodeValues returns the possible values for the ResourceSKURestrictionsReasonCode const type. +func PossibleResourceSKURestrictionsReasonCodeValues() []ResourceSKURestrictionsReasonCode { + return []ResourceSKURestrictionsReasonCode{ + ResourceSKURestrictionsReasonCodeNotAvailableForSubscription, + ResourceSKURestrictionsReasonCodeQuotaID, + } +} + +// ToPtr returns a *ResourceSKURestrictionsReasonCode pointing to the current value. +func (c ResourceSKURestrictionsReasonCode) ToPtr() *ResourceSKURestrictionsReasonCode { + return &c +} + +// ResourceSKURestrictionsType - The type of restrictions. +type ResourceSKURestrictionsType string + +const ( + ResourceSKURestrictionsTypeLocation ResourceSKURestrictionsType = "Location" + ResourceSKURestrictionsTypeZone ResourceSKURestrictionsType = "Zone" +) + +// PossibleResourceSKURestrictionsTypeValues returns the possible values for the ResourceSKURestrictionsType const type. +func PossibleResourceSKURestrictionsTypeValues() []ResourceSKURestrictionsType { + return []ResourceSKURestrictionsType{ + ResourceSKURestrictionsTypeLocation, + ResourceSKURestrictionsTypeZone, + } +} + +// ToPtr returns a *ResourceSKURestrictionsType pointing to the current value. +func (c ResourceSKURestrictionsType) ToPtr() *ResourceSKURestrictionsType { + return &c +} + +// SKUTier - This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. +type SKUTier string + +const ( + SKUTierBasic SKUTier = "Basic" + SKUTierEnterprise SKUTier = "Enterprise" + SKUTierFree SKUTier = "Free" + SKUTierPremium SKUTier = "Premium" + SKUTierStandard SKUTier = "Standard" +) + +// PossibleSKUTierValues returns the possible values for the SKUTier const type. +func PossibleSKUTierValues() []SKUTier { + return []SKUTier{ + SKUTierBasic, + SKUTierEnterprise, + SKUTierFree, + SKUTierPremium, + SKUTierStandard, + } +} + +// ToPtr returns a *SKUTier pointing to the current value. +func (c SKUTier) ToPtr() *SKUTier { + return &c +} + +// UnitType - The unit of the metric. +type UnitType string + +const ( + UnitTypeBytes UnitType = "Bytes" + UnitTypeBytesPerSecond UnitType = "BytesPerSecond" + UnitTypeCount UnitType = "Count" + UnitTypeCountPerSecond UnitType = "CountPerSecond" + UnitTypeMilliseconds UnitType = "Milliseconds" + UnitTypePercent UnitType = "Percent" + UnitTypeSeconds UnitType = "Seconds" +) + +// PossibleUnitTypeValues returns the possible values for the UnitType const type. +func PossibleUnitTypeValues() []UnitType { + return []UnitType{ + UnitTypeBytes, + UnitTypeBytesPerSecond, + UnitTypeCount, + UnitTypeCountPerSecond, + UnitTypeMilliseconds, + UnitTypePercent, + UnitTypeSeconds, + } +} + +// ToPtr returns a *UnitType pointing to the current value. +func (c UnitType) ToPtr() *UnitType { + return &c +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_deletedaccounts_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_deletedaccounts_client.go new file mode 100644 index 000000000000..a2d192e3fc48 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_deletedaccounts_client.go @@ -0,0 +1,239 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// DeletedAccountsClient contains the methods for the DeletedAccounts group. +// Don't use this type directly, use NewDeletedAccountsClient() instead. +type DeletedAccountsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewDeletedAccountsClient creates a new instance of DeletedAccountsClient with the specified values. +func NewDeletedAccountsClient(con *arm.Connection, subscriptionID string) *DeletedAccountsClient { + return &DeletedAccountsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Get - Returns a Cognitive Services account specified by the parameters. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DeletedAccountsClient) Get(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsGetOptions) (DeletedAccountsGetResponse, error) { + req, err := client.getCreateRequest(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return DeletedAccountsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return DeletedAccountsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return DeletedAccountsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *DeletedAccountsClient) getCreateRequest(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DeletedAccountsClient) getHandleResponse(resp *http.Response) (DeletedAccountsGetResponse, error) { + result := DeletedAccountsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Account); err != nil { + return DeletedAccountsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *DeletedAccountsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Returns all the resources of a particular type belonging to a subscription. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DeletedAccountsClient) List(options *DeletedAccountsListOptions) *DeletedAccountsListPager { + return &DeletedAccountsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp DeletedAccountsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AccountListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *DeletedAccountsClient) listCreateRequest(ctx context.Context, options *DeletedAccountsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/deletedAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *DeletedAccountsClient) listHandleResponse(resp *http.Response) (DeletedAccountsListResponse, error) { + result := DeletedAccountsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountListResult); err != nil { + return DeletedAccountsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *DeletedAccountsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginPurge - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DeletedAccountsClient) BeginPurge(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsBeginPurgeOptions) (DeletedAccountsPurgePollerResponse, error) { + resp, err := client.purge(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return DeletedAccountsPurgePollerResponse{}, err + } + result := DeletedAccountsPurgePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("DeletedAccountsClient.Purge", "", resp, client.pl, client.purgeHandleError) + if err != nil { + return DeletedAccountsPurgePollerResponse{}, err + } + result.Poller = &DeletedAccountsPurgePoller{ + pt: pt, + } + return result, nil +} + +// Purge - Deletes a Cognitive Services account from the resource group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DeletedAccountsClient) purge(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsBeginPurgeOptions) (*http.Response, error) { + req, err := client.purgeCreateRequest(ctx, location, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.purgeHandleError(resp) + } + return resp, nil +} + +// purgeCreateRequest creates the Purge request. +func (client *DeletedAccountsClient) purgeCreateRequest(ctx context.Context, location string, resourceGroupName string, accountName string, options *DeletedAccountsBeginPurgeOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/locations/{location}/resourceGroups/{resourceGroupName}/deletedAccounts/{accountName}" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// purgeHandleError handles the Purge error response. +func (client *DeletedAccountsClient) purgeHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_models.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_models.go new file mode 100644 index 000000000000..a62c0168f3c7 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_models.go @@ -0,0 +1,1217 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// APIKeys - The access keys for the cognitive services account. +type APIKeys struct { + // Gets the value of key 1. + Key1 *string `json:"key1,omitempty"` + + // Gets the value of key 2. + Key2 *string `json:"key2,omitempty"` +} + +// APIProperties - The api properties for special APIs. +type APIProperties struct { + // (Metrics Advisor Only) The Azure AD Client Id (Application Id). + AADClientID *string `json:"aadClientId,omitempty"` + + // (Metrics Advisor Only) The Azure AD Tenant Id. + AADTenantID *string `json:"aadTenantId,omitempty"` + + // OPTIONAL; Contains additional key/value pairs not defined in the schema. + AdditionalProperties map[string]map[string]interface{} + + // (Personalization Only) The flag to enable statistics of Bing Search. + EventHubConnectionString *string `json:"eventHubConnectionString,omitempty"` + + // (QnAMaker Only) The Azure Search endpoint id of QnAMaker. + QnaAzureSearchEndpointID *string `json:"qnaAzureSearchEndpointId,omitempty"` + + // (QnAMaker Only) The Azure Search endpoint key of QnAMaker. + QnaAzureSearchEndpointKey *string `json:"qnaAzureSearchEndpointKey,omitempty"` + + // (QnAMaker Only) The runtime endpoint of QnAMaker. + QnaRuntimeEndpoint *string `json:"qnaRuntimeEndpoint,omitempty"` + + // (Bing Search Only) The flag to enable statistics of Bing Search. + StatisticsEnabled *bool `json:"statisticsEnabled,omitempty"` + + // (Personalization Only) The storage account connection string. + StorageAccountConnectionString *string `json:"storageAccountConnectionString,omitempty"` + + // (Metrics Advisor Only) The super user of Metrics Advisor. + SuperUser *string `json:"superUser,omitempty"` + + // (Metrics Advisor Only) The website name of Metrics Advisor. + WebsiteName *string `json:"websiteName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type APIProperties. +func (a APIProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "aadClientId", a.AADClientID) + populate(objectMap, "aadTenantId", a.AADTenantID) + populate(objectMap, "eventHubConnectionString", a.EventHubConnectionString) + populate(objectMap, "qnaAzureSearchEndpointId", a.QnaAzureSearchEndpointID) + populate(objectMap, "qnaAzureSearchEndpointKey", a.QnaAzureSearchEndpointKey) + populate(objectMap, "qnaRuntimeEndpoint", a.QnaRuntimeEndpoint) + populate(objectMap, "statisticsEnabled", a.StatisticsEnabled) + populate(objectMap, "storageAccountConnectionString", a.StorageAccountConnectionString) + populate(objectMap, "superUser", a.SuperUser) + populate(objectMap, "websiteName", a.WebsiteName) + if a.AdditionalProperties != nil { + for key, val := range a.AdditionalProperties { + objectMap[key] = val + } + } + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type APIProperties. +func (a *APIProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "aadClientId": + err = unpopulate(val, &a.AADClientID) + delete(rawMsg, key) + case "aadTenantId": + err = unpopulate(val, &a.AADTenantID) + delete(rawMsg, key) + case "eventHubConnectionString": + err = unpopulate(val, &a.EventHubConnectionString) + delete(rawMsg, key) + case "qnaAzureSearchEndpointId": + err = unpopulate(val, &a.QnaAzureSearchEndpointID) + delete(rawMsg, key) + case "qnaAzureSearchEndpointKey": + err = unpopulate(val, &a.QnaAzureSearchEndpointKey) + delete(rawMsg, key) + case "qnaRuntimeEndpoint": + err = unpopulate(val, &a.QnaRuntimeEndpoint) + delete(rawMsg, key) + case "statisticsEnabled": + err = unpopulate(val, &a.StatisticsEnabled) + delete(rawMsg, key) + case "storageAccountConnectionString": + err = unpopulate(val, &a.StorageAccountConnectionString) + delete(rawMsg, key) + case "superUser": + err = unpopulate(val, &a.SuperUser) + delete(rawMsg, key) + case "websiteName": + err = unpopulate(val, &a.WebsiteName) + delete(rawMsg, key) + default: + if a.AdditionalProperties == nil { + a.AdditionalProperties = map[string]map[string]interface{}{} + } + if val != nil { + var aux map[string]interface{} + err = json.Unmarshal(val, &aux) + a.AdditionalProperties[key] = aux + } + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// Account - Cognitive Services account is an Azure resource representing the provisioned account, it's type, location and SKU. +type Account struct { + AzureEntityResource + // Identity for the resource. + Identity *Identity `json:"identity,omitempty"` + + // The Kind of the resource. + Kind *string `json:"kind,omitempty"` + + // The geo-location where the resource lives + Location *string `json:"location,omitempty"` + + // Properties of Cognitive Services account. + Properties *AccountProperties `json:"properties,omitempty"` + + // The resource model definition representing SKU + SKU *SKU `json:"sku,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Account. +func (a Account) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.AzureEntityResource.marshalInternal(objectMap) + populate(objectMap, "identity", a.Identity) + populate(objectMap, "kind", a.Kind) + populate(objectMap, "location", a.Location) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "sku", a.SKU) + populate(objectMap, "systemData", a.SystemData) + populate(objectMap, "tags", a.Tags) + return json.Marshal(objectMap) +} + +// AccountListResult - The list of cognitive services accounts operation response. +type AccountListResult struct { + // The link used to get the next page of accounts. + NextLink *string `json:"nextLink,omitempty"` + + // READ-ONLY; Gets the list of Cognitive Services accounts and their properties. + Value []*Account `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccountListResult. +func (a AccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AccountProperties - Properties of Cognitive Services account. +type AccountProperties struct { + // The api properties for special APIs. + APIProperties *APIProperties `json:"apiProperties,omitempty"` + AllowedFqdnList []*string `json:"allowedFqdnList,omitempty"` + + // Optional subdomain name used for token-based authentication. + CustomSubDomainName *string `json:"customSubDomainName,omitempty"` + DisableLocalAuth *bool `json:"disableLocalAuth,omitempty"` + + // The encryption properties for this resource. + Encryption *Encryption `json:"encryption,omitempty"` + + // Resource migration token. + MigrationToken *string `json:"migrationToken,omitempty"` + + // A collection of rules governing the accessibility from specific network locations. + NetworkACLs *NetworkRuleSet `json:"networkAcls,omitempty"` + + // Whether or not public endpoint access is allowed for this account. Value is optional but if passed in, must be 'Enabled' or 'Disabled' + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + Restore *bool `json:"restore,omitempty"` + RestrictOutboundNetworkAccess *bool `json:"restrictOutboundNetworkAccess,omitempty"` + + // The storage accounts for this resource. + UserOwnedStorage []*UserOwnedStorage `json:"userOwnedStorage,omitempty"` + + // READ-ONLY; The call rate limit Cognitive Services account. + CallRateLimit *CallRateLimit `json:"callRateLimit,omitempty" azure:"ro"` + + // READ-ONLY; Gets the capabilities of the cognitive services account. Each item indicates the capability of a specific feature. The values are read-only + // and for reference only. + Capabilities []*SKUCapability `json:"capabilities,omitempty" azure:"ro"` + + // READ-ONLY; Gets the date of cognitive services account creation. + DateCreated *string `json:"dateCreated,omitempty" azure:"ro"` + + // READ-ONLY; Endpoint of the created account. + Endpoint *string `json:"endpoint,omitempty" azure:"ro"` + + // READ-ONLY; Dictionary of + Endpoints map[string]*string `json:"endpoints,omitempty" azure:"ro"` + + // READ-ONLY; The internal identifier (deprecated, do not use this property). + InternalID *string `json:"internalId,omitempty" azure:"ro"` + + // READ-ONLY; If the resource is migrated from an existing key. + IsMigrated *bool `json:"isMigrated,omitempty" azure:"ro"` + + // READ-ONLY; The private endpoint connection associated with the Cognitive Services account. + PrivateEndpointConnections []*PrivateEndpointConnection `json:"privateEndpointConnections,omitempty" azure:"ro"` + + // READ-ONLY; Gets the status of the cognitive services account at the time the operation was called. + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY + QuotaLimit *QuotaLimit `json:"quotaLimit,omitempty" azure:"ro"` + + // READ-ONLY; Sku change info of account. + SKUChangeInfo *SKUChangeInfo `json:"skuChangeInfo,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccountProperties. +func (a AccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "apiProperties", a.APIProperties) + populate(objectMap, "allowedFqdnList", a.AllowedFqdnList) + populate(objectMap, "callRateLimit", a.CallRateLimit) + populate(objectMap, "capabilities", a.Capabilities) + populate(objectMap, "customSubDomainName", a.CustomSubDomainName) + populate(objectMap, "dateCreated", a.DateCreated) + populate(objectMap, "disableLocalAuth", a.DisableLocalAuth) + populate(objectMap, "encryption", a.Encryption) + populate(objectMap, "endpoint", a.Endpoint) + populate(objectMap, "endpoints", a.Endpoints) + populate(objectMap, "internalId", a.InternalID) + populate(objectMap, "isMigrated", a.IsMigrated) + populate(objectMap, "migrationToken", a.MigrationToken) + populate(objectMap, "networkAcls", a.NetworkACLs) + populate(objectMap, "privateEndpointConnections", a.PrivateEndpointConnections) + populate(objectMap, "provisioningState", a.ProvisioningState) + populate(objectMap, "publicNetworkAccess", a.PublicNetworkAccess) + populate(objectMap, "quotaLimit", a.QuotaLimit) + populate(objectMap, "restore", a.Restore) + populate(objectMap, "restrictOutboundNetworkAccess", a.RestrictOutboundNetworkAccess) + populate(objectMap, "skuChangeInfo", a.SKUChangeInfo) + populate(objectMap, "userOwnedStorage", a.UserOwnedStorage) + return json.Marshal(objectMap) +} + +// AccountSKU - Cognitive Services resource type and SKU. +type AccountSKU struct { + // Resource Namespace and Type + ResourceType *string `json:"resourceType,omitempty"` + + // The SKU of Cognitive Services account. + SKU *SKU `json:"sku,omitempty"` +} + +// AccountSKUListResult - The list of cognitive services accounts operation response. +type AccountSKUListResult struct { + // Gets the list of Cognitive Services accounts and their properties. + Value []*AccountSKU `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccountSKUListResult. +func (a AccountSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AccountsBeginCreateOptions contains the optional parameters for the Accounts.BeginCreate method. +type AccountsBeginCreateOptions struct { + // placeholder for future optional parameters +} + +// AccountsBeginDeleteOptions contains the optional parameters for the Accounts.BeginDelete method. +type AccountsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// AccountsBeginUpdateOptions contains the optional parameters for the Accounts.BeginUpdate method. +type AccountsBeginUpdateOptions struct { + // placeholder for future optional parameters +} + +// AccountsGetOptions contains the optional parameters for the Accounts.Get method. +type AccountsGetOptions struct { + // placeholder for future optional parameters +} + +// AccountsListByResourceGroupOptions contains the optional parameters for the Accounts.ListByResourceGroup method. +type AccountsListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// AccountsListKeysOptions contains the optional parameters for the Accounts.ListKeys method. +type AccountsListKeysOptions struct { + // placeholder for future optional parameters +} + +// AccountsListOptions contains the optional parameters for the Accounts.List method. +type AccountsListOptions struct { + // placeholder for future optional parameters +} + +// AccountsListSKUsOptions contains the optional parameters for the Accounts.ListSKUs method. +type AccountsListSKUsOptions struct { + // placeholder for future optional parameters +} + +// AccountsListUsagesOptions contains the optional parameters for the Accounts.ListUsages method. +type AccountsListUsagesOptions struct { + // An OData filter expression that describes a subset of usages to return. The supported parameter is name.value (name of the metric, can have an or of + // multiple names). + Filter *string +} + +// AccountsRegenerateKeyOptions contains the optional parameters for the Accounts.RegenerateKey method. +type AccountsRegenerateKeyOptions struct { + // placeholder for future optional parameters +} + +// AzureEntityResource - The resource model definition for an Azure Resource Manager resource with an etag. +type AzureEntityResource struct { + Resource + // READ-ONLY; Resource Etag. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureEntityResource. +func (a AzureEntityResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (a AzureEntityResource) marshalInternal(objectMap map[string]interface{}) { + a.Resource.marshalInternal(objectMap) + populate(objectMap, "etag", a.Etag) +} + +// CallRateLimit - The call rate limit Cognitive Services account. +type CallRateLimit struct { + // The count value of Call Rate Limit. + Count *float32 `json:"count,omitempty"` + + // The renewal period in seconds of Call Rate Limit. + RenewalPeriod *float32 `json:"renewalPeriod,omitempty"` + Rules []*ThrottlingRule `json:"rules,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CallRateLimit. +func (c CallRateLimit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", c.Count) + populate(objectMap, "renewalPeriod", c.RenewalPeriod) + populate(objectMap, "rules", c.Rules) + return json.Marshal(objectMap) +} + +// CheckDomainAvailabilityParameter - Check Domain availability parameter. +type CheckDomainAvailabilityParameter struct { + // REQUIRED; The subdomain name to use. + SubdomainName *string `json:"subdomainName,omitempty"` + + // REQUIRED; The Type of the resource. + Type *string `json:"type,omitempty"` +} + +// CheckSKUAvailabilityParameter - Check SKU availability parameter. +type CheckSKUAvailabilityParameter struct { + // REQUIRED; The Kind of the resource. + Kind *string `json:"kind,omitempty"` + + // REQUIRED; The SKU of the resource. + SKUs []*string `json:"skus,omitempty"` + + // REQUIRED; The Type of the resource. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CheckSKUAvailabilityParameter. +func (c CheckSKUAvailabilityParameter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "kind", c.Kind) + populate(objectMap, "skus", c.SKUs) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// CognitiveServicesManagementClientCheckDomainAvailabilityOptions contains the optional parameters for the CognitiveServicesManagementClient.CheckDomainAvailability +// method. +type CognitiveServicesManagementClientCheckDomainAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// CognitiveServicesManagementClientCheckSKUAvailabilityOptions contains the optional parameters for the CognitiveServicesManagementClient.CheckSKUAvailability +// method. +type CognitiveServicesManagementClientCheckSKUAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsBeginPurgeOptions contains the optional parameters for the DeletedAccounts.BeginPurge method. +type DeletedAccountsBeginPurgeOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsGetOptions contains the optional parameters for the DeletedAccounts.Get method. +type DeletedAccountsGetOptions struct { + // placeholder for future optional parameters +} + +// DeletedAccountsListOptions contains the optional parameters for the DeletedAccounts.List method. +type DeletedAccountsListOptions struct { + // placeholder for future optional parameters +} + +// DomainAvailability - Domain availability. +type DomainAvailability struct { + // Indicates the given SKU is available or not. + IsSubdomainAvailable *bool `json:"isSubdomainAvailable,omitempty"` + + // Reason why the SKU is not available. + Reason *string `json:"reason,omitempty"` + + // The subdomain name to use. + SubdomainName *string `json:"subdomainName,omitempty"` + + // The Type of the resource. + Type *string `json:"type,omitempty"` +} + +// Encryption - Properties to configure Encryption +type Encryption struct { + // Enumerates the possible value of keySource for Encryption + KeySource *KeySource `json:"keySource,omitempty"` + + // Properties of KeyVault + KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info map[string]interface{} `json:"info,omitempty" azure:"ro"` + + // READ-ONLY; The additional info type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo `json:"additionalInfo,omitempty" azure:"ro"` + + // READ-ONLY; The error code. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; The error details. + Details []*ErrorDetail `json:"details,omitempty" azure:"ro"` + + // READ-ONLY; The error message. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The error target. + Target *string `json:"target,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponse - Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData +// error response format.). +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // The error object. + InnerError *ErrorDetail `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// IPRule - A rule governing the accessibility from a specific ip address or ip range. +type IPRule struct { + // REQUIRED; An IPv4 address range in CIDR notation, such as '124.56.78.91' (simple IP address) or '124.56.78.0/24' (all addresses that start with 124.56.78). + Value *string `json:"value,omitempty"` +} + +// Identity for the resource. +type Identity struct { + // The identity type. + Type *ResourceIdentityType `json:"type,omitempty"` + + // The list of user assigned identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: + // '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName} + UserAssignedIdentities map[string]*UserAssignedIdentity `json:"userAssignedIdentities,omitempty"` + + // READ-ONLY; The principal ID of resource identity. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` + + // READ-ONLY; The tenant ID of resource. + TenantID *string `json:"tenantId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Identity. +func (i Identity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "principalId", i.PrincipalID) + populate(objectMap, "tenantId", i.TenantID) + populate(objectMap, "type", i.Type) + populate(objectMap, "userAssignedIdentities", i.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// KeyVaultProperties - Properties to configure keyVault Properties +type KeyVaultProperties struct { + IdentityClientID *string `json:"identityClientId,omitempty"` + + // Name of the Key from KeyVault + KeyName *string `json:"keyName,omitempty"` + + // Uri of KeyVault + KeyVaultURI *string `json:"keyVaultUri,omitempty"` + + // Version of the Key from KeyVault + KeyVersion *string `json:"keyVersion,omitempty"` +} + +// MetricName - A metric name. +type MetricName struct { + // The friendly name of the metric. + LocalizedValue *string `json:"localizedValue,omitempty"` + + // The name of the metric. + Value *string `json:"value,omitempty"` +} + +// NetworkRuleSet - A set of rules governing the network accessibility. +type NetworkRuleSet struct { + // The default action when no rule from ipRules and from virtualNetworkRules match. This is only used after the bypass property has been evaluated. + DefaultAction *NetworkRuleAction `json:"defaultAction,omitempty"` + + // The list of IP address rules. + IPRules []*IPRule `json:"ipRules,omitempty"` + + // The list of virtual network rules. + VirtualNetworkRules []*VirtualNetworkRule `json:"virtualNetworkRules,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "defaultAction", n.DefaultAction) + populate(objectMap, "ipRules", n.IPRules) + populate(objectMap, "virtualNetworkRules", n.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// Operation - Details of a REST API operation, returned from the Resource Provider Operations API +type Operation struct { + // Localized display information for this particular operation. + Display *OperationDisplay `json:"display,omitempty"` + + // READ-ONLY; Enum. Indicates the action type. "Internal" refers to actions that are for internal only APIs. + ActionType *ActionType `json:"actionType,omitempty" azure:"ro"` + + // READ-ONLY; Whether the operation applies to data-plane. This is "true" for data-plane operations and "false" for ARM/control-plane operations. + IsDataAction *bool `json:"isDataAction,omitempty" azure:"ro"` + + // READ-ONLY; The name of the operation, as per Resource-Based Access Control (RBAC). Examples: "Microsoft.Compute/virtualMachines/write", "Microsoft.Compute/virtualMachines/capture/action" + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The intended executor of the operation; as in Resource Based Access Control (RBAC) and audit logs UX. Default value is "user,system" + Origin *Origin `json:"origin,omitempty" azure:"ro"` +} + +// OperationDisplay - Localized display information for this particular operation. +type OperationDisplay struct { + // READ-ONLY; The short, localized friendly description of the operation; suitable for tool tips and detailed views. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; The concise, localized friendly name for the operation; suitable for dropdowns. E.g. "Create or Update Virtual Machine", "Restart Virtual + // Machine". + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; The localized friendly form of the resource provider name, e.g. "Microsoft Monitoring Insights" or "Microsoft Compute". + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; The localized friendly name of the resource type related to this operation. E.g. "Virtual Machines" or "Job Schedule Collections". + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - A list of REST API operations supported by an Azure Resource Provider. It contains an URL link to get the next set of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results (if there are any). + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; List of operations supported by the resource provider + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpoint - The Private Endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The ARM identifier for Private Endpoint + ID *string `json:"id,omitempty" azure:"ro"` +} + +// PrivateEndpointConnection - The Private Endpoint Connection resource. +type PrivateEndpointConnection struct { + AzureEntityResource + // The location of the private endpoint connection + Location *string `json:"location,omitempty"` + + // Resource properties. + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + + // READ-ONLY; Metadata pertaining to creation and last modification of the resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.AzureEntityResource.marshalInternal(objectMap) + populate(objectMap, "location", p.Location) + populate(objectMap, "properties", p.Properties) + populate(objectMap, "systemData", p.SystemData) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionListResult - A list of private endpoint connections +type PrivateEndpointConnectionListResult struct { + // Array of private endpoint connections + Value []*PrivateEndpointConnection `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnectProperties. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + + // The private link resource group ids. + GroupIDs []*string `json:"groupIds,omitempty"` + + // The resource of private end point. + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState `json:"provisioningState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionProperties. +func (p PrivateEndpointConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateEndpoint", p.PrivateEndpoint) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "provisioningState", p.ProvisioningState) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionsBeginCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnections.BeginCreateOrUpdate method. +type PrivateEndpointConnectionsBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnections.BeginDelete method. +type PrivateEndpointConnectionsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsGetOptions contains the optional parameters for the PrivateEndpointConnections.Get method. +type PrivateEndpointConnectionsGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsListOptions contains the optional parameters for the PrivateEndpointConnections.List method. +type PrivateEndpointConnectionsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResource - A private link resource +type PrivateLinkResource struct { + Resource + // Resource properties. + Properties *PrivateLinkResourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateLinkResourceListResult - A list of private link resources +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource Private link DNS zone name. + RequiredZoneNames []*string `json:"requiredZoneNames,omitempty"` + + // READ-ONLY; The private link resource display name. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; The private link resource group id. + GroupID *string `json:"groupId,omitempty" azure:"ro"` + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string `json:"requiredMembers,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// PrivateLinkResourcesListOptions contains the optional parameters for the PrivateLinkResources.List method. +type PrivateLinkResourcesListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string `json:"actionsRequired,omitempty"` + + // The reason for approval/rejection of the connection. + Description *string `json:"description,omitempty"` + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus `json:"status,omitempty"` +} + +type QuotaLimit struct { + Count *float32 `json:"count,omitempty"` + RenewalPeriod *float32 `json:"renewalPeriod,omitempty"` + Rules []*ThrottlingRule `json:"rules,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type QuotaLimit. +func (q QuotaLimit) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", q.Count) + populate(objectMap, "renewalPeriod", q.RenewalPeriod) + populate(objectMap, "rules", q.Rules) + return json.Marshal(objectMap) +} + +// RegenerateKeyParameters - Regenerate key parameters. +type RegenerateKeyParameters struct { + // REQUIRED; key name to generate (Key1|Key2) + KeyName *KeyName `json:"keyName,omitempty"` +} + +type RequestMatchPattern struct { + Method *string `json:"method,omitempty"` + Path *string `json:"path,omitempty"` +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +// ResourceSKU - Describes an available Cognitive Services SKU. +type ResourceSKU struct { + // The Kind of resources that are supported in this SKU. + Kind *string `json:"kind,omitempty"` + + // The set of locations that the SKU is available. + Locations []*string `json:"locations,omitempty"` + + // The name of SKU. + Name *string `json:"name,omitempty"` + + // The type of resource the SKU applies to. + ResourceType *string `json:"resourceType,omitempty"` + + // The restrictions because of which SKU cannot be used. This is empty if there are no restrictions. + Restrictions []*ResourceSKURestrictions `json:"restrictions,omitempty"` + + // Specifies the tier of Cognitive Services account. + Tier *string `json:"tier,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKU. +func (r ResourceSKU) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "kind", r.Kind) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "name", r.Name) + populate(objectMap, "resourceType", r.ResourceType) + populate(objectMap, "restrictions", r.Restrictions) + populate(objectMap, "tier", r.Tier) + return json.Marshal(objectMap) +} + +// ResourceSKUListResult - The Get Skus operation response. +type ResourceSKUListResult struct { + // REQUIRED; The list of skus available for the subscription. + Value []*ResourceSKU `json:"value,omitempty"` + + // The uri to fetch the next page of Skus. + NextLink *string `json:"nextLink,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKUListResult. +func (r ResourceSKUListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +type ResourceSKURestrictionInfo struct { + // Locations where the SKU is restricted + Locations []*string `json:"locations,omitempty"` + + // List of availability zones where the SKU is restricted. + Zones []*string `json:"zones,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictionInfo. +func (r ResourceSKURestrictionInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "locations", r.Locations) + populate(objectMap, "zones", r.Zones) + return json.Marshal(objectMap) +} + +// ResourceSKURestrictions - Describes restrictions of a SKU. +type ResourceSKURestrictions struct { + // The reason for restriction. + ReasonCode *ResourceSKURestrictionsReasonCode `json:"reasonCode,omitempty"` + + // The information about the restriction where the SKU cannot be used. + RestrictionInfo *ResourceSKURestrictionInfo `json:"restrictionInfo,omitempty"` + + // The type of restrictions. + Type *ResourceSKURestrictionsType `json:"type,omitempty"` + + // The value of restrictions. If the restriction type is set to location. This would be different locations where the SKU is restricted. + Values []*string `json:"values,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceSKURestrictions. +func (r ResourceSKURestrictions) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "reasonCode", r.ReasonCode) + populate(objectMap, "restrictionInfo", r.RestrictionInfo) + populate(objectMap, "type", r.Type) + populate(objectMap, "values", r.Values) + return json.Marshal(objectMap) +} + +// ResourceSKUsListOptions contains the optional parameters for the ResourceSKUs.List method. +type ResourceSKUsListOptions struct { + // placeholder for future optional parameters +} + +// SKU - The resource model definition representing SKU +type SKU struct { + // REQUIRED; The name of the SKU. Ex - P3. It is typically a letter+number code + Name *string `json:"name,omitempty"` + + // If the SKU supports scale out/in then the capacity integer should be included. If scale out/in is not possible for the resource this may be omitted. + Capacity *int32 `json:"capacity,omitempty"` + + // If the service has different generations of hardware, for the same SKU, then that can be captured here. + Family *string `json:"family,omitempty"` + + // The SKU size. When the name field is the combination of tier and some other value, this would be the standalone code. + Size *string `json:"size,omitempty"` + + // This field is required to be implemented by the Resource Provider if the service has more than one tier, but is not required on a PUT. + Tier *SKUTier `json:"tier,omitempty"` +} + +// SKUAvailability - SKU availability. +type SKUAvailability struct { + // The Kind of the resource. + Kind *string `json:"kind,omitempty"` + + // Additional error message. + Message *string `json:"message,omitempty"` + + // Reason why the SKU is not available. + Reason *string `json:"reason,omitempty"` + + // Indicates the given SKU is available or not. + SKUAvailable *bool `json:"skuAvailable,omitempty"` + + // The SKU of Cognitive Services account. + SKUName *string `json:"skuName,omitempty"` + + // The Type of the resource. + Type *string `json:"type,omitempty"` +} + +// SKUAvailabilityListResult - Check SKU availability result list. +type SKUAvailabilityListResult struct { + // Check SKU availability result list. + Value []*SKUAvailability `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SKUAvailabilityListResult. +func (s SKUAvailabilityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// SKUCapability - SkuCapability indicates the capability of a certain feature. +type SKUCapability struct { + // The name of the SkuCapability. + Name *string `json:"name,omitempty"` + + // The value of the SkuCapability. + Value *string `json:"value,omitempty"` +} + +// SKUChangeInfo - Sku change info of account. +type SKUChangeInfo struct { + // Gets the count of downgrades. + CountOfDowngrades *float32 `json:"countOfDowngrades,omitempty"` + + // Gets the count of upgrades after downgrades. + CountOfUpgradesAfterDowngrades *float32 `json:"countOfUpgradesAfterDowngrades,omitempty"` + + // Gets the last change date. + LastChangeDate *string `json:"lastChangeDate,omitempty"` +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // The identity that created the resource. + CreatedBy *string `json:"createdBy,omitempty"` + + // The type of identity that created the resource. + CreatedByType *CreatedByType `json:"createdByType,omitempty"` + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time `json:"lastModifiedAt,omitempty"` + + // The identity that last modified the resource. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType `json:"lastModifiedByType,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(s.CreatedAt)) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populate(objectMap, "lastModifiedAt", (*timeRFC3339)(s.LastModifiedAt)) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type ThrottlingRule struct { + Count *float32 `json:"count,omitempty"` + DynamicThrottlingEnabled *bool `json:"dynamicThrottlingEnabled,omitempty"` + Key *string `json:"key,omitempty"` + MatchPatterns []*RequestMatchPattern `json:"matchPatterns,omitempty"` + MinCount *float32 `json:"minCount,omitempty"` + RenewalPeriod *float32 `json:"renewalPeriod,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ThrottlingRule. +func (t ThrottlingRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", t.Count) + populate(objectMap, "dynamicThrottlingEnabled", t.DynamicThrottlingEnabled) + populate(objectMap, "key", t.Key) + populate(objectMap, "matchPatterns", t.MatchPatterns) + populate(objectMap, "minCount", t.MinCount) + populate(objectMap, "renewalPeriod", t.RenewalPeriod) + return json.Marshal(objectMap) +} + +// Usage - The usage data for a usage request. +type Usage struct { + // Current value for this metric. + CurrentValue *float64 `json:"currentValue,omitempty"` + + // Maximum value for this metric. + Limit *float64 `json:"limit,omitempty"` + + // The name information for the metric. + Name *MetricName `json:"name,omitempty"` + + // Next reset time for current quota. + NextResetTime *string `json:"nextResetTime,omitempty"` + + // The quota period used to summarize the usage values. + QuotaPeriod *string `json:"quotaPeriod,omitempty"` + + // Cognitive Services account quota usage status. + Status *QuotaUsageStatus `json:"status,omitempty"` + + // The unit of the metric. + Unit *UnitType `json:"unit,omitempty"` +} + +// UsageListResult - The response to a list usage request. +type UsageListResult struct { + // The list of usages for Cognitive Service account. + Value []*Usage `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UsageListResult. +func (u UsageListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", u.Value) + return json.Marshal(objectMap) +} + +// UserAssignedIdentity - User-assigned managed identity. +type UserAssignedIdentity struct { + // READ-ONLY; Client App Id associated with this identity. + ClientID *string `json:"clientId,omitempty" azure:"ro"` + + // READ-ONLY; Azure Active Directory principal ID associated with this Identity. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` +} + +// UserOwnedStorage - The user owned storage for Cognitive Services account. +type UserOwnedStorage struct { + IdentityClientID *string `json:"identityClientId,omitempty"` + + // Full resource id of a Microsoft.Storage resource. + ResourceID *string `json:"resourceId,omitempty"` +} + +// VirtualNetworkRule - A rule governing the accessibility from a specific virtual network. +type VirtualNetworkRule struct { + // REQUIRED; Full resource id of a vnet subnet, such as '/subscriptions/subid/resourceGroups/rg1/providers/Microsoft.Network/virtualNetworks/test-vnet/subnets/subnet1'. + ID *string `json:"id,omitempty"` + + // Ignore missing vnet service endpoint or not. + IgnoreMissingVnetServiceEndpoint *bool `json:"ignoreMissingVnetServiceEndpoint,omitempty"` + + // Gets the state of virtual network rule. + State *string `json:"state,omitempty"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_operations_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_operations_client.go new file mode 100644 index 000000000000..b153e5f5288c --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all the available Cognitive Services account operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.CognitiveServices/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pagers.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pagers.go new file mode 100644 index 000000000000..73b8bc6d6f1f --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pagers.go @@ -0,0 +1,288 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountsListByResourceGroupPager provides operations for iterating over paged responses. +type AccountsListByResourceGroupPager struct { + client *AccountsClient + current AccountsListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AccountsListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AccountsListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AccountsListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AccountListResult.NextLink == nil || len(*p.current.AccountListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AccountsListByResourceGroupResponse page. +func (p *AccountsListByResourceGroupPager) PageResponse() AccountsListByResourceGroupResponse { + return p.current +} + +// AccountsListPager provides operations for iterating over paged responses. +type AccountsListPager struct { + client *AccountsClient + current AccountsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AccountsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AccountsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AccountsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AccountListResult.NextLink == nil || len(*p.current.AccountListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AccountsListResponse page. +func (p *AccountsListPager) PageResponse() AccountsListResponse { + return p.current +} + +// DeletedAccountsListPager provides operations for iterating over paged responses. +type DeletedAccountsListPager struct { + client *DeletedAccountsClient + current DeletedAccountsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, DeletedAccountsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *DeletedAccountsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *DeletedAccountsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AccountListResult.NextLink == nil || len(*p.current.AccountListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current DeletedAccountsListResponse page. +func (p *DeletedAccountsListPager) PageResponse() DeletedAccountsListResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} + +// ResourceSKUsListPager provides operations for iterating over paged responses. +type ResourceSKUsListPager struct { + client *ResourceSKUsClient + current ResourceSKUsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ResourceSKUsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ResourceSKUsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ResourceSKUsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ResourceSKUListResult.NextLink == nil || len(*p.current.ResourceSKUListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ResourceSKUsListResponse page. +func (p *ResourceSKUsListPager) PageResponse() ResourceSKUsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pollers.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pollers.go new file mode 100644 index 000000000000..bb1f7f6fbf93 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_pollers.go @@ -0,0 +1,274 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AccountsCreatePoller provides polling facilities until the operation reaches a terminal state. +type AccountsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsCreateResponse will be returned. +func (p *AccountsCreatePoller) FinalResponse(ctx context.Context) (AccountsCreateResponse, error) { + respType := AccountsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Account) + if err != nil { + return AccountsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// AccountsDeletePoller provides polling facilities until the operation reaches a terminal state. +type AccountsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsDeleteResponse will be returned. +func (p *AccountsDeletePoller) FinalResponse(ctx context.Context) (AccountsDeleteResponse, error) { + respType := AccountsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return AccountsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// AccountsUpdatePoller provides polling facilities until the operation reaches a terminal state. +type AccountsUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsUpdateResponse will be returned. +func (p *AccountsUpdatePoller) FinalResponse(ctx context.Context) (AccountsUpdateResponse, error) { + respType := AccountsUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Account) + if err != nil { + return AccountsUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// DeletedAccountsPurgePoller provides polling facilities until the operation reaches a terminal state. +type DeletedAccountsPurgePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *DeletedAccountsPurgePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *DeletedAccountsPurgePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final DeletedAccountsPurgeResponse will be returned. +func (p *DeletedAccountsPurgePoller) FinalResponse(ctx context.Context) (DeletedAccountsPurgeResponse, error) { + respType := DeletedAccountsPurgeResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return DeletedAccountsPurgeResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *DeletedAccountsPurgePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// PrivateEndpointConnectionsCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type PrivateEndpointConnectionsCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *PrivateEndpointConnectionsCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *PrivateEndpointConnectionsCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final PrivateEndpointConnectionsCreateOrUpdateResponse will be returned. +func (p *PrivateEndpointConnectionsCreateOrUpdatePoller) FinalResponse(ctx context.Context) (PrivateEndpointConnectionsCreateOrUpdateResponse, error) { + respType := PrivateEndpointConnectionsCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.PrivateEndpointConnection) + if err != nil { + return PrivateEndpointConnectionsCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *PrivateEndpointConnectionsCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// PrivateEndpointConnectionsDeletePoller provides polling facilities until the operation reaches a terminal state. +type PrivateEndpointConnectionsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *PrivateEndpointConnectionsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *PrivateEndpointConnectionsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final PrivateEndpointConnectionsDeleteResponse will be returned. +func (p *PrivateEndpointConnectionsDeletePoller) FinalResponse(ctx context.Context) (PrivateEndpointConnectionsDeleteResponse, error) { + respType := PrivateEndpointConnectionsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *PrivateEndpointConnectionsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privateendpointconnections_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privateendpointconnections_client.go new file mode 100644 index 000000000000..8899e266bf13 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privateendpointconnections_client.go @@ -0,0 +1,330 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +func NewPrivateEndpointConnectionsClient(con *arm.Connection, subscriptionID string) *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrUpdate - Update the state of specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOrUpdateOptions) (PrivateEndpointConnectionsCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, accountName, privateEndpointConnectionName, properties, options) + if err != nil { + return PrivateEndpointConnectionsCreateOrUpdatePollerResponse{}, err + } + result := PrivateEndpointConnectionsCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("PrivateEndpointConnectionsClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return PrivateEndpointConnectionsCreateOrUpdatePollerResponse{}, err + } + result.Poller = &PrivateEndpointConnectionsCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Update the state of specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) createOrUpdate(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, properties, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrivateEndpointConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, properties PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, properties) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *PrivateEndpointConnectionsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (PrivateEndpointConnectionsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsDeletePollerResponse{}, err + } + result := PrivateEndpointConnectionsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("PrivateEndpointConnectionsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return PrivateEndpointConnectionsDeletePollerResponse{}, err + } + result.Poller = &PrivateEndpointConnectionsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *PrivateEndpointConnectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the specified private endpoint connection associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsGetOptions) (PrivateEndpointConnectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsGetResponse, error) { + result := PrivateEndpointConnectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateEndpointConnectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Gets the private endpoint connections associated with the Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsListOptions) (PrivateEndpointConnectionsListResponse, error) { + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateEndpointConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsListResponse, error) { + result := PrivateEndpointConnectionsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateEndpointConnectionsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privatelinkresources_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privatelinkresources_client.go new file mode 100644 index 000000000000..0f90dc208383 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_privatelinkresources_client.go @@ -0,0 +1,100 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +func NewPrivateLinkResourcesClient(con *arm.Connection, subscriptionID string) *PrivateLinkResourcesClient { + return &PrivateLinkResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// List - Gets the private link resources that need to be created for a Cognitive Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesListOptions) (PrivateLinkResourcesListResponse, error) { + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateLinkResourcesListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateLinkResourcesListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateLinkResourcesListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CognitiveServices/accounts/{accountName}/privateLinkResources" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateLinkResourcesClient) listHandleResponse(resp *http.Response) (PrivateLinkResourcesListResponse, error) { + result := PrivateLinkResourcesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinkResourcesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateLinkResourcesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_resourceskus_client.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_resourceskus_client.go new file mode 100644 index 000000000000..49f428a17a10 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_resourceskus_client.go @@ -0,0 +1,89 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ResourceSKUsClient contains the methods for the ResourceSKUs group. +// Don't use this type directly, use NewResourceSKUsClient() instead. +type ResourceSKUsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewResourceSKUsClient creates a new instance of ResourceSKUsClient with the specified values. +func NewResourceSKUsClient(con *arm.Connection, subscriptionID string) *ResourceSKUsClient { + return &ResourceSKUsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// List - Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ResourceSKUsClient) List(options *ResourceSKUsListOptions) *ResourceSKUsListPager { + return &ResourceSKUsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp ResourceSKUsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ResourceSKUListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *ResourceSKUsClient) listCreateRequest(ctx context.Context, options *ResourceSKUsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.CognitiveServices/skus" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-30") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ResourceSKUsClient) listHandleResponse(resp *http.Response) (ResourceSKUsListResponse, error) { + result := ResourceSKUsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceSKUListResult); err != nil { + return ResourceSKUsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *ResourceSKUsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_response_types.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_response_types.go new file mode 100644 index 000000000000..aa0f6a05b1b8 --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_response_types.go @@ -0,0 +1,491 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// AccountsCreatePollerResponse contains the response from method Accounts.Create. +type AccountsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsCreateResponse, error) { + respType := AccountsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Account) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsCreatePollerResponse from the provided client and resume token. +func (l *AccountsCreatePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &AccountsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsCreateResponse contains the response from method Accounts.Create. +type AccountsCreateResponse struct { + AccountsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsCreateResult contains the result from method Accounts.Create. +type AccountsCreateResult struct { + Account +} + +// AccountsDeletePollerResponse contains the response from method Accounts.Delete. +type AccountsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsDeleteResponse, error) { + respType := AccountsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsDeletePollerResponse from the provided client and resume token. +func (l *AccountsDeletePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &AccountsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsDeleteResponse contains the response from method Accounts.Delete. +type AccountsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsGetResponse contains the response from method Accounts.Get. +type AccountsGetResponse struct { + AccountsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsGetResult contains the result from method Accounts.Get. +type AccountsGetResult struct { + Account +} + +// AccountsListByResourceGroupResponse contains the response from method Accounts.ListByResourceGroup. +type AccountsListByResourceGroupResponse struct { + AccountsListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListByResourceGroupResult contains the result from method Accounts.ListByResourceGroup. +type AccountsListByResourceGroupResult struct { + AccountListResult +} + +// AccountsListKeysResponse contains the response from method Accounts.ListKeys. +type AccountsListKeysResponse struct { + AccountsListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListKeysResult contains the result from method Accounts.ListKeys. +type AccountsListKeysResult struct { + APIKeys +} + +// AccountsListResponse contains the response from method Accounts.List. +type AccountsListResponse struct { + AccountsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListResult contains the result from method Accounts.List. +type AccountsListResult struct { + AccountListResult +} + +// AccountsListSKUsResponse contains the response from method Accounts.ListSKUs. +type AccountsListSKUsResponse struct { + AccountsListSKUsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListSKUsResult contains the result from method Accounts.ListSKUs. +type AccountsListSKUsResult struct { + AccountSKUListResult +} + +// AccountsListUsagesResponse contains the response from method Accounts.ListUsages. +type AccountsListUsagesResponse struct { + AccountsListUsagesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListUsagesResult contains the result from method Accounts.ListUsages. +type AccountsListUsagesResult struct { + UsageListResult +} + +// AccountsRegenerateKeyResponse contains the response from method Accounts.RegenerateKey. +type AccountsRegenerateKeyResponse struct { + AccountsRegenerateKeyResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsRegenerateKeyResult contains the result from method Accounts.RegenerateKey. +type AccountsRegenerateKeyResult struct { + APIKeys +} + +// AccountsUpdatePollerResponse contains the response from method Accounts.Update. +type AccountsUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsUpdateResponse, error) { + respType := AccountsUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Account) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsUpdatePollerResponse from the provided client and resume token. +func (l *AccountsUpdatePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &AccountsUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsUpdateResponse contains the response from method Accounts.Update. +type AccountsUpdateResponse struct { + AccountsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsUpdateResult contains the result from method Accounts.Update. +type AccountsUpdateResult struct { + Account +} + +// CognitiveServicesManagementClientCheckDomainAvailabilityResponse contains the response from method CognitiveServicesManagementClient.CheckDomainAvailability. +type CognitiveServicesManagementClientCheckDomainAvailabilityResponse struct { + CognitiveServicesManagementClientCheckDomainAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// CognitiveServicesManagementClientCheckDomainAvailabilityResult contains the result from method CognitiveServicesManagementClient.CheckDomainAvailability. +type CognitiveServicesManagementClientCheckDomainAvailabilityResult struct { + DomainAvailability +} + +// CognitiveServicesManagementClientCheckSKUAvailabilityResponse contains the response from method CognitiveServicesManagementClient.CheckSKUAvailability. +type CognitiveServicesManagementClientCheckSKUAvailabilityResponse struct { + CognitiveServicesManagementClientCheckSKUAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// CognitiveServicesManagementClientCheckSKUAvailabilityResult contains the result from method CognitiveServicesManagementClient.CheckSKUAvailability. +type CognitiveServicesManagementClientCheckSKUAvailabilityResult struct { + SKUAvailabilityListResult +} + +// DeletedAccountsGetResponse contains the response from method DeletedAccounts.Get. +type DeletedAccountsGetResponse struct { + DeletedAccountsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DeletedAccountsGetResult contains the result from method DeletedAccounts.Get. +type DeletedAccountsGetResult struct { + Account +} + +// DeletedAccountsListResponse contains the response from method DeletedAccounts.List. +type DeletedAccountsListResponse struct { + DeletedAccountsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DeletedAccountsListResult contains the result from method DeletedAccounts.List. +type DeletedAccountsListResult struct { + AccountListResult +} + +// DeletedAccountsPurgePollerResponse contains the response from method DeletedAccounts.Purge. +type DeletedAccountsPurgePollerResponse struct { + // Poller contains an initialized poller. + Poller *DeletedAccountsPurgePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l DeletedAccountsPurgePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (DeletedAccountsPurgeResponse, error) { + respType := DeletedAccountsPurgeResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a DeletedAccountsPurgePollerResponse from the provided client and resume token. +func (l *DeletedAccountsPurgePollerResponse) Resume(ctx context.Context, client *DeletedAccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("DeletedAccountsClient.Purge", token, client.pl, client.purgeHandleError) + if err != nil { + return err + } + poller := &DeletedAccountsPurgePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// DeletedAccountsPurgeResponse contains the response from method DeletedAccounts.Purge. +type DeletedAccountsPurgeResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// PrivateEndpointConnectionsCreateOrUpdatePollerResponse contains the response from method PrivateEndpointConnections.CreateOrUpdate. +type PrivateEndpointConnectionsCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *PrivateEndpointConnectionsCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l PrivateEndpointConnectionsCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (PrivateEndpointConnectionsCreateOrUpdateResponse, error) { + respType := PrivateEndpointConnectionsCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.PrivateEndpointConnection) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a PrivateEndpointConnectionsCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *PrivateEndpointConnectionsCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *PrivateEndpointConnectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("PrivateEndpointConnectionsClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &PrivateEndpointConnectionsCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// PrivateEndpointConnectionsCreateOrUpdateResponse contains the response from method PrivateEndpointConnections.CreateOrUpdate. +type PrivateEndpointConnectionsCreateOrUpdateResponse struct { + PrivateEndpointConnectionsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsCreateOrUpdateResult contains the result from method PrivateEndpointConnections.CreateOrUpdate. +type PrivateEndpointConnectionsCreateOrUpdateResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsDeletePollerResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *PrivateEndpointConnectionsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l PrivateEndpointConnectionsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (PrivateEndpointConnectionsDeleteResponse, error) { + respType := PrivateEndpointConnectionsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a PrivateEndpointConnectionsDeletePollerResponse from the provided client and resume token. +func (l *PrivateEndpointConnectionsDeletePollerResponse) Resume(ctx context.Context, client *PrivateEndpointConnectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("PrivateEndpointConnectionsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &PrivateEndpointConnectionsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// PrivateEndpointConnectionsDeleteResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResponse contains the response from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResponse struct { + PrivateEndpointConnectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResult contains the result from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsListResponse contains the response from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResponse struct { + PrivateEndpointConnectionsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsListResult contains the result from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResult struct { + PrivateEndpointConnectionListResult +} + +// PrivateLinkResourcesListResponse contains the response from method PrivateLinkResources.List. +type PrivateLinkResourcesListResponse struct { + PrivateLinkResourcesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesListResult contains the result from method PrivateLinkResources.List. +type PrivateLinkResourcesListResult struct { + PrivateLinkResourceListResult +} + +// ResourceSKUsListResponse contains the response from method ResourceSKUs.List. +type ResourceSKUsListResponse struct { + ResourceSKUsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ResourceSKUsListResult contains the result from method ResourceSKUs.List. +type ResourceSKUsListResult struct { + ResourceSKUListResult +} diff --git a/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_time_rfc3339.go b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..f25a0f5022ef --- /dev/null +++ b/sdk/resourcemanager/cognitiveservices/armcognitiveservices/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armcognitiveservices + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/CHANGELOG.md b/sdk/resourcemanager/databricks/armdatabricks/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/databricks/armdatabricks/LICENSE.txt b/sdk/resourcemanager/databricks/armdatabricks/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/databricks/armdatabricks/README.md b/sdk/resourcemanager/databricks/armdatabricks/README.md new file mode 100644 index 000000000000..7d53c9de891e --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/README.md @@ -0,0 +1,76 @@ +# Azure Databricks Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databricks/armdatabricks)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databricks/armdatabricks) + +The `armdatabricks` module provides operations for working with Azure Databricks. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/databricks/armdatabricks) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Databricks module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databricks/armdatabricks +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Databricks. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Databricks + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Databricks modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armdatabricks.NewWorkspacesClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Databricks` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/databricks/armdatabricks/autorest.md b/sdk/resourcemanager/databricks/armdatabricks/autorest.md new file mode 100644 index 000000000000..0dc9df444ac5 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/databricks/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/databricks/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/databricks/armdatabricks/build.go b/sdk/resourcemanager/databricks/armdatabricks/build.go new file mode 100644 index 000000000000..b98147c2087c --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/databricks/armdatabricks + +package armdatabricks diff --git a/sdk/resourcemanager/databricks/armdatabricks/ci.yml b/sdk/resourcemanager/databricks/armdatabricks/ci.yml new file mode 100644 index 000000000000..e6b4b3961392 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/databricks/armdatabricks/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/databricks/armdatabricks/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/databricks/armdatabricks' diff --git a/sdk/resourcemanager/databricks/armdatabricks/go.mod b/sdk/resourcemanager/databricks/armdatabricks/go.mod new file mode 100644 index 000000000000..416ec90638d6 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/databricks/armdatabricks + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/databricks/armdatabricks/go.sum b/sdk/resourcemanager/databricks/armdatabricks/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/databricks/armdatabricks/go_mod_tidy_hack.go b/sdk/resourcemanager/databricks/armdatabricks/go_mod_tidy_hack.go new file mode 100644 index 000000000000..fd1479661fa0 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armdatabricks + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_constants.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_constants.go new file mode 100644 index 000000000000..3b84791f428b --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_constants.go @@ -0,0 +1,287 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +const ( + module = "armdatabricks" + version = "v0.1.1" +) + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ToPtr returns a *CreatedByType pointing to the current value. +func (c CreatedByType) ToPtr() *CreatedByType { + return &c +} + +// CustomParameterType - Provisioning status of the workspace. +type CustomParameterType string + +const ( + CustomParameterTypeBool CustomParameterType = "Bool" + CustomParameterTypeObject CustomParameterType = "Object" + CustomParameterTypeString CustomParameterType = "String" +) + +// PossibleCustomParameterTypeValues returns the possible values for the CustomParameterType const type. +func PossibleCustomParameterTypeValues() []CustomParameterType { + return []CustomParameterType{ + CustomParameterTypeBool, + CustomParameterTypeObject, + CustomParameterTypeString, + } +} + +// ToPtr returns a *CustomParameterType pointing to the current value. +func (c CustomParameterType) ToPtr() *CustomParameterType { + return &c +} + +// EncryptionKeySource - The encryption keySource (provider). Possible values (case-insensitive): Microsoft.Keyvault +type EncryptionKeySource string + +const ( + EncryptionKeySourceMicrosoftKeyvault EncryptionKeySource = "Microsoft.Keyvault" +) + +// PossibleEncryptionKeySourceValues returns the possible values for the EncryptionKeySource const type. +func PossibleEncryptionKeySourceValues() []EncryptionKeySource { + return []EncryptionKeySource{ + EncryptionKeySourceMicrosoftKeyvault, + } +} + +// ToPtr returns a *EncryptionKeySource pointing to the current value. +func (c EncryptionKeySource) ToPtr() *EncryptionKeySource { + return &c +} + +// KeySource - The encryption keySource (provider). Possible values (case-insensitive): Default, Microsoft.Keyvault +type KeySource string + +const ( + KeySourceDefault KeySource = "Default" + KeySourceMicrosoftKeyvault KeySource = "Microsoft.Keyvault" +) + +// PossibleKeySourceValues returns the possible values for the KeySource const type. +func PossibleKeySourceValues() []KeySource { + return []KeySource{ + KeySourceDefault, + KeySourceMicrosoftKeyvault, + } +} + +// ToPtr returns a *KeySource pointing to the current value. +func (c KeySource) ToPtr() *KeySource { + return &c +} + +// PeeringProvisioningState - The current provisioning state. +type PeeringProvisioningState string + +const ( + PeeringProvisioningStateDeleting PeeringProvisioningState = "Deleting" + PeeringProvisioningStateFailed PeeringProvisioningState = "Failed" + PeeringProvisioningStateSucceeded PeeringProvisioningState = "Succeeded" + PeeringProvisioningStateUpdating PeeringProvisioningState = "Updating" +) + +// PossiblePeeringProvisioningStateValues returns the possible values for the PeeringProvisioningState const type. +func PossiblePeeringProvisioningStateValues() []PeeringProvisioningState { + return []PeeringProvisioningState{ + PeeringProvisioningStateDeleting, + PeeringProvisioningStateFailed, + PeeringProvisioningStateSucceeded, + PeeringProvisioningStateUpdating, + } +} + +// ToPtr returns a *PeeringProvisioningState pointing to the current value. +func (c PeeringProvisioningState) ToPtr() *PeeringProvisioningState { + return &c +} + +// PeeringState - The status of the virtual network peering. +type PeeringState string + +const ( + PeeringStateConnected PeeringState = "Connected" + PeeringStateDisconnected PeeringState = "Disconnected" + PeeringStateInitiated PeeringState = "Initiated" +) + +// PossiblePeeringStateValues returns the possible values for the PeeringState const type. +func PossiblePeeringStateValues() []PeeringState { + return []PeeringState{ + PeeringStateConnected, + PeeringStateDisconnected, + PeeringStateInitiated, + } +} + +// ToPtr returns a *PeeringState pointing to the current value. +func (c PeeringState) ToPtr() *PeeringState { + return &c +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" + PrivateEndpointConnectionProvisioningStateUpdating PrivateEndpointConnectionProvisioningState = "Updating" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + PrivateEndpointConnectionProvisioningStateUpdating, + } +} + +// ToPtr returns a *PrivateEndpointConnectionProvisioningState pointing to the current value. +func (c PrivateEndpointConnectionProvisioningState) ToPtr() *PrivateEndpointConnectionProvisioningState { + return &c +} + +// PrivateLinkServiceConnectionStatus - The status of a private endpoint connection +type PrivateLinkServiceConnectionStatus string + +const ( + PrivateLinkServiceConnectionStatusApproved PrivateLinkServiceConnectionStatus = "Approved" + PrivateLinkServiceConnectionStatusDisconnected PrivateLinkServiceConnectionStatus = "Disconnected" + PrivateLinkServiceConnectionStatusPending PrivateLinkServiceConnectionStatus = "Pending" + PrivateLinkServiceConnectionStatusRejected PrivateLinkServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateLinkServiceConnectionStatusValues returns the possible values for the PrivateLinkServiceConnectionStatus const type. +func PossiblePrivateLinkServiceConnectionStatusValues() []PrivateLinkServiceConnectionStatus { + return []PrivateLinkServiceConnectionStatus{ + PrivateLinkServiceConnectionStatusApproved, + PrivateLinkServiceConnectionStatusDisconnected, + PrivateLinkServiceConnectionStatusPending, + PrivateLinkServiceConnectionStatusRejected, + } +} + +// ToPtr returns a *PrivateLinkServiceConnectionStatus pointing to the current value. +func (c PrivateLinkServiceConnectionStatus) ToPtr() *PrivateLinkServiceConnectionStatus { + return &c +} + +// ProvisioningState - Provisioning status of the workspace. +type ProvisioningState string + +const ( + ProvisioningStateAccepted ProvisioningState = "Accepted" + ProvisioningStateCanceled ProvisioningState = "Canceled" + ProvisioningStateCreated ProvisioningState = "Created" + ProvisioningStateCreating ProvisioningState = "Creating" + ProvisioningStateDeleted ProvisioningState = "Deleted" + ProvisioningStateDeleting ProvisioningState = "Deleting" + ProvisioningStateFailed ProvisioningState = "Failed" + ProvisioningStateReady ProvisioningState = "Ready" + ProvisioningStateRunning ProvisioningState = "Running" + ProvisioningStateSucceeded ProvisioningState = "Succeeded" + ProvisioningStateUpdating ProvisioningState = "Updating" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateAccepted, + ProvisioningStateCanceled, + ProvisioningStateCreated, + ProvisioningStateCreating, + ProvisioningStateDeleted, + ProvisioningStateDeleting, + ProvisioningStateFailed, + ProvisioningStateReady, + ProvisioningStateRunning, + ProvisioningStateSucceeded, + ProvisioningStateUpdating, + } +} + +// ToPtr returns a *ProvisioningState pointing to the current value. +func (c ProvisioningState) ToPtr() *ProvisioningState { + return &c +} + +// PublicNetworkAccess - The network access type for accessing workspace. Set value to disabled to access workspace only via private link. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// ToPtr returns a *PublicNetworkAccess pointing to the current value. +func (c PublicNetworkAccess) ToPtr() *PublicNetworkAccess { + return &c +} + +// RequiredNsgRules - Gets or sets a value indicating whether data plane (clusters) to control plane communication happen over private endpoint. Supported +// values are 'AllRules' and 'NoAzureDatabricksRules'. +// 'NoAzureServiceRules' value is for internal use only. +type RequiredNsgRules string + +const ( + RequiredNsgRulesAllRules RequiredNsgRules = "AllRules" + RequiredNsgRulesNoAzureDatabricksRules RequiredNsgRules = "NoAzureDatabricksRules" + RequiredNsgRulesNoAzureServiceRules RequiredNsgRules = "NoAzureServiceRules" +) + +// PossibleRequiredNsgRulesValues returns the possible values for the RequiredNsgRules const type. +func PossibleRequiredNsgRulesValues() []RequiredNsgRules { + return []RequiredNsgRules{ + RequiredNsgRulesAllRules, + RequiredNsgRulesNoAzureDatabricksRules, + RequiredNsgRulesNoAzureServiceRules, + } +} + +// ToPtr returns a *RequiredNsgRules pointing to the current value. +func (c RequiredNsgRules) ToPtr() *RequiredNsgRules { + return &c +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_models.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_models.go new file mode 100644 index 000000000000..bc05e96058d6 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_models.go @@ -0,0 +1,958 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AddressSpace contains an array of IP address ranges that can be used by subnets of the virtual network. +type AddressSpace struct { + // A list of address blocks reserved for this virtual network in CIDR notation. + AddressPrefixes []*string `json:"addressPrefixes,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AddressSpace. +func (a AddressSpace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "addressPrefixes", a.AddressPrefixes) + return json.Marshal(objectMap) +} + +// CreatedBy - Provides details of the entity that created/updated the workspace. +type CreatedBy struct { + // READ-ONLY; The application ID of the application that initiated the creation of the workspace. For example, Azure Portal. + ApplicationID *string `json:"applicationId,omitempty" azure:"ro"` + + // READ-ONLY; The Object ID that created the workspace. + Oid *string `json:"oid,omitempty" azure:"ro"` + + // READ-ONLY; The Personal Object ID corresponding to the object ID above + Puid *string `json:"puid,omitempty" azure:"ro"` +} + +// Encryption - The object that contains details of encryption used on the workspace. +type Encryption struct { + // The name of KeyVault key. + KeyName *string `json:"KeyName,omitempty"` + + // The encryption keySource (provider). Possible values (case-insensitive): Default, Microsoft.Keyvault + KeySource *KeySource `json:"keySource,omitempty"` + + // The Uri of KeyVault. + KeyVaultURI *string `json:"keyvaulturi,omitempty"` + + // The version of KeyVault key. + KeyVersion *string `json:"keyversion,omitempty"` +} + +// EncryptionEntitiesDefinition - Encryption entities for databricks workspace resource. +type EncryptionEntitiesDefinition struct { + // Encryption properties for the databricks managed services. + ManagedServices *EncryptionV2 `json:"managedServices,omitempty"` +} + +// EncryptionV2 - The object that contains details of encryption used on the workspace. +type EncryptionV2 struct { + // REQUIRED; The encryption keySource (provider). Possible values (case-insensitive): Microsoft.Keyvault + KeySource *EncryptionKeySource `json:"keySource,omitempty"` + + // Key Vault input properties for encryption. + KeyVaultProperties *EncryptionV2KeyVaultProperties `json:"keyVaultProperties,omitempty"` +} + +// EncryptionV2KeyVaultProperties - Key Vault input properties for encryption. +type EncryptionV2KeyVaultProperties struct { + // REQUIRED; The name of KeyVault key. + KeyName *string `json:"keyName,omitempty"` + + // REQUIRED; The Uri of KeyVault. + KeyVaultURI *string `json:"keyVaultUri,omitempty"` + + // REQUIRED; The version of KeyVault key. + KeyVersion *string `json:"keyVersion,omitempty"` +} + +// EndpointDependency - A domain name or IP address the Workspace is reaching at. +type EndpointDependency struct { + // The domain name of the dependency. + DomainName *string `json:"domainName,omitempty"` + + // The Ports used when connecting to domainName. + EndpointDetails []*EndpointDetail `json:"endpointDetails,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EndpointDependency. +func (e EndpointDependency) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "domainName", e.DomainName) + populate(objectMap, "endpointDetails", e.EndpointDetails) + return json.Marshal(objectMap) +} + +// EndpointDetail - Connect information from the Workspace to a single endpoint. +type EndpointDetail struct { + // An IP Address that Domain Name currently resolves to. + IPAddress *string `json:"ipAddress,omitempty"` + + // Whether it is possible to create a connection from the Workspace to this IpAddress at this Port. + IsAccessible *bool `json:"isAccessible,omitempty"` + + // The time in milliseconds it takes for the connection to be created from the Workspace to this IpAddress at this Port. + Latency *float64 `json:"latency,omitempty"` + + // The port an endpoint is connected to. + Port *int32 `json:"port,omitempty"` +} + +// ErrorDetail - Error details. +type ErrorDetail struct { + // REQUIRED; The error's code. + Code *string `json:"code,omitempty"` + + // REQUIRED; A human readable error message. + Message *string `json:"message,omitempty"` + + // Indicates which property in the request is responsible for the error. + Target *string `json:"target,omitempty"` +} + +// ErrorInfo - The code and message for an error. +type ErrorInfo struct { + // REQUIRED; A machine readable error code. + Code *string `json:"code,omitempty"` + + // REQUIRED; A human readable error message. + Message *string `json:"message,omitempty"` + + // error details. + Details []*ErrorDetail `json:"details,omitempty"` + + // Inner error details if they exist. + Innererror *string `json:"innererror,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorInfo. +func (e ErrorInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "innererror", e.Innererror) + populate(objectMap, "message", e.Message) + return json.Marshal(objectMap) +} + +// ErrorResponse - Contains details when the response code indicates an error. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // REQUIRED; The error details. + InnerError *ErrorInfo `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// GroupIDInformation - The group information for creating a private endpoint on a workspace +type GroupIDInformation struct { + Resource + // REQUIRED; The group id properties. + Properties *GroupIDInformationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type GroupIDInformation. +func (g GroupIDInformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + g.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", g.Properties) + return json.Marshal(objectMap) +} + +// GroupIDInformationProperties - The properties for a group information object +type GroupIDInformationProperties struct { + // The group id + GroupID *string `json:"groupId,omitempty"` + + // The required members for a specific group id + RequiredMembers []*string `json:"requiredMembers,omitempty"` + + // The required DNS zones for a specific group id + RequiredZoneNames []*string `json:"requiredZoneNames,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type GroupIDInformationProperties. +func (g GroupIDInformationProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupId", g.GroupID) + populate(objectMap, "requiredMembers", g.RequiredMembers) + populate(objectMap, "requiredZoneNames", g.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// ManagedIdentityConfiguration - The Managed Identity details for storage account. +type ManagedIdentityConfiguration struct { + // READ-ONLY; The objectId of the Managed Identity that is linked to the Managed Storage account. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` + + // READ-ONLY; The tenant Id where the Managed Identity is created. + TenantID *string `json:"tenantId,omitempty" azure:"ro"` + + // READ-ONLY; The type of Identity created. It can be either SystemAssigned or UserAssigned. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// Operation - REST API operation +type Operation struct { + // The object that represents the operation. + Display *OperationDisplay `json:"display,omitempty"` + + // Operation name: {provider}/{resource}/{operation} + Name *string `json:"name,omitempty"` +} + +// OperationDisplay - The object that represents the operation. +type OperationDisplay struct { + // Operation type: Read, write, delete, etc. + Operation *string `json:"operation,omitempty"` + + // Service provider: Microsoft.ResourceProvider + Provider *string `json:"provider,omitempty"` + + // Resource on which the operation is performed. + Resource *string `json:"resource,omitempty"` +} + +// OperationListResult - Result of the request to list Resource Provider operations. It contains a list of operations and a URL link to get the next set +// of results. +type OperationListResult struct { + // URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty"` + + // List of Resource Provider operations supported by the Resource Provider resource provider. + Value []*Operation `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// OutboundEnvironmentEndpoint - Egress endpoints which Workspace connects to for common purposes. +type OutboundEnvironmentEndpoint struct { + // The category of endpoints accessed by the Workspace, e.g. azure-storage, azure-mysql, etc. + Category *string `json:"category,omitempty"` + + // The endpoints that Workspace connect to + Endpoints []*EndpointDependency `json:"endpoints,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OutboundEnvironmentEndpoint. +func (o OutboundEnvironmentEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "category", o.Category) + populate(objectMap, "endpoints", o.Endpoints) + return json.Marshal(objectMap) +} + +// OutboundNetworkDependenciesEndpointsListOptions contains the optional parameters for the OutboundNetworkDependenciesEndpoints.List method. +type OutboundNetworkDependenciesEndpointsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpoint - The private endpoint property of a private endpoint connection +type PrivateEndpoint struct { + // READ-ONLY; The resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` +} + +// PrivateEndpointConnection - The private endpoint connection of a workspace +type PrivateEndpointConnection struct { + // REQUIRED; The private endpoint connection properties. + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` + + // READ-ONLY; The resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// PrivateEndpointConnectionProperties - The properties of a private endpoint connection +type PrivateEndpointConnectionProperties struct { + // REQUIRED; Private endpoint connection state + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + + // Private endpoint + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + + // READ-ONLY; Provisioning state of the private endpoint connection. + ProvisioningState *PrivateEndpointConnectionProvisioningState `json:"provisioningState,omitempty" azure:"ro"` +} + +// PrivateEndpointConnectionsBeginCreateOptions contains the optional parameters for the PrivateEndpointConnections.BeginCreate method. +type PrivateEndpointConnectionsBeginCreateOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsBeginDeleteOptions contains the optional parameters for the PrivateEndpointConnections.BeginDelete method. +type PrivateEndpointConnectionsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsGetOptions contains the optional parameters for the PrivateEndpointConnections.Get method. +type PrivateEndpointConnectionsGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsList - List of private link connections. +type PrivateEndpointConnectionsList struct { + // The URL to get the next set of endpoint connections. + NextLink *string `json:"nextLink,omitempty"` + + // The list of returned private endpoint connection. + Value []*PrivateEndpointConnection `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionsList. +func (p PrivateEndpointConnectionsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionsListOptions contains the optional parameters for the PrivateEndpointConnections.List method. +type PrivateEndpointConnectionsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesGetOptions contains the optional parameters for the PrivateLinkResources.Get method. +type PrivateLinkResourcesGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesList - The available private link resources for a workspace +type PrivateLinkResourcesList struct { + // The URL to get the next set of private link resources. + NextLink *string `json:"nextLink,omitempty"` + + // The list of available private link resources for a workspace + Value []*GroupIDInformation `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourcesList. +func (p PrivateLinkResourcesList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateLinkResourcesListOptions contains the optional parameters for the PrivateLinkResources.List method. +type PrivateLinkResourcesListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServiceConnectionState - The current state of a private endpoint connection +type PrivateLinkServiceConnectionState struct { + // REQUIRED; The status of a private endpoint connection + Status *PrivateLinkServiceConnectionStatus `json:"status,omitempty"` + + // Actions required for a private endpoint connection + ActionRequired *string `json:"actionRequired,omitempty"` + + // The description for the current state of a private endpoint connection + Description *string `json:"description,omitempty"` +} + +// Resource - The core properties of ARM resources +type Resource struct { + // READ-ONLY; Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +// SKU for the resource. +type SKU struct { + // REQUIRED; The SKU name. + Name *string `json:"name,omitempty"` + + // The SKU tier. + Tier *string `json:"tier,omitempty"` +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // The identity that created the resource. + CreatedBy *string `json:"createdBy,omitempty"` + + // The type of identity that created the resource. + CreatedByType *CreatedByType `json:"createdByType,omitempty"` + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time `json:"lastModifiedAt,omitempty"` + + // The identity that last modified the resource. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType `json:"lastModifiedByType,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(s.CreatedAt)) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populate(objectMap, "lastModifiedAt", (*timeRFC3339)(s.LastModifiedAt)) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// TrackedResource - The resource model definition for a ARM tracked top level resource +type TrackedResource struct { + Resource + // REQUIRED; The geo-location where the resource lives + Location *string `json:"location,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (t TrackedResource) marshalInternal(objectMap map[string]interface{}) { + t.Resource.marshalInternal(objectMap) + populate(objectMap, "location", t.Location) + populate(objectMap, "tags", t.Tags) +} + +// VNetPeeringBeginCreateOrUpdateOptions contains the optional parameters for the VNetPeering.BeginCreateOrUpdate method. +type VNetPeeringBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// VNetPeeringBeginDeleteOptions contains the optional parameters for the VNetPeering.BeginDelete method. +type VNetPeeringBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// VNetPeeringGetOptions contains the optional parameters for the VNetPeering.Get method. +type VNetPeeringGetOptions struct { + // placeholder for future optional parameters +} + +// VNetPeeringListByWorkspaceOptions contains the optional parameters for the VNetPeering.ListByWorkspace method. +type VNetPeeringListByWorkspaceOptions struct { + // placeholder for future optional parameters +} + +// VirtualNetworkPeering - Peerings in a VirtualNetwork resource +type VirtualNetworkPeering struct { + // REQUIRED; List of properties for vNet Peering + Properties *VirtualNetworkPeeringPropertiesFormat `json:"properties,omitempty"` + + // READ-ONLY; Resource ID. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Name of the virtual network peering resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; type of the virtual network peering resource + Type *string `json:"type,omitempty" azure:"ro"` +} + +// VirtualNetworkPeeringList - Gets all virtual network peerings under a workspace. +type VirtualNetworkPeeringList struct { + // URL to get the next set of virtual network peering list results if there are any. + NextLink *string `json:"nextLink,omitempty"` + + // List of virtual network peerings on workspace. + Value []*VirtualNetworkPeering `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkPeeringList. +func (v VirtualNetworkPeeringList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", v.NextLink) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// VirtualNetworkPeeringPropertiesFormat - Properties of the virtual network peering. +type VirtualNetworkPeeringPropertiesFormat struct { + // REQUIRED; The remote virtual network should be in the same region. See here to learn more (https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/vnet-peering). + RemoteVirtualNetwork *VirtualNetworkPeeringPropertiesFormatRemoteVirtualNetwork `json:"remoteVirtualNetwork,omitempty"` + + // Whether the forwarded traffic from the VMs in the local virtual network will be allowed/disallowed in remote virtual network. + AllowForwardedTraffic *bool `json:"allowForwardedTraffic,omitempty"` + + // If gateway links can be used in remote virtual networking to link to this virtual network. + AllowGatewayTransit *bool `json:"allowGatewayTransit,omitempty"` + + // Whether the VMs in the local virtual network space would be able to access the VMs in remote virtual network space. + AllowVirtualNetworkAccess *bool `json:"allowVirtualNetworkAccess,omitempty"` + + // The reference to the databricks virtual network address space. + DatabricksAddressSpace *AddressSpace `json:"databricksAddressSpace,omitempty"` + + // The remote virtual network should be in the same region. See here to learn more (https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/vnet-peering). + DatabricksVirtualNetwork *VirtualNetworkPeeringPropertiesFormatDatabricksVirtualNetwork `json:"databricksVirtualNetwork,omitempty"` + + // The reference to the remote virtual network address space. + RemoteAddressSpace *AddressSpace `json:"remoteAddressSpace,omitempty"` + + // If remote gateways can be used on this virtual network. If the flag is set to true, and allowGatewayTransit on remote peering is also true, virtual network + // will use gateways of remote virtual network + // for transit. Only one peering can have this flag set to true. This flag cannot be set if virtual network already has a gateway. + UseRemoteGateways *bool `json:"useRemoteGateways,omitempty"` + + // READ-ONLY; The status of the virtual network peering. + PeeringState *PeeringState `json:"peeringState,omitempty" azure:"ro"` + + // READ-ONLY; The provisioning state of the virtual network peering resource. + ProvisioningState *PeeringProvisioningState `json:"provisioningState,omitempty" azure:"ro"` +} + +// VirtualNetworkPeeringPropertiesFormatDatabricksVirtualNetwork - The remote virtual network should be in the same region. See here to learn more (https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/vnet-peering). +type VirtualNetworkPeeringPropertiesFormatDatabricksVirtualNetwork struct { + // The Id of the databricks virtual network. + ID *string `json:"id,omitempty"` +} + +// VirtualNetworkPeeringPropertiesFormatRemoteVirtualNetwork - The remote virtual network should be in the same region. See here to learn more (https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/vnet-peering). +type VirtualNetworkPeeringPropertiesFormatRemoteVirtualNetwork struct { + // The Id of the remote virtual network. + ID *string `json:"id,omitempty"` +} + +// Workspace - Information about workspace. +type Workspace struct { + TrackedResource + // REQUIRED; The workspace properties. + Properties *WorkspaceProperties `json:"properties,omitempty"` + + // The SKU of the resource. + SKU *SKU `json:"sku,omitempty"` + + // READ-ONLY; The system metadata relating to this resource + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Workspace. +func (w Workspace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + w.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "properties", w.Properties) + populate(objectMap, "sku", w.SKU) + populate(objectMap, "systemData", w.SystemData) + return json.Marshal(objectMap) +} + +// WorkspaceCustomBooleanParameter - The value which should be used for this field. +type WorkspaceCustomBooleanParameter struct { + // REQUIRED; The value which should be used for this field. + Value *bool `json:"value,omitempty"` + + // READ-ONLY; The type of variable that this is + Type *CustomParameterType `json:"type,omitempty" azure:"ro"` +} + +// WorkspaceCustomObjectParameter - The value which should be used for this field. +type WorkspaceCustomObjectParameter struct { + // REQUIRED; The value which should be used for this field. + Value map[string]interface{} `json:"value,omitempty"` + + // READ-ONLY; The type of variable that this is + Type *CustomParameterType `json:"type,omitempty" azure:"ro"` +} + +// WorkspaceCustomParameters - Custom Parameters used for Cluster Creation. +type WorkspaceCustomParameters struct { + // The ID of a Azure Machine Learning workspace to link with Databricks workspace + AmlWorkspaceID *WorkspaceCustomStringParameter `json:"amlWorkspaceId,omitempty"` + + // The name of the Private Subnet within the Virtual Network + CustomPrivateSubnetName *WorkspaceCustomStringParameter `json:"customPrivateSubnetName,omitempty"` + + // The name of a Public Subnet within the Virtual Network + CustomPublicSubnetName *WorkspaceCustomStringParameter `json:"customPublicSubnetName,omitempty"` + + // The ID of a Virtual Network where this Databricks Cluster should be created + CustomVirtualNetworkID *WorkspaceCustomStringParameter `json:"customVirtualNetworkId,omitempty"` + + // Should the Public IP be Disabled? + EnableNoPublicIP *WorkspaceCustomBooleanParameter `json:"enableNoPublicIp,omitempty"` + + // Contains the encryption details for Customer-Managed Key (CMK) enabled workspace. + Encryption *WorkspaceEncryptionParameter `json:"encryption,omitempty"` + + // Name of the outbound Load Balancer Backend Pool for Secure Cluster Connectivity (No Public IP). + LoadBalancerBackendPoolName *WorkspaceCustomStringParameter `json:"loadBalancerBackendPoolName,omitempty"` + + // Resource URI of Outbound Load balancer for Secure Cluster Connectivity (No Public IP) workspace. + LoadBalancerID *WorkspaceCustomStringParameter `json:"loadBalancerId,omitempty"` + + // Name of the NAT gateway for Secure Cluster Connectivity (No Public IP) workspace subnets. + NatGatewayName *WorkspaceCustomStringParameter `json:"natGatewayName,omitempty"` + + // Prepare the workspace for encryption. Enables the Managed Identity for managed storage account. + PrepareEncryption *WorkspaceCustomBooleanParameter `json:"prepareEncryption,omitempty"` + + // Name of the Public IP for No Public IP workspace with managed vNet. + PublicIPName *WorkspaceCustomStringParameter `json:"publicIpName,omitempty"` + + // A boolean indicating whether or not the DBFS root file system will be enabled with secondary layer of encryption with platform managed keys for data + // at rest. + RequireInfrastructureEncryption *WorkspaceCustomBooleanParameter `json:"requireInfrastructureEncryption,omitempty"` + + // Default DBFS storage account name. + StorageAccountName *WorkspaceCustomStringParameter `json:"storageAccountName,omitempty"` + + // Storage account SKU name, ex: StandardGRS, StandardLRS. Refer https://aka.ms/storageskus for valid inputs. + StorageAccountSKUName *WorkspaceCustomStringParameter `json:"storageAccountSkuName,omitempty"` + + // Address prefix for Managed virtual network. Default value for this input is 10.139. + VnetAddressPrefix *WorkspaceCustomStringParameter `json:"vnetAddressPrefix,omitempty"` + + // READ-ONLY; Tags applied to resources under Managed resource group. These can be updated by updating tags at workspace level. + ResourceTags *WorkspaceCustomObjectParameter `json:"resourceTags,omitempty" azure:"ro"` +} + +// WorkspaceCustomStringParameter - The Value. +type WorkspaceCustomStringParameter struct { + // REQUIRED; The value which should be used for this field. + Value *string `json:"value,omitempty"` + + // READ-ONLY; The type of variable that this is + Type *CustomParameterType `json:"type,omitempty" azure:"ro"` +} + +// WorkspaceEncryptionParameter - The object that contains details of encryption used on the workspace. +type WorkspaceEncryptionParameter struct { + // The value which should be used for this field. + Value *Encryption `json:"value,omitempty"` + + // READ-ONLY; The type of variable that this is + Type *CustomParameterType `json:"type,omitempty" azure:"ro"` +} + +// WorkspaceListResult - List of workspaces. +type WorkspaceListResult struct { + // The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty"` + + // The array of workspaces. + Value []*Workspace `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceListResult. +func (w WorkspaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +// WorkspaceProperties - The workspace properties. +type WorkspaceProperties struct { + // REQUIRED; The managed resource group Id. + ManagedResourceGroupID *string `json:"managedResourceGroupId,omitempty"` + + // The workspace provider authorizations. + Authorizations []*WorkspaceProviderAuthorization `json:"authorizations,omitempty"` + + // Indicates the Object ID, PUID and Application ID of entity that created the workspace. + CreatedBy *CreatedBy `json:"createdBy,omitempty"` + + // Encryption properties for databricks workspace + Encryption *WorkspacePropertiesEncryption `json:"encryption,omitempty"` + + // The workspace's custom parameters. + Parameters *WorkspaceCustomParameters `json:"parameters,omitempty"` + + // The network access type for accessing workspace. Set value to disabled to access workspace only via private link. + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + + // Gets or sets a value indicating whether data plane (clusters) to control plane communication happen over private endpoint. Supported values are 'AllRules' + // and 'NoAzureDatabricksRules'. + // 'NoAzureServiceRules' value is for internal use only. + RequiredNsgRules *RequiredNsgRules `json:"requiredNsgRules,omitempty"` + + // The details of Managed Identity of Storage Account + StorageAccountIdentity *ManagedIdentityConfiguration `json:"storageAccountIdentity,omitempty"` + + // The blob URI where the UI definition file is located. + UIDefinitionURI *string `json:"uiDefinitionUri,omitempty"` + + // Indicates the Object ID, PUID and Application ID of entity that last updated the workspace. + UpdatedBy *CreatedBy `json:"updatedBy,omitempty"` + + // READ-ONLY; Specifies the date and time when the workspace is created. + CreatedDateTime *time.Time `json:"createdDateTime,omitempty" azure:"ro"` + + // READ-ONLY; Private endpoint connections created on the workspace + PrivateEndpointConnections []*PrivateEndpointConnection `json:"privateEndpointConnections,omitempty" azure:"ro"` + + // READ-ONLY; The workspace provisioning state. + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The unique identifier of the databricks workspace in databricks control plane. + WorkspaceID *string `json:"workspaceId,omitempty" azure:"ro"` + + // READ-ONLY; The workspace URL which is of the format 'adb-{workspaceId}.{random}.azuredatabricks.net' + WorkspaceURL *string `json:"workspaceUrl,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceProperties. +func (w WorkspaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "authorizations", w.Authorizations) + populate(objectMap, "createdBy", w.CreatedBy) + populate(objectMap, "createdDateTime", (*timeRFC3339)(w.CreatedDateTime)) + populate(objectMap, "encryption", w.Encryption) + populate(objectMap, "managedResourceGroupId", w.ManagedResourceGroupID) + populate(objectMap, "parameters", w.Parameters) + populate(objectMap, "privateEndpointConnections", w.PrivateEndpointConnections) + populate(objectMap, "provisioningState", w.ProvisioningState) + populate(objectMap, "publicNetworkAccess", w.PublicNetworkAccess) + populate(objectMap, "requiredNsgRules", w.RequiredNsgRules) + populate(objectMap, "storageAccountIdentity", w.StorageAccountIdentity) + populate(objectMap, "uiDefinitionUri", w.UIDefinitionURI) + populate(objectMap, "updatedBy", w.UpdatedBy) + populate(objectMap, "workspaceId", w.WorkspaceID) + populate(objectMap, "workspaceUrl", w.WorkspaceURL) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WorkspaceProperties. +func (w *WorkspaceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "authorizations": + err = unpopulate(val, &w.Authorizations) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, &w.CreatedBy) + delete(rawMsg, key) + case "createdDateTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + w.CreatedDateTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "encryption": + err = unpopulate(val, &w.Encryption) + delete(rawMsg, key) + case "managedResourceGroupId": + err = unpopulate(val, &w.ManagedResourceGroupID) + delete(rawMsg, key) + case "parameters": + err = unpopulate(val, &w.Parameters) + delete(rawMsg, key) + case "privateEndpointConnections": + err = unpopulate(val, &w.PrivateEndpointConnections) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &w.ProvisioningState) + delete(rawMsg, key) + case "publicNetworkAccess": + err = unpopulate(val, &w.PublicNetworkAccess) + delete(rawMsg, key) + case "requiredNsgRules": + err = unpopulate(val, &w.RequiredNsgRules) + delete(rawMsg, key) + case "storageAccountIdentity": + err = unpopulate(val, &w.StorageAccountIdentity) + delete(rawMsg, key) + case "uiDefinitionUri": + err = unpopulate(val, &w.UIDefinitionURI) + delete(rawMsg, key) + case "updatedBy": + err = unpopulate(val, &w.UpdatedBy) + delete(rawMsg, key) + case "workspaceId": + err = unpopulate(val, &w.WorkspaceID) + delete(rawMsg, key) + case "workspaceUrl": + err = unpopulate(val, &w.WorkspaceURL) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// WorkspacePropertiesEncryption - Encryption properties for databricks workspace +type WorkspacePropertiesEncryption struct { + // REQUIRED; Encryption entities definition for the workspace. + Entities *EncryptionEntitiesDefinition `json:"entities,omitempty"` +} + +// WorkspaceProviderAuthorization - The workspace provider authorization. +type WorkspaceProviderAuthorization struct { + // REQUIRED; The provider's principal identifier. This is the identity that the provider will use to call ARM to manage the workspace resources. + PrincipalID *string `json:"principalId,omitempty"` + + // REQUIRED; The provider's role definition identifier. This role will define all the permissions that the provider must have on the workspace's container + // resource group. This role definition cannot have + // permission to delete the resource group. + RoleDefinitionID *string `json:"roleDefinitionId,omitempty"` +} + +// WorkspaceUpdate - An update to a workspace. +type WorkspaceUpdate struct { + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type WorkspaceUpdate. +func (w WorkspaceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "tags", w.Tags) + return json.Marshal(objectMap) +} + +// WorkspacesBeginCreateOrUpdateOptions contains the optional parameters for the Workspaces.BeginCreateOrUpdate method. +type WorkspacesBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesBeginDeleteOptions contains the optional parameters for the Workspaces.BeginDelete method. +type WorkspacesBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesBeginUpdateOptions contains the optional parameters for the Workspaces.BeginUpdate method. +type WorkspacesBeginUpdateOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesGetOptions contains the optional parameters for the Workspaces.Get method. +type WorkspacesGetOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesListByResourceGroupOptions contains the optional parameters for the Workspaces.ListByResourceGroup method. +type WorkspacesListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// WorkspacesListBySubscriptionOptions contains the optional parameters for the Workspaces.ListBySubscription method. +type WorkspacesListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_operations_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_operations_client.go new file mode 100644 index 000000000000..8f5e5c842f57 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available RP operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Databricks/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_outboundnetworkdependenciesendpoints_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_outboundnetworkdependenciesendpoints_client.go new file mode 100644 index 000000000000..807bb2ca41d5 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_outboundnetworkdependenciesendpoints_client.go @@ -0,0 +1,102 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OutboundNetworkDependenciesEndpointsClient contains the methods for the OutboundNetworkDependenciesEndpoints group. +// Don't use this type directly, use NewOutboundNetworkDependenciesEndpointsClient() instead. +type OutboundNetworkDependenciesEndpointsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewOutboundNetworkDependenciesEndpointsClient creates a new instance of OutboundNetworkDependenciesEndpointsClient with the specified values. +func NewOutboundNetworkDependenciesEndpointsClient(con *arm.Connection, subscriptionID string) *OutboundNetworkDependenciesEndpointsClient { + return &OutboundNetworkDependenciesEndpointsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// List - Gets the list of endpoints that VNET Injected Workspace calls Azure Databricks Control Plane. You must configure outbound access with these endpoints. +// For more information, see +// https://docs.microsoft.com/en-us/azure/databricks/administration-guide/cloud-configurations/azure/udr +// If the operation fails it returns the *ErrorResponse error type. +func (client *OutboundNetworkDependenciesEndpointsClient) List(ctx context.Context, resourceGroupName string, workspaceName string, options *OutboundNetworkDependenciesEndpointsListOptions) (OutboundNetworkDependenciesEndpointsListResponse, error) { + req, err := client.listCreateRequest(ctx, resourceGroupName, workspaceName, options) + if err != nil { + return OutboundNetworkDependenciesEndpointsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OutboundNetworkDependenciesEndpointsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OutboundNetworkDependenciesEndpointsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *OutboundNetworkDependenciesEndpointsClient) listCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *OutboundNetworkDependenciesEndpointsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/outboundNetworkDependenciesEndpoints" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OutboundNetworkDependenciesEndpointsClient) listHandleResponse(resp *http.Response) (OutboundNetworkDependenciesEndpointsListResponse, error) { + result := OutboundNetworkDependenciesEndpointsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OutboundEnvironmentEndpointArray); err != nil { + return OutboundNetworkDependenciesEndpointsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OutboundNetworkDependenciesEndpointsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pagers.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pagers.go new file mode 100644 index 000000000000..c783ce251255 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pagers.go @@ -0,0 +1,342 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} + +// PrivateEndpointConnectionsListPager provides operations for iterating over paged responses. +type PrivateEndpointConnectionsListPager struct { + client *PrivateEndpointConnectionsClient + current PrivateEndpointConnectionsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, PrivateEndpointConnectionsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *PrivateEndpointConnectionsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *PrivateEndpointConnectionsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.PrivateEndpointConnectionsList.NextLink == nil || len(*p.current.PrivateEndpointConnectionsList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current PrivateEndpointConnectionsListResponse page. +func (p *PrivateEndpointConnectionsListPager) PageResponse() PrivateEndpointConnectionsListResponse { + return p.current +} + +// PrivateLinkResourcesListPager provides operations for iterating over paged responses. +type PrivateLinkResourcesListPager struct { + client *PrivateLinkResourcesClient + current PrivateLinkResourcesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, PrivateLinkResourcesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *PrivateLinkResourcesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *PrivateLinkResourcesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.PrivateLinkResourcesList.NextLink == nil || len(*p.current.PrivateLinkResourcesList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current PrivateLinkResourcesListResponse page. +func (p *PrivateLinkResourcesListPager) PageResponse() PrivateLinkResourcesListResponse { + return p.current +} + +// VNetPeeringListByWorkspacePager provides operations for iterating over paged responses. +type VNetPeeringListByWorkspacePager struct { + client *VNetPeeringClient + current VNetPeeringListByWorkspaceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, VNetPeeringListByWorkspaceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *VNetPeeringListByWorkspacePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *VNetPeeringListByWorkspacePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.VirtualNetworkPeeringList.NextLink == nil || len(*p.current.VirtualNetworkPeeringList.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByWorkspaceHandleError(resp) + return false + } + result, err := p.client.listByWorkspaceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current VNetPeeringListByWorkspaceResponse page. +func (p *VNetPeeringListByWorkspacePager) PageResponse() VNetPeeringListByWorkspaceResponse { + return p.current +} + +// WorkspacesListByResourceGroupPager provides operations for iterating over paged responses. +type WorkspacesListByResourceGroupPager struct { + client *WorkspacesClient + current WorkspacesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, WorkspacesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *WorkspacesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *WorkspacesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.WorkspaceListResult.NextLink == nil || len(*p.current.WorkspaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current WorkspacesListByResourceGroupResponse page. +func (p *WorkspacesListByResourceGroupPager) PageResponse() WorkspacesListByResourceGroupResponse { + return p.current +} + +// WorkspacesListBySubscriptionPager provides operations for iterating over paged responses. +type WorkspacesListBySubscriptionPager struct { + client *WorkspacesClient + current WorkspacesListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, WorkspacesListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *WorkspacesListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *WorkspacesListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.WorkspaceListResult.NextLink == nil || len(*p.current.WorkspaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current WorkspacesListBySubscriptionResponse page. +func (p *WorkspacesListBySubscriptionPager) PageResponse() WorkspacesListBySubscriptionResponse { + return p.current +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pollers.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pollers.go new file mode 100644 index 000000000000..1197e7a22405 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_pollers.go @@ -0,0 +1,317 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// PrivateEndpointConnectionsCreatePoller provides polling facilities until the operation reaches a terminal state. +type PrivateEndpointConnectionsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *PrivateEndpointConnectionsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *PrivateEndpointConnectionsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final PrivateEndpointConnectionsCreateResponse will be returned. +func (p *PrivateEndpointConnectionsCreatePoller) FinalResponse(ctx context.Context) (PrivateEndpointConnectionsCreateResponse, error) { + respType := PrivateEndpointConnectionsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.PrivateEndpointConnection) + if err != nil { + return PrivateEndpointConnectionsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *PrivateEndpointConnectionsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// PrivateEndpointConnectionsDeletePoller provides polling facilities until the operation reaches a terminal state. +type PrivateEndpointConnectionsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *PrivateEndpointConnectionsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *PrivateEndpointConnectionsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final PrivateEndpointConnectionsDeleteResponse will be returned. +func (p *PrivateEndpointConnectionsDeletePoller) FinalResponse(ctx context.Context) (PrivateEndpointConnectionsDeleteResponse, error) { + respType := PrivateEndpointConnectionsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *PrivateEndpointConnectionsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// VNetPeeringCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type VNetPeeringCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *VNetPeeringCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *VNetPeeringCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final VNetPeeringCreateOrUpdateResponse will be returned. +func (p *VNetPeeringCreateOrUpdatePoller) FinalResponse(ctx context.Context) (VNetPeeringCreateOrUpdateResponse, error) { + respType := VNetPeeringCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.VirtualNetworkPeering) + if err != nil { + return VNetPeeringCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *VNetPeeringCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// VNetPeeringDeletePoller provides polling facilities until the operation reaches a terminal state. +type VNetPeeringDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *VNetPeeringDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *VNetPeeringDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final VNetPeeringDeleteResponse will be returned. +func (p *VNetPeeringDeletePoller) FinalResponse(ctx context.Context) (VNetPeeringDeleteResponse, error) { + respType := VNetPeeringDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return VNetPeeringDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *VNetPeeringDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// WorkspacesCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type WorkspacesCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *WorkspacesCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *WorkspacesCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final WorkspacesCreateOrUpdateResponse will be returned. +func (p *WorkspacesCreateOrUpdatePoller) FinalResponse(ctx context.Context) (WorkspacesCreateOrUpdateResponse, error) { + respType := WorkspacesCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Workspace) + if err != nil { + return WorkspacesCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *WorkspacesCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// WorkspacesDeletePoller provides polling facilities until the operation reaches a terminal state. +type WorkspacesDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *WorkspacesDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *WorkspacesDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final WorkspacesDeleteResponse will be returned. +func (p *WorkspacesDeletePoller) FinalResponse(ctx context.Context) (WorkspacesDeleteResponse, error) { + respType := WorkspacesDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return WorkspacesDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *WorkspacesDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// WorkspacesUpdatePoller provides polling facilities until the operation reaches a terminal state. +type WorkspacesUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *WorkspacesUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *WorkspacesUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final WorkspacesUpdateResponse will be returned. +func (p *WorkspacesUpdatePoller) FinalResponse(ctx context.Context) (WorkspacesUpdateResponse, error) { + respType := WorkspacesUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Workspace) + if err != nil { + return WorkspacesUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *WorkspacesUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privateendpointconnections_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privateendpointconnections_client.go new file mode 100644 index 000000000000..c1c3e8f7cfc8 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privateendpointconnections_client.go @@ -0,0 +1,327 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +func NewPrivateEndpointConnectionsClient(con *arm.Connection, subscriptionID string) *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreate - Update the status of a private endpoint connection with the specified name +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) BeginCreate(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOptions) (PrivateEndpointConnectionsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, workspaceName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return PrivateEndpointConnectionsCreatePollerResponse{}, err + } + result := PrivateEndpointConnectionsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("PrivateEndpointConnectionsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return PrivateEndpointConnectionsCreatePollerResponse{}, err + } + result.Poller = &PrivateEndpointConnectionsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Update the status of a private endpoint connection with the specified name +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) create(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, workspaceName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *PrivateEndpointConnectionsClient) createCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *PrivateEndpointConnectionsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, privateEndpointConnection) +} + +// createHandleError handles the Create error response. +func (client *PrivateEndpointConnectionsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Remove private endpoint connection with the specified name +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (PrivateEndpointConnectionsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, workspaceName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsDeletePollerResponse{}, err + } + result := PrivateEndpointConnectionsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("PrivateEndpointConnectionsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return PrivateEndpointConnectionsDeletePollerResponse{}, err + } + result.Poller = &PrivateEndpointConnectionsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Remove private endpoint connection with the specified name +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, workspaceName, privateEndpointConnectionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *PrivateEndpointConnectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get a private endpoint connection properties for a workspace +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsGetOptions) (PrivateEndpointConnectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, workspaceName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, privateEndpointConnectionName string, options *PrivateEndpointConnectionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsGetResponse, error) { + result := PrivateEndpointConnectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateEndpointConnectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List private endpoint connections of the workspace +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) List(resourceGroupName string, workspaceName string, options *PrivateEndpointConnectionsListOptions) *PrivateEndpointConnectionsListPager { + return &PrivateEndpointConnectionsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, workspaceName, options) + }, + advancer: func(ctx context.Context, resp PrivateEndpointConnectionsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.PrivateEndpointConnectionsList.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *PrivateEndpointConnectionsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateEndpointConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsListResponse, error) { + result := PrivateEndpointConnectionsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionsList); err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateEndpointConnectionsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privatelinkresources_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privatelinkresources_client.go new file mode 100644 index 000000000000..c8bcaa084233 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_privatelinkresources_client.go @@ -0,0 +1,166 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +func NewPrivateLinkResourcesClient(con *arm.Connection, subscriptionID string) *PrivateLinkResourcesClient { + return &PrivateLinkResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Get - Get the specified private link resource for the given group id (sub-resource) +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, groupID string, options *PrivateLinkResourcesGetOptions) (PrivateLinkResourcesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, workspaceName, groupID, options) + if err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateLinkResourcesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateLinkResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, groupID string, options *PrivateLinkResourcesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateLinkResources/{groupId}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateLinkResourcesClient) getHandleResponse(resp *http.Response) (PrivateLinkResourcesGetResponse, error) { + result := PrivateLinkResourcesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.GroupIDInformation); err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateLinkResourcesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List private link resources for a given workspace +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateLinkResourcesClient) List(resourceGroupName string, workspaceName string, options *PrivateLinkResourcesListOptions) *PrivateLinkResourcesListPager { + return &PrivateLinkResourcesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, workspaceName, options) + }, + advancer: func(ctx context.Context, resp PrivateLinkResourcesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.PrivateLinkResourcesList.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *PrivateLinkResourcesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/privateLinkResources" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateLinkResourcesClient) listHandleResponse(resp *http.Response) (PrivateLinkResourcesListResponse, error) { + result := PrivateLinkResourcesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourcesList); err != nil { + return PrivateLinkResourcesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateLinkResourcesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_response_types.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_response_types.go new file mode 100644 index 000000000000..2b6e999ab47e --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_response_types.go @@ -0,0 +1,482 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// OutboundNetworkDependenciesEndpointsListResponse contains the response from method OutboundNetworkDependenciesEndpoints.List. +type OutboundNetworkDependenciesEndpointsListResponse struct { + OutboundNetworkDependenciesEndpointsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutboundNetworkDependenciesEndpointsListResult contains the result from method OutboundNetworkDependenciesEndpoints.List. +type OutboundNetworkDependenciesEndpointsListResult struct { + // Collection of outbound network dependency endpoints + OutboundEnvironmentEndpointArray []*OutboundEnvironmentEndpoint +} + +// PrivateEndpointConnectionsCreatePollerResponse contains the response from method PrivateEndpointConnections.Create. +type PrivateEndpointConnectionsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *PrivateEndpointConnectionsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l PrivateEndpointConnectionsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (PrivateEndpointConnectionsCreateResponse, error) { + respType := PrivateEndpointConnectionsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.PrivateEndpointConnection) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a PrivateEndpointConnectionsCreatePollerResponse from the provided client and resume token. +func (l *PrivateEndpointConnectionsCreatePollerResponse) Resume(ctx context.Context, client *PrivateEndpointConnectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("PrivateEndpointConnectionsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &PrivateEndpointConnectionsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// PrivateEndpointConnectionsCreateResponse contains the response from method PrivateEndpointConnections.Create. +type PrivateEndpointConnectionsCreateResponse struct { + PrivateEndpointConnectionsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsCreateResult contains the result from method PrivateEndpointConnections.Create. +type PrivateEndpointConnectionsCreateResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsDeletePollerResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *PrivateEndpointConnectionsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l PrivateEndpointConnectionsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (PrivateEndpointConnectionsDeleteResponse, error) { + respType := PrivateEndpointConnectionsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a PrivateEndpointConnectionsDeletePollerResponse from the provided client and resume token. +func (l *PrivateEndpointConnectionsDeletePollerResponse) Resume(ctx context.Context, client *PrivateEndpointConnectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("PrivateEndpointConnectionsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &PrivateEndpointConnectionsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// PrivateEndpointConnectionsDeleteResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResponse contains the response from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResponse struct { + PrivateEndpointConnectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResult contains the result from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsListResponse contains the response from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResponse struct { + PrivateEndpointConnectionsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsListResult contains the result from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResult struct { + PrivateEndpointConnectionsList +} + +// PrivateLinkResourcesGetResponse contains the response from method PrivateLinkResources.Get. +type PrivateLinkResourcesGetResponse struct { + PrivateLinkResourcesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesGetResult contains the result from method PrivateLinkResources.Get. +type PrivateLinkResourcesGetResult struct { + GroupIDInformation +} + +// PrivateLinkResourcesListResponse contains the response from method PrivateLinkResources.List. +type PrivateLinkResourcesListResponse struct { + PrivateLinkResourcesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesListResult contains the result from method PrivateLinkResources.List. +type PrivateLinkResourcesListResult struct { + PrivateLinkResourcesList +} + +// VNetPeeringCreateOrUpdatePollerResponse contains the response from method VNetPeering.CreateOrUpdate. +type VNetPeeringCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *VNetPeeringCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l VNetPeeringCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (VNetPeeringCreateOrUpdateResponse, error) { + respType := VNetPeeringCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.VirtualNetworkPeering) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a VNetPeeringCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *VNetPeeringCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *VNetPeeringClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("VNetPeeringClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &VNetPeeringCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// VNetPeeringCreateOrUpdateResponse contains the response from method VNetPeering.CreateOrUpdate. +type VNetPeeringCreateOrUpdateResponse struct { + VNetPeeringCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// VNetPeeringCreateOrUpdateResult contains the result from method VNetPeering.CreateOrUpdate. +type VNetPeeringCreateOrUpdateResult struct { + VirtualNetworkPeering +} + +// VNetPeeringDeletePollerResponse contains the response from method VNetPeering.Delete. +type VNetPeeringDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *VNetPeeringDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l VNetPeeringDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (VNetPeeringDeleteResponse, error) { + respType := VNetPeeringDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a VNetPeeringDeletePollerResponse from the provided client and resume token. +func (l *VNetPeeringDeletePollerResponse) Resume(ctx context.Context, client *VNetPeeringClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("VNetPeeringClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &VNetPeeringDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// VNetPeeringDeleteResponse contains the response from method VNetPeering.Delete. +type VNetPeeringDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// VNetPeeringGetResponse contains the response from method VNetPeering.Get. +type VNetPeeringGetResponse struct { + VNetPeeringGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// VNetPeeringGetResult contains the result from method VNetPeering.Get. +type VNetPeeringGetResult struct { + VirtualNetworkPeering +} + +// VNetPeeringListByWorkspaceResponse contains the response from method VNetPeering.ListByWorkspace. +type VNetPeeringListByWorkspaceResponse struct { + VNetPeeringListByWorkspaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// VNetPeeringListByWorkspaceResult contains the result from method VNetPeering.ListByWorkspace. +type VNetPeeringListByWorkspaceResult struct { + VirtualNetworkPeeringList +} + +// WorkspacesCreateOrUpdatePollerResponse contains the response from method Workspaces.CreateOrUpdate. +type WorkspacesCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *WorkspacesCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l WorkspacesCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (WorkspacesCreateOrUpdateResponse, error) { + respType := WorkspacesCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Workspace) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a WorkspacesCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *WorkspacesCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *WorkspacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("WorkspacesClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &WorkspacesCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// WorkspacesCreateOrUpdateResponse contains the response from method Workspaces.CreateOrUpdate. +type WorkspacesCreateOrUpdateResponse struct { + WorkspacesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesCreateOrUpdateResult contains the result from method Workspaces.CreateOrUpdate. +type WorkspacesCreateOrUpdateResult struct { + Workspace +} + +// WorkspacesDeletePollerResponse contains the response from method Workspaces.Delete. +type WorkspacesDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *WorkspacesDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l WorkspacesDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (WorkspacesDeleteResponse, error) { + respType := WorkspacesDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a WorkspacesDeletePollerResponse from the provided client and resume token. +func (l *WorkspacesDeletePollerResponse) Resume(ctx context.Context, client *WorkspacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("WorkspacesClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &WorkspacesDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// WorkspacesDeleteResponse contains the response from method Workspaces.Delete. +type WorkspacesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesGetResponse contains the response from method Workspaces.Get. +type WorkspacesGetResponse struct { + WorkspacesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesGetResult contains the result from method Workspaces.Get. +type WorkspacesGetResult struct { + Workspace +} + +// WorkspacesListByResourceGroupResponse contains the response from method Workspaces.ListByResourceGroup. +type WorkspacesListByResourceGroupResponse struct { + WorkspacesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesListByResourceGroupResult contains the result from method Workspaces.ListByResourceGroup. +type WorkspacesListByResourceGroupResult struct { + WorkspaceListResult +} + +// WorkspacesListBySubscriptionResponse contains the response from method Workspaces.ListBySubscription. +type WorkspacesListBySubscriptionResponse struct { + WorkspacesListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesListBySubscriptionResult contains the result from method Workspaces.ListBySubscription. +type WorkspacesListBySubscriptionResult struct { + WorkspaceListResult +} + +// WorkspacesUpdatePollerResponse contains the response from method Workspaces.Update. +type WorkspacesUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *WorkspacesUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l WorkspacesUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (WorkspacesUpdateResponse, error) { + respType := WorkspacesUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Workspace) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a WorkspacesUpdatePollerResponse from the provided client and resume token. +func (l *WorkspacesUpdatePollerResponse) Resume(ctx context.Context, client *WorkspacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("WorkspacesClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &WorkspacesUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// WorkspacesUpdateResponse contains the response from method Workspaces.Update. +type WorkspacesUpdateResponse struct { + WorkspacesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WorkspacesUpdateResult contains the result from method Workspaces.Update. +type WorkspacesUpdateResult struct { + Workspace +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_time_rfc3339.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..436b9c34723f --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_vnetpeering_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_vnetpeering_client.go new file mode 100644 index 000000000000..a0132e0324b9 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_vnetpeering_client.go @@ -0,0 +1,327 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// VNetPeeringClient contains the methods for the VNetPeering group. +// Don't use this type directly, use NewVNetPeeringClient() instead. +type VNetPeeringClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewVNetPeeringClient creates a new instance of VNetPeeringClient with the specified values. +func NewVNetPeeringClient(con *arm.Connection, subscriptionID string) *VNetPeeringClient { + return &VNetPeeringClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrUpdate - Creates vNet Peering for workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VNetPeeringBeginCreateOrUpdateOptions) (VNetPeeringCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, workspaceName, peeringName, virtualNetworkPeeringParameters, options) + if err != nil { + return VNetPeeringCreateOrUpdatePollerResponse{}, err + } + result := VNetPeeringCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("VNetPeeringClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return VNetPeeringCreateOrUpdatePollerResponse{}, err + } + result.Poller = &VNetPeeringCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Creates vNet Peering for workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) createOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VNetPeeringBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, workspaceName, peeringName, virtualNetworkPeeringParameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *VNetPeeringClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, virtualNetworkPeeringParameters VirtualNetworkPeering, options *VNetPeeringBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/virtualNetworkPeerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, virtualNetworkPeeringParameters) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *VNetPeeringClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes the workspace vNetPeering. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) BeginDelete(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, options *VNetPeeringBeginDeleteOptions) (VNetPeeringDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, workspaceName, peeringName, options) + if err != nil { + return VNetPeeringDeletePollerResponse{}, err + } + result := VNetPeeringDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("VNetPeeringClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return VNetPeeringDeletePollerResponse{}, err + } + result.Poller = &VNetPeeringDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes the workspace vNetPeering. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) deleteOperation(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, options *VNetPeeringBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, workspaceName, peeringName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *VNetPeeringClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, options *VNetPeeringBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/virtualNetworkPeerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *VNetPeeringClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the workspace vNet Peering. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, options *VNetPeeringGetOptions) (VNetPeeringGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, workspaceName, peeringName, options) + if err != nil { + return VNetPeeringGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return VNetPeeringGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return VNetPeeringGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *VNetPeeringClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, peeringName string, options *VNetPeeringGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/virtualNetworkPeerings/{peeringName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if peeringName == "" { + return nil, errors.New("parameter peeringName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{peeringName}", url.PathEscape(peeringName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *VNetPeeringClient) getHandleResponse(resp *http.Response) (VNetPeeringGetResponse, error) { + result := VNetPeeringGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkPeering); err != nil { + return VNetPeeringGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *VNetPeeringClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByWorkspace - Lists the workspace vNet Peerings. +// If the operation fails it returns the *ErrorResponse error type. +func (client *VNetPeeringClient) ListByWorkspace(resourceGroupName string, workspaceName string, options *VNetPeeringListByWorkspaceOptions) *VNetPeeringListByWorkspacePager { + return &VNetPeeringListByWorkspacePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByWorkspaceCreateRequest(ctx, resourceGroupName, workspaceName, options) + }, + advancer: func(ctx context.Context, resp VNetPeeringListByWorkspaceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.VirtualNetworkPeeringList.NextLink) + }, + } +} + +// listByWorkspaceCreateRequest creates the ListByWorkspace request. +func (client *VNetPeeringClient) listByWorkspaceCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *VNetPeeringListByWorkspaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}/virtualNetworkPeerings" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByWorkspaceHandleResponse handles the ListByWorkspace response. +func (client *VNetPeeringClient) listByWorkspaceHandleResponse(resp *http.Response) (VNetPeeringListByWorkspaceResponse, error) { + result := VNetPeeringListByWorkspaceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.VirtualNetworkPeeringList); err != nil { + return VNetPeeringListByWorkspaceResponse{}, err + } + return result, nil +} + +// listByWorkspaceHandleError handles the ListByWorkspace error response. +func (client *VNetPeeringClient) listByWorkspaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/databricks/armdatabricks/zz_generated_workspaces_client.go b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_workspaces_client.go new file mode 100644 index 000000000000..e8e53422e820 --- /dev/null +++ b/sdk/resourcemanager/databricks/armdatabricks/zz_generated_workspaces_client.go @@ -0,0 +1,441 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatabricks + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// WorkspacesClient contains the methods for the Workspaces group. +// Don't use this type directly, use NewWorkspacesClient() instead. +type WorkspacesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewWorkspacesClient creates a new instance of WorkspacesClient with the specified values. +func NewWorkspacesClient(con *arm.Connection, subscriptionID string) *WorkspacesClient { + return &WorkspacesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrUpdate - Creates a new workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, parameters Workspace, options *WorkspacesBeginCreateOrUpdateOptions) (WorkspacesCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, workspaceName, parameters, options) + if err != nil { + return WorkspacesCreateOrUpdatePollerResponse{}, err + } + result := WorkspacesCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("WorkspacesClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return WorkspacesCreateOrUpdatePollerResponse{}, err + } + result.Poller = &WorkspacesCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Creates a new workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) createOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, parameters Workspace, options *WorkspacesBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, workspaceName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WorkspacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, parameters Workspace, options *WorkspacesBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *WorkspacesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes the workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) BeginDelete(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesBeginDeleteOptions) (WorkspacesDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, workspaceName, options) + if err != nil { + return WorkspacesDeletePollerResponse{}, err + } + result := WorkspacesDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("WorkspacesClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return WorkspacesDeletePollerResponse{}, err + } + result.Poller = &WorkspacesDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes the workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) deleteOperation(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, workspaceName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WorkspacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *WorkspacesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) Get(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesGetOptions) (WorkspacesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, workspaceName, options) + if err != nil { + return WorkspacesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WorkspacesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WorkspacesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *WorkspacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, options *WorkspacesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WorkspacesClient) getHandleResponse(resp *http.Response) (WorkspacesGetResponse, error) { + result := WorkspacesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Workspace); err != nil { + return WorkspacesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *WorkspacesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Gets all the workspaces within a resource group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) ListByResourceGroup(resourceGroupName string, options *WorkspacesListByResourceGroupOptions) *WorkspacesListByResourceGroupPager { + return &WorkspacesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp WorkspacesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.WorkspaceListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *WorkspacesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *WorkspacesListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *WorkspacesClient) listByResourceGroupHandleResponse(resp *http.Response) (WorkspacesListByResourceGroupResponse, error) { + result := WorkspacesListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkspaceListResult); err != nil { + return WorkspacesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *WorkspacesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscription - Gets all the workspaces within a subscription. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) ListBySubscription(options *WorkspacesListBySubscriptionOptions) *WorkspacesListBySubscriptionPager { + return &WorkspacesListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp WorkspacesListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.WorkspaceListResult.NextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *WorkspacesClient) listBySubscriptionCreateRequest(ctx context.Context, options *WorkspacesListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Databricks/workspaces" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *WorkspacesClient) listBySubscriptionHandleResponse(resp *http.Response) (WorkspacesListBySubscriptionResponse, error) { + result := WorkspacesListBySubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.WorkspaceListResult); err != nil { + return WorkspacesListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *WorkspacesClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates a workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) BeginUpdate(ctx context.Context, resourceGroupName string, workspaceName string, parameters WorkspaceUpdate, options *WorkspacesBeginUpdateOptions) (WorkspacesUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, workspaceName, parameters, options) + if err != nil { + return WorkspacesUpdatePollerResponse{}, err + } + result := WorkspacesUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("WorkspacesClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return WorkspacesUpdatePollerResponse{}, err + } + result.Poller = &WorkspacesUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates a workspace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WorkspacesClient) update(ctx context.Context, resourceGroupName string, workspaceName string, parameters WorkspaceUpdate, options *WorkspacesBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, workspaceName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *WorkspacesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, workspaceName string, parameters WorkspaceUpdate, options *WorkspacesBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Databricks/workspaces/{workspaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if workspaceName == "" { + return nil, errors.New("parameter workspaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{workspaceName}", url.PathEscape(workspaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleError handles the Update error response. +func (client *WorkspacesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/CHANGELOG.md b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/CHANGELOG.md new file mode 100644 index 000000000000..2020c499e6f2 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-27) + +- Initial preview release. diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/LICENSE.txt b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/README.md b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/README.md new file mode 100644 index 000000000000..6a28a58020fc --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/README.md @@ -0,0 +1,76 @@ +# Azure Data Lake Analytics Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics) + +The `armdatalakeanalytics` module provides operations for working with Azure Data Lake Analytics. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Data Lake Analytics module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Data Lake Analytics. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Data Lake Analytics + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Data Lake Analytics modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armdatalakeanalytics.NewDataLakeStoreAccountsClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Data Lake Analytics` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/autorest.md b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/autorest.md new file mode 100644 index 000000000000..278242687b6d --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/348665d474283df6a73d6a2ec6defef271251f13/specification/datalake-analytics/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/348665d474283df6a73d6a2ec6defef271251f13/specification/datalake-analytics/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/build.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/build.go new file mode 100644 index 000000000000..303ff2fa5afa --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/datalake-analytics/armdatalakeanalytics + +package armdatalakeanalytics diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/ci.yml b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/ci.yml new file mode 100644 index 000000000000..31f089e68136 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/datalake-analytics/armdatalakeanalytics' diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.mod b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.mod new file mode 100644 index 000000000000..9f96f134c50f --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.3.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.sum b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.sum new file mode 100644 index 000000000000..af10d0f1292e --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible h1:lb9OWePNuJMiibdxg9XvdbiOldR0Yifge37L4LoOxIs= +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go_mod_tidy_hack.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go_mod_tidy_hack.go new file mode 100644 index 000000000000..c1c5b254b71d --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armdatalakeanalytics + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_accounts_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_accounts_client.go new file mode 100644 index 000000000000..51ce5349e954 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_accounts_client.go @@ -0,0 +1,543 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountsClient contains the methods for the Accounts group. +// Don't use this type directly, use NewAccountsClient() instead. +type AccountsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAccountsClient creates a new instance of AccountsClient with the specified values. +func NewAccountsClient(con *arm.Connection, subscriptionID string) *AccountsClient { + return &AccountsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckNameAvailability - Checks whether the specified account name is available or taken. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) CheckNameAvailability(ctx context.Context, location string, parameters CheckNameAvailabilityParameters, options *AccountsCheckNameAvailabilityOptions) (AccountsCheckNameAvailabilityResponse, error) { + req, err := client.checkNameAvailabilityCreateRequest(ctx, location, parameters, options) + if err != nil { + return AccountsCheckNameAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsCheckNameAvailabilityResponse{}, client.checkNameAvailabilityHandleError(resp) + } + return client.checkNameAvailabilityHandleResponse(resp) +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *AccountsClient) checkNameAvailabilityCreateRequest(ctx context.Context, location string, parameters CheckNameAvailabilityParameters, options *AccountsCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeAnalytics/locations/{location}/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *AccountsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (AccountsCheckNameAvailabilityResponse, error) { + result := AccountsCheckNameAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NameAvailabilityInformation); err != nil { + return AccountsCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// checkNameAvailabilityHandleError handles the CheckNameAvailability error response. +func (client *AccountsClient) checkNameAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginCreate - Creates the specified Data Lake Analytics account. This supplies the user with computation services for Data Lake Analytics workloads. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, parameters CreateDataLakeAnalyticsAccountParameters, options *AccountsBeginCreateOptions) (AccountsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return AccountsCreatePollerResponse{}, err + } + result := AccountsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return AccountsCreatePollerResponse{}, err + } + result.Poller = &AccountsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Creates the specified Data Lake Analytics account. This supplies the user with computation services for Data Lake Analytics workloads. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) create(ctx context.Context, resourceGroupName string, accountName string, parameters CreateDataLakeAnalyticsAccountParameters, options *AccountsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *AccountsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters CreateDataLakeAnalyticsAccountParameters, options *AccountsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleError handles the Create error response. +func (client *AccountsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Begins the delete process for the Data Lake Analytics account object specified by the account name. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (AccountsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsDeletePollerResponse{}, err + } + result := AccountsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return AccountsDeletePollerResponse{}, err + } + result.Poller = &AccountsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Begins the delete process for the Data Lake Analytics account object specified by the account name. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *AccountsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details of the specified Data Lake Analytics account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *AccountsGetOptions) (AccountsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountsClient) getHandleResponse(resp *http.Response) (AccountsGetResponse, error) { + result := AccountsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DataLakeAnalyticsAccount); err != nil { + return AccountsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AccountsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Gets the first page of Data Lake Analytics accounts, if any, within the current subscription. This includes a link to the next page, if any. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) List(options *AccountsListOptions) *AccountsListPager { + return &AccountsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp AccountsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.DataLakeAnalyticsAccountListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AccountsClient) listCreateRequest(ctx context.Context, options *AccountsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeAnalytics/accounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + if options != nil && options.Count != nil { + reqQP.Set("$count", strconv.FormatBool(*options.Count)) + } + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountsClient) listHandleResponse(resp *http.Response) (AccountsListResponse, error) { + result := AccountsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DataLakeAnalyticsAccountListResult); err != nil { + return AccountsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AccountsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Gets the first page of Data Lake Analytics accounts, if any, within a specific resource group. This includes a link to the next +// page, if any. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) ListByResourceGroup(resourceGroupName string, options *AccountsListByResourceGroupOptions) *AccountsListByResourceGroupPager { + return &AccountsListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp AccountsListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.DataLakeAnalyticsAccountListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AccountsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *AccountsListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + if options != nil && options.Count != nil { + reqQP.Set("$count", strconv.FormatBool(*options.Count)) + } + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AccountsClient) listByResourceGroupHandleResponse(resp *http.Response) (AccountsListByResourceGroupResponse, error) { + result := AccountsListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DataLakeAnalyticsAccountListResult); err != nil { + return AccountsListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *AccountsClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates the Data Lake Analytics account object specified by the accountName with the contents of the account object. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginUpdateOptions) (AccountsUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, accountName, options) + if err != nil { + return AccountsUpdatePollerResponse{}, err + } + result := AccountsUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("AccountsClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return AccountsUpdatePollerResponse{}, err + } + result.Poller = &AccountsUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates the Data Lake Analytics account object specified by the accountName with the contents of the account object. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountsClient) update(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *AccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountsBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// updateHandleError handles the Update error response. +func (client *AccountsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_computepolicies_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_computepolicies_client.go new file mode 100644 index 000000000000..28798c8646d6 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_computepolicies_client.go @@ -0,0 +1,368 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ComputePoliciesClient contains the methods for the ComputePolicies group. +// Don't use this type directly, use NewComputePoliciesClient() instead. +type ComputePoliciesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewComputePoliciesClient creates a new instance of ComputePoliciesClient with the specified values. +func NewComputePoliciesClient(con *arm.Connection, subscriptionID string) *ComputePoliciesClient { + return &ComputePoliciesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates the specified compute policy. During update, the compute policy with the specified name will be replaced with this +// new compute policy. An account supports, at most, 50 policies +// If the operation fails it returns the *ErrorResponse error type. +func (client *ComputePoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, parameters CreateOrUpdateComputePolicyParameters, options *ComputePoliciesCreateOrUpdateOptions) (ComputePoliciesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, computePolicyName, parameters, options) + if err != nil { + return ComputePoliciesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ComputePoliciesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ComputePoliciesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ComputePoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, parameters CreateOrUpdateComputePolicyParameters, options *ComputePoliciesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if computePolicyName == "" { + return nil, errors.New("parameter computePolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{computePolicyName}", url.PathEscape(computePolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ComputePoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (ComputePoliciesCreateOrUpdateResponse, error) { + result := ComputePoliciesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ComputePolicy); err != nil { + return ComputePoliciesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *ComputePoliciesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes the specified compute policy from the specified Data Lake Analytics account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ComputePoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesDeleteOptions) (ComputePoliciesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, computePolicyName, options) + if err != nil { + return ComputePoliciesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ComputePoliciesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return ComputePoliciesDeleteResponse{}, client.deleteHandleError(resp) + } + return ComputePoliciesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ComputePoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if computePolicyName == "" { + return nil, errors.New("parameter computePolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{computePolicyName}", url.PathEscape(computePolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ComputePoliciesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the specified Data Lake Analytics compute policy. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ComputePoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesGetOptions) (ComputePoliciesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, computePolicyName, options) + if err != nil { + return ComputePoliciesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ComputePoliciesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ComputePoliciesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *ComputePoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if computePolicyName == "" { + return nil, errors.New("parameter computePolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{computePolicyName}", url.PathEscape(computePolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ComputePoliciesClient) getHandleResponse(resp *http.Response) (ComputePoliciesGetResponse, error) { + result := ComputePoliciesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ComputePolicy); err != nil { + return ComputePoliciesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *ComputePoliciesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByAccount - Lists the Data Lake Analytics compute policies within the specified Data Lake Analytics account. An account supports, at most, 50 policies +// If the operation fails it returns the *ErrorResponse error type. +func (client *ComputePoliciesClient) ListByAccount(resourceGroupName string, accountName string, options *ComputePoliciesListByAccountOptions) *ComputePoliciesListByAccountPager { + return &ComputePoliciesListByAccountPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByAccountCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp ComputePoliciesListByAccountResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ComputePolicyListResult.NextLink) + }, + } +} + +// listByAccountCreateRequest creates the ListByAccount request. +func (client *ComputePoliciesClient) listByAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *ComputePoliciesListByAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByAccountHandleResponse handles the ListByAccount response. +func (client *ComputePoliciesClient) listByAccountHandleResponse(resp *http.Response) (ComputePoliciesListByAccountResponse, error) { + result := ComputePoliciesListByAccountResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ComputePolicyListResult); err != nil { + return ComputePoliciesListByAccountResponse{}, err + } + return result, nil +} + +// listByAccountHandleError handles the ListByAccount error response. +func (client *ComputePoliciesClient) listByAccountHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates the specified compute policy. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ComputePoliciesClient) Update(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesUpdateOptions) (ComputePoliciesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, computePolicyName, options) + if err != nil { + return ComputePoliciesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ComputePoliciesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ComputePoliciesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *ComputePoliciesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, computePolicyName string, options *ComputePoliciesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/computePolicies/{computePolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if computePolicyName == "" { + return nil, errors.New("parameter computePolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{computePolicyName}", url.PathEscape(computePolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *ComputePoliciesClient) updateHandleResponse(resp *http.Response) (ComputePoliciesUpdateResponse, error) { + result := ComputePoliciesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ComputePolicy); err != nil { + return ComputePoliciesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *ComputePoliciesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_constants.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_constants.go new file mode 100644 index 000000000000..4f1af617a259 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_constants.go @@ -0,0 +1,313 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +const ( + module = "armdatalakeanalytics" + version = "v0.1.1" +) + +// AADObjectType - The type of AAD object the object identifier refers to. +type AADObjectType string + +const ( + AADObjectTypeGroup AADObjectType = "Group" + AADObjectTypeServicePrincipal AADObjectType = "ServicePrincipal" + AADObjectTypeUser AADObjectType = "User" +) + +// PossibleAADObjectTypeValues returns the possible values for the AADObjectType const type. +func PossibleAADObjectTypeValues() []AADObjectType { + return []AADObjectType{ + AADObjectTypeGroup, + AADObjectTypeServicePrincipal, + AADObjectTypeUser, + } +} + +// ToPtr returns a *AADObjectType pointing to the current value. +func (c AADObjectType) ToPtr() *AADObjectType { + return &c +} + +// CheckNameAvailabilityParametersType - The resource type. Note: This should not be set by the user, as the constant value is Microsoft.DataLakeAnalytics/accounts +type CheckNameAvailabilityParametersType string + +const ( + CheckNameAvailabilityParametersTypeMicrosoftDataLakeAnalyticsAccounts CheckNameAvailabilityParametersType = "Microsoft.DataLakeAnalytics/accounts" +) + +// PossibleCheckNameAvailabilityParametersTypeValues returns the possible values for the CheckNameAvailabilityParametersType const type. +func PossibleCheckNameAvailabilityParametersTypeValues() []CheckNameAvailabilityParametersType { + return []CheckNameAvailabilityParametersType{ + CheckNameAvailabilityParametersTypeMicrosoftDataLakeAnalyticsAccounts, + } +} + +// ToPtr returns a *CheckNameAvailabilityParametersType pointing to the current value. +func (c CheckNameAvailabilityParametersType) ToPtr() *CheckNameAvailabilityParametersType { + return &c +} + +// DataLakeAnalyticsAccountState - The state of the Data Lake Analytics account. +type DataLakeAnalyticsAccountState string + +const ( + DataLakeAnalyticsAccountStateActive DataLakeAnalyticsAccountState = "Active" + DataLakeAnalyticsAccountStateSuspended DataLakeAnalyticsAccountState = "Suspended" +) + +// PossibleDataLakeAnalyticsAccountStateValues returns the possible values for the DataLakeAnalyticsAccountState const type. +func PossibleDataLakeAnalyticsAccountStateValues() []DataLakeAnalyticsAccountState { + return []DataLakeAnalyticsAccountState{ + DataLakeAnalyticsAccountStateActive, + DataLakeAnalyticsAccountStateSuspended, + } +} + +// ToPtr returns a *DataLakeAnalyticsAccountState pointing to the current value. +func (c DataLakeAnalyticsAccountState) ToPtr() *DataLakeAnalyticsAccountState { + return &c +} + +// DataLakeAnalyticsAccountStatus - The provisioning status of the Data Lake Analytics account. +type DataLakeAnalyticsAccountStatus string + +const ( + DataLakeAnalyticsAccountStatusFailed DataLakeAnalyticsAccountStatus = "Failed" + DataLakeAnalyticsAccountStatusCreating DataLakeAnalyticsAccountStatus = "Creating" + DataLakeAnalyticsAccountStatusRunning DataLakeAnalyticsAccountStatus = "Running" + DataLakeAnalyticsAccountStatusSucceeded DataLakeAnalyticsAccountStatus = "Succeeded" + DataLakeAnalyticsAccountStatusPatching DataLakeAnalyticsAccountStatus = "Patching" + DataLakeAnalyticsAccountStatusSuspending DataLakeAnalyticsAccountStatus = "Suspending" + DataLakeAnalyticsAccountStatusResuming DataLakeAnalyticsAccountStatus = "Resuming" + DataLakeAnalyticsAccountStatusDeleting DataLakeAnalyticsAccountStatus = "Deleting" + DataLakeAnalyticsAccountStatusDeleted DataLakeAnalyticsAccountStatus = "Deleted" + DataLakeAnalyticsAccountStatusUndeleting DataLakeAnalyticsAccountStatus = "Undeleting" + DataLakeAnalyticsAccountStatusCanceled DataLakeAnalyticsAccountStatus = "Canceled" +) + +// PossibleDataLakeAnalyticsAccountStatusValues returns the possible values for the DataLakeAnalyticsAccountStatus const type. +func PossibleDataLakeAnalyticsAccountStatusValues() []DataLakeAnalyticsAccountStatus { + return []DataLakeAnalyticsAccountStatus{ + DataLakeAnalyticsAccountStatusFailed, + DataLakeAnalyticsAccountStatusCreating, + DataLakeAnalyticsAccountStatusRunning, + DataLakeAnalyticsAccountStatusSucceeded, + DataLakeAnalyticsAccountStatusPatching, + DataLakeAnalyticsAccountStatusSuspending, + DataLakeAnalyticsAccountStatusResuming, + DataLakeAnalyticsAccountStatusDeleting, + DataLakeAnalyticsAccountStatusDeleted, + DataLakeAnalyticsAccountStatusUndeleting, + DataLakeAnalyticsAccountStatusCanceled, + } +} + +// ToPtr returns a *DataLakeAnalyticsAccountStatus pointing to the current value. +func (c DataLakeAnalyticsAccountStatus) ToPtr() *DataLakeAnalyticsAccountStatus { + return &c +} + +// DebugDataAccessLevel - The current state of the DebugDataAccessLevel for this account. +type DebugDataAccessLevel string + +const ( + DebugDataAccessLevelAll DebugDataAccessLevel = "All" + DebugDataAccessLevelCustomer DebugDataAccessLevel = "Customer" + DebugDataAccessLevelNone DebugDataAccessLevel = "None" +) + +// PossibleDebugDataAccessLevelValues returns the possible values for the DebugDataAccessLevel const type. +func PossibleDebugDataAccessLevelValues() []DebugDataAccessLevel { + return []DebugDataAccessLevel{ + DebugDataAccessLevelAll, + DebugDataAccessLevelCustomer, + DebugDataAccessLevelNone, + } +} + +// ToPtr returns a *DebugDataAccessLevel pointing to the current value. +func (c DebugDataAccessLevel) ToPtr() *DebugDataAccessLevel { + return &c +} + +// FirewallAllowAzureIPsState - The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, +// this is not enforced. +type FirewallAllowAzureIPsState string + +const ( + FirewallAllowAzureIPsStateEnabled FirewallAllowAzureIPsState = "Enabled" + FirewallAllowAzureIPsStateDisabled FirewallAllowAzureIPsState = "Disabled" +) + +// PossibleFirewallAllowAzureIPsStateValues returns the possible values for the FirewallAllowAzureIPsState const type. +func PossibleFirewallAllowAzureIPsStateValues() []FirewallAllowAzureIPsState { + return []FirewallAllowAzureIPsState{ + FirewallAllowAzureIPsStateEnabled, + FirewallAllowAzureIPsStateDisabled, + } +} + +// ToPtr returns a *FirewallAllowAzureIPsState pointing to the current value. +func (c FirewallAllowAzureIPsState) ToPtr() *FirewallAllowAzureIPsState { + return &c +} + +// FirewallState - The current state of the IP address firewall for this account. +type FirewallState string + +const ( + FirewallStateEnabled FirewallState = "Enabled" + FirewallStateDisabled FirewallState = "Disabled" +) + +// PossibleFirewallStateValues returns the possible values for the FirewallState const type. +func PossibleFirewallStateValues() []FirewallState { + return []FirewallState{ + FirewallStateEnabled, + FirewallStateDisabled, + } +} + +// ToPtr returns a *FirewallState pointing to the current value. +func (c FirewallState) ToPtr() *FirewallState { + return &c +} + +// NestedResourceProvisioningState - The current state of the NestedResourceProvisioning for this account. +type NestedResourceProvisioningState string + +const ( + NestedResourceProvisioningStateSucceeded NestedResourceProvisioningState = "Succeeded" + NestedResourceProvisioningStateCanceled NestedResourceProvisioningState = "Canceled" + NestedResourceProvisioningStateFailed NestedResourceProvisioningState = "Failed" +) + +// PossibleNestedResourceProvisioningStateValues returns the possible values for the NestedResourceProvisioningState const type. +func PossibleNestedResourceProvisioningStateValues() []NestedResourceProvisioningState { + return []NestedResourceProvisioningState{ + NestedResourceProvisioningStateSucceeded, + NestedResourceProvisioningStateCanceled, + NestedResourceProvisioningStateFailed, + } +} + +// ToPtr returns a *NestedResourceProvisioningState pointing to the current value. +func (c NestedResourceProvisioningState) ToPtr() *NestedResourceProvisioningState { + return &c +} + +// OperationOrigin - The intended executor of the operation. +type OperationOrigin string + +const ( + OperationOriginSystem OperationOrigin = "system" + OperationOriginUser OperationOrigin = "user" + OperationOriginUserSystem OperationOrigin = "user,system" +) + +// PossibleOperationOriginValues returns the possible values for the OperationOrigin const type. +func PossibleOperationOriginValues() []OperationOrigin { + return []OperationOrigin{ + OperationOriginSystem, + OperationOriginUser, + OperationOriginUserSystem, + } +} + +// ToPtr returns a *OperationOrigin pointing to the current value. +func (c OperationOrigin) ToPtr() *OperationOrigin { + return &c +} + +// SubscriptionState - The subscription state. +type SubscriptionState string + +const ( + SubscriptionStateDeleted SubscriptionState = "Deleted" + SubscriptionStateRegistered SubscriptionState = "Registered" + SubscriptionStateSuspended SubscriptionState = "Suspended" + SubscriptionStateUnregistered SubscriptionState = "Unregistered" + SubscriptionStateWarned SubscriptionState = "Warned" +) + +// PossibleSubscriptionStateValues returns the possible values for the SubscriptionState const type. +func PossibleSubscriptionStateValues() []SubscriptionState { + return []SubscriptionState{ + SubscriptionStateDeleted, + SubscriptionStateRegistered, + SubscriptionStateSuspended, + SubscriptionStateUnregistered, + SubscriptionStateWarned, + } +} + +// ToPtr returns a *SubscriptionState pointing to the current value. +func (c SubscriptionState) ToPtr() *SubscriptionState { + return &c +} + +// TierType - The commitment tier for the next month. +type TierType string + +const ( + TierTypeConsumption TierType = "Consumption" + TierTypeCommitment100AUHours TierType = "Commitment_100AUHours" + TierTypeCommitment500AUHours TierType = "Commitment_500AUHours" + TierTypeCommitment1000AUHours TierType = "Commitment_1000AUHours" + TierTypeCommitment5000AUHours TierType = "Commitment_5000AUHours" + TierTypeCommitment10000AUHours TierType = "Commitment_10000AUHours" + TierTypeCommitment50000AUHours TierType = "Commitment_50000AUHours" + TierTypeCommitment100000AUHours TierType = "Commitment_100000AUHours" + TierTypeCommitment500000AUHours TierType = "Commitment_500000AUHours" +) + +// PossibleTierTypeValues returns the possible values for the TierType const type. +func PossibleTierTypeValues() []TierType { + return []TierType{ + TierTypeConsumption, + TierTypeCommitment100AUHours, + TierTypeCommitment500AUHours, + TierTypeCommitment1000AUHours, + TierTypeCommitment5000AUHours, + TierTypeCommitment10000AUHours, + TierTypeCommitment50000AUHours, + TierTypeCommitment100000AUHours, + TierTypeCommitment500000AUHours, + } +} + +// ToPtr returns a *TierType pointing to the current value. +func (c TierType) ToPtr() *TierType { + return &c +} + +// VirtualNetworkRuleState - The current state of the VirtualNetworkRule for this account. +type VirtualNetworkRuleState string + +const ( + VirtualNetworkRuleStateActive VirtualNetworkRuleState = "Active" + VirtualNetworkRuleStateNetworkSourceDeleted VirtualNetworkRuleState = "NetworkSourceDeleted" + VirtualNetworkRuleStateFailed VirtualNetworkRuleState = "Failed" +) + +// PossibleVirtualNetworkRuleStateValues returns the possible values for the VirtualNetworkRuleState const type. +func PossibleVirtualNetworkRuleStateValues() []VirtualNetworkRuleState { + return []VirtualNetworkRuleState{ + VirtualNetworkRuleStateActive, + VirtualNetworkRuleStateNetworkSourceDeleted, + VirtualNetworkRuleStateFailed, + } +} + +// ToPtr returns a *VirtualNetworkRuleState pointing to the current value. +func (c VirtualNetworkRuleState) ToPtr() *VirtualNetworkRuleState { + return &c +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_datalakestoreaccounts_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_datalakestoreaccounts_client.go new file mode 100644 index 000000000000..820d59116c28 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_datalakestoreaccounts_client.go @@ -0,0 +1,309 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// DataLakeStoreAccountsClient contains the methods for the DataLakeStoreAccounts group. +// Don't use this type directly, use NewDataLakeStoreAccountsClient() instead. +type DataLakeStoreAccountsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewDataLakeStoreAccountsClient creates a new instance of DataLakeStoreAccountsClient with the specified values. +func NewDataLakeStoreAccountsClient(con *arm.Connection, subscriptionID string) *DataLakeStoreAccountsClient { + return &DataLakeStoreAccountsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Add - Updates the specified Data Lake Analytics account to include the additional Data Lake Store account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DataLakeStoreAccountsClient) Add(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsAddOptions) (DataLakeStoreAccountsAddResponse, error) { + req, err := client.addCreateRequest(ctx, resourceGroupName, accountName, dataLakeStoreAccountName, options) + if err != nil { + return DataLakeStoreAccountsAddResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return DataLakeStoreAccountsAddResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return DataLakeStoreAccountsAddResponse{}, client.addHandleError(resp) + } + return DataLakeStoreAccountsAddResponse{RawResponse: resp}, nil +} + +// addCreateRequest creates the Add request. +func (client *DataLakeStoreAccountsClient) addCreateRequest(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsAddOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/dataLakeStoreAccounts/{dataLakeStoreAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if dataLakeStoreAccountName == "" { + return nil, errors.New("parameter dataLakeStoreAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dataLakeStoreAccountName}", url.PathEscape(dataLakeStoreAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// addHandleError handles the Add error response. +func (client *DataLakeStoreAccountsClient) addHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Updates the Data Lake Analytics account specified to remove the specified Data Lake Store account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DataLakeStoreAccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsDeleteOptions) (DataLakeStoreAccountsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, dataLakeStoreAccountName, options) + if err != nil { + return DataLakeStoreAccountsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return DataLakeStoreAccountsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return DataLakeStoreAccountsDeleteResponse{}, client.deleteHandleError(resp) + } + return DataLakeStoreAccountsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *DataLakeStoreAccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/dataLakeStoreAccounts/{dataLakeStoreAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if dataLakeStoreAccountName == "" { + return nil, errors.New("parameter dataLakeStoreAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dataLakeStoreAccountName}", url.PathEscape(dataLakeStoreAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *DataLakeStoreAccountsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the specified Data Lake Store account details in the specified Data Lake Analytics account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DataLakeStoreAccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsGetOptions) (DataLakeStoreAccountsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, dataLakeStoreAccountName, options) + if err != nil { + return DataLakeStoreAccountsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return DataLakeStoreAccountsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return DataLakeStoreAccountsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *DataLakeStoreAccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, dataLakeStoreAccountName string, options *DataLakeStoreAccountsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/dataLakeStoreAccounts/{dataLakeStoreAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if dataLakeStoreAccountName == "" { + return nil, errors.New("parameter dataLakeStoreAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{dataLakeStoreAccountName}", url.PathEscape(dataLakeStoreAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *DataLakeStoreAccountsClient) getHandleResponse(resp *http.Response) (DataLakeStoreAccountsGetResponse, error) { + result := DataLakeStoreAccountsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DataLakeStoreAccountInformation); err != nil { + return DataLakeStoreAccountsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *DataLakeStoreAccountsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByAccount - Gets the first page of Data Lake Store accounts linked to the specified Data Lake Analytics account. The response includes a link to +// the next page, if any. +// If the operation fails it returns the *ErrorResponse error type. +func (client *DataLakeStoreAccountsClient) ListByAccount(resourceGroupName string, accountName string, options *DataLakeStoreAccountsListByAccountOptions) *DataLakeStoreAccountsListByAccountPager { + return &DataLakeStoreAccountsListByAccountPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByAccountCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp DataLakeStoreAccountsListByAccountResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.DataLakeStoreAccountInformationListResult.NextLink) + }, + } +} + +// listByAccountCreateRequest creates the ListByAccount request. +func (client *DataLakeStoreAccountsClient) listByAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *DataLakeStoreAccountsListByAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/dataLakeStoreAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + if options != nil && options.Count != nil { + reqQP.Set("$count", strconv.FormatBool(*options.Count)) + } + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByAccountHandleResponse handles the ListByAccount response. +func (client *DataLakeStoreAccountsClient) listByAccountHandleResponse(resp *http.Response) (DataLakeStoreAccountsListByAccountResponse, error) { + result := DataLakeStoreAccountsListByAccountResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DataLakeStoreAccountInformationListResult); err != nil { + return DataLakeStoreAccountsListByAccountResponse{}, err + } + return result, nil +} + +// listByAccountHandleError handles the ListByAccount error response. +func (client *DataLakeStoreAccountsClient) listByAccountHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_firewallrules_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_firewallrules_client.go new file mode 100644 index 000000000000..1e452be17ecc --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_firewallrules_client.go @@ -0,0 +1,368 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// FirewallRulesClient contains the methods for the FirewallRules group. +// Don't use this type directly, use NewFirewallRulesClient() instead. +type FirewallRulesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewFirewallRulesClient creates a new instance of FirewallRulesClient with the specified values. +func NewFirewallRulesClient(con *arm.Connection, subscriptionID string) *FirewallRulesClient { + return &FirewallRulesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates the specified firewall rule. During update, the firewall rule with the specified name will be replaced with this +// new firewall rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *FirewallRulesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, parameters CreateOrUpdateFirewallRuleParameters, options *FirewallRulesCreateOrUpdateOptions) (FirewallRulesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, firewallRuleName, parameters, options) + if err != nil { + return FirewallRulesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FirewallRulesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FirewallRulesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *FirewallRulesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, parameters CreateOrUpdateFirewallRuleParameters, options *FirewallRulesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *FirewallRulesClient) createOrUpdateHandleResponse(resp *http.Response) (FirewallRulesCreateOrUpdateResponse, error) { + result := FirewallRulesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { + return FirewallRulesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *FirewallRulesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes the specified firewall rule from the specified Data Lake Analytics account +// If the operation fails it returns the *ErrorResponse error type. +func (client *FirewallRulesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesDeleteOptions) (FirewallRulesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, firewallRuleName, options) + if err != nil { + return FirewallRulesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FirewallRulesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return FirewallRulesDeleteResponse{}, client.deleteHandleError(resp) + } + return FirewallRulesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *FirewallRulesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the specified Data Lake Analytics firewall rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *FirewallRulesClient) Get(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesGetOptions) (FirewallRulesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, firewallRuleName, options) + if err != nil { + return FirewallRulesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FirewallRulesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FirewallRulesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *FirewallRulesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FirewallRulesClient) getHandleResponse(resp *http.Response) (FirewallRulesGetResponse, error) { + result := FirewallRulesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { + return FirewallRulesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *FirewallRulesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByAccount - Lists the Data Lake Analytics firewall rules within the specified Data Lake Analytics account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *FirewallRulesClient) ListByAccount(resourceGroupName string, accountName string, options *FirewallRulesListByAccountOptions) *FirewallRulesListByAccountPager { + return &FirewallRulesListByAccountPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByAccountCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp FirewallRulesListByAccountResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.FirewallRuleListResult.NextLink) + }, + } +} + +// listByAccountCreateRequest creates the ListByAccount request. +func (client *FirewallRulesClient) listByAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *FirewallRulesListByAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByAccountHandleResponse handles the ListByAccount response. +func (client *FirewallRulesClient) listByAccountHandleResponse(resp *http.Response) (FirewallRulesListByAccountResponse, error) { + result := FirewallRulesListByAccountResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRuleListResult); err != nil { + return FirewallRulesListByAccountResponse{}, err + } + return result, nil +} + +// listByAccountHandleError handles the ListByAccount error response. +func (client *FirewallRulesClient) listByAccountHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates the specified firewall rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *FirewallRulesClient) Update(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesUpdateOptions) (FirewallRulesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, firewallRuleName, options) + if err != nil { + return FirewallRulesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FirewallRulesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FirewallRulesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *FirewallRulesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, firewallRuleName string, options *FirewallRulesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/firewallRules/{firewallRuleName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if firewallRuleName == "" { + return nil, errors.New("parameter firewallRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{firewallRuleName}", url.PathEscape(firewallRuleName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// updateHandleResponse handles the Update response. +func (client *FirewallRulesClient) updateHandleResponse(resp *http.Response) (FirewallRulesUpdateResponse, error) { + result := FirewallRulesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.FirewallRule); err != nil { + return FirewallRulesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *FirewallRulesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_locations_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_locations_client.go new file mode 100644 index 000000000000..844ec826533d --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_locations_client.go @@ -0,0 +1,96 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// LocationsClient contains the methods for the Locations group. +// Don't use this type directly, use NewLocationsClient() instead. +type LocationsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewLocationsClient creates a new instance of LocationsClient with the specified values. +func NewLocationsClient(con *arm.Connection, subscriptionID string) *LocationsClient { + return &LocationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// GetCapability - Gets subscription-level properties and limits for Data Lake Analytics specified by resource location. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LocationsClient) GetCapability(ctx context.Context, location string, options *LocationsGetCapabilityOptions) (LocationsGetCapabilityResponse, error) { + req, err := client.getCapabilityCreateRequest(ctx, location, options) + if err != nil { + return LocationsGetCapabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return LocationsGetCapabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNotFound) { + return LocationsGetCapabilityResponse{}, client.getCapabilityHandleError(resp) + } + return client.getCapabilityHandleResponse(resp) +} + +// getCapabilityCreateRequest creates the GetCapability request. +func (client *LocationsClient) getCapabilityCreateRequest(ctx context.Context, location string, options *LocationsGetCapabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.DataLakeAnalytics/locations/{location}/capability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getCapabilityHandleResponse handles the GetCapability response. +func (client *LocationsClient) getCapabilityHandleResponse(resp *http.Response) (LocationsGetCapabilityResponse, error) { + result := LocationsGetCapabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CapabilityInformation); err != nil { + return LocationsGetCapabilityResponse{}, err + } + return result, nil +} + +// getCapabilityHandleError handles the GetCapability error response. +func (client *LocationsClient) getCapabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_models.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_models.go new file mode 100644 index 000000000000..4a907545bb62 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_models.go @@ -0,0 +1,1495 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AccountsBeginCreateOptions contains the optional parameters for the Accounts.BeginCreate method. +type AccountsBeginCreateOptions struct { + // placeholder for future optional parameters +} + +// AccountsBeginDeleteOptions contains the optional parameters for the Accounts.BeginDelete method. +type AccountsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// AccountsBeginUpdateOptions contains the optional parameters for the Accounts.BeginUpdate method. +type AccountsBeginUpdateOptions struct { + // Parameters supplied to the update Data Lake Analytics account operation. + Parameters *UpdateDataLakeAnalyticsAccountParameters +} + +// AccountsCheckNameAvailabilityOptions contains the optional parameters for the Accounts.CheckNameAvailability method. +type AccountsCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// AccountsGetOptions contains the optional parameters for the Accounts.Get method. +type AccountsGetOptions struct { + // placeholder for future optional parameters +} + +// AccountsListByResourceGroupOptions contains the optional parameters for the Accounts.ListByResourceGroup method. +type AccountsListByResourceGroupOptions struct { + // The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. + // Optional. + Count *bool + // OData filter. Optional. + Filter *string + // OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, + // e.g. Categories?$orderby=CategoryName desc. Optional. + Orderby *string + // OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. + Select *string + // The number of items to skip over before returning elements. Optional. + Skip *int32 + // The number of items to return. Optional. + Top *int32 +} + +// AccountsListOptions contains the optional parameters for the Accounts.List method. +type AccountsListOptions struct { + // The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. + // Optional. + Count *bool + // OData filter. Optional. + Filter *string + // OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, + // e.g. Categories?$orderby=CategoryName desc. Optional. + Orderby *string + // OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. + Select *string + // The number of items to skip over before returning elements. Optional. + Skip *int32 + // The number of items to return. Optional. + Top *int32 +} + +// AddDataLakeStoreParameters - The parameters used to add a new Data Lake Store account. +type AddDataLakeStoreParameters struct { + // The Data Lake Store account properties to use when adding a new Data Lake Store account. + Properties *AddDataLakeStoreProperties `json:"properties,omitempty"` +} + +// AddDataLakeStoreProperties - The Data Lake Store account properties to use when adding a new Data Lake Store account. +type AddDataLakeStoreProperties struct { + // The optional suffix for the Data Lake Store account. + Suffix *string `json:"suffix,omitempty"` +} + +// AddDataLakeStoreWithAccountParameters - The parameters used to add a new Data Lake Store account while creating a new Data Lake Analytics account. +type AddDataLakeStoreWithAccountParameters struct { + // REQUIRED; The unique name of the Data Lake Store account to add. + Name *string `json:"name,omitempty"` + + // The Data Lake Store account properties to use when adding a new Data Lake Store account. + Properties *AddDataLakeStoreProperties `json:"properties,omitempty"` +} + +// AddStorageAccountParameters - The parameters used to add a new Azure Storage account. +type AddStorageAccountParameters struct { + // REQUIRED; The Azure Storage account properties to use when adding a new Azure Storage account. + Properties *AddStorageAccountProperties `json:"properties,omitempty"` +} + +// AddStorageAccountProperties - The Azure Storage account properties to use when adding a new Azure Storage account. +type AddStorageAccountProperties struct { + // REQUIRED; The access key associated with this Azure Storage account that will be used to connect to it. + AccessKey *string `json:"accessKey,omitempty"` + + // The optional suffix for the storage account. + Suffix *string `json:"suffix,omitempty"` +} + +// AddStorageAccountWithAccountParameters - The parameters used to add a new Azure Storage account while creating a new Data Lake Analytics account. +type AddStorageAccountWithAccountParameters struct { + // REQUIRED; The unique name of the Azure Storage account to add. + Name *string `json:"name,omitempty"` + + // REQUIRED; The Azure Storage account properties to use when adding a new Azure Storage account. + Properties *AddStorageAccountProperties `json:"properties,omitempty"` +} + +// CapabilityInformation - Subscription-level properties and limits for Data Lake Analytics. +type CapabilityInformation struct { + // READ-ONLY; The current number of accounts under this subscription. + AccountCount *int32 `json:"accountCount,omitempty" azure:"ro"` + + // READ-ONLY; The maximum supported number of accounts under this subscription. + MaxAccountCount *int32 `json:"maxAccountCount,omitempty" azure:"ro"` + + // READ-ONLY; The Boolean value of true or false to indicate the maintenance state. + MigrationState *bool `json:"migrationState,omitempty" azure:"ro"` + + // READ-ONLY; The subscription state. + State *SubscriptionState `json:"state,omitempty" azure:"ro"` + + // READ-ONLY; The subscription credentials that uniquely identifies the subscription. + SubscriptionID *string `json:"subscriptionId,omitempty" azure:"ro"` +} + +// CheckNameAvailabilityParameters - Data Lake Analytics account name availability check parameters. +type CheckNameAvailabilityParameters struct { + // REQUIRED; The Data Lake Analytics name to check availability for. + Name *string `json:"name,omitempty"` + + // REQUIRED; The resource type. Note: This should not be set by the user, as the constant value is Microsoft.DataLakeAnalytics/accounts + Type *CheckNameAvailabilityParametersType `json:"type,omitempty"` +} + +// ComputePoliciesCreateOrUpdateOptions contains the optional parameters for the ComputePolicies.CreateOrUpdate method. +type ComputePoliciesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ComputePoliciesDeleteOptions contains the optional parameters for the ComputePolicies.Delete method. +type ComputePoliciesDeleteOptions struct { + // placeholder for future optional parameters +} + +// ComputePoliciesGetOptions contains the optional parameters for the ComputePolicies.Get method. +type ComputePoliciesGetOptions struct { + // placeholder for future optional parameters +} + +// ComputePoliciesListByAccountOptions contains the optional parameters for the ComputePolicies.ListByAccount method. +type ComputePoliciesListByAccountOptions struct { + // placeholder for future optional parameters +} + +// ComputePoliciesUpdateOptions contains the optional parameters for the ComputePolicies.Update method. +type ComputePoliciesUpdateOptions struct { + // Parameters supplied to update the compute policy. + Parameters *UpdateComputePolicyParameters +} + +// ComputePolicy - Data Lake Analytics compute policy information. +type ComputePolicy struct { + SubResource + // READ-ONLY; The compute policy properties. + Properties *ComputePolicyProperties `json:"properties,omitempty" azure:"ro"` +} + +// ComputePolicyListResult - The list of compute policies in the account. +type ComputePolicyListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*ComputePolicy `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ComputePolicyListResult. +func (c ComputePolicyListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// ComputePolicyProperties - The compute policy properties. +type ComputePolicyProperties struct { + // READ-ONLY; The maximum degree of parallelism per job this user can use to submit jobs. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty" azure:"ro"` + + // READ-ONLY; The minimum priority per job this user can use to submit jobs. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty" azure:"ro"` + + // READ-ONLY; The AAD object identifier for the entity to create a policy for. + ObjectID *string `json:"objectId,omitempty" azure:"ro"` + + // READ-ONLY; The type of AAD object the object identifier refers to. + ObjectType *AADObjectType `json:"objectType,omitempty" azure:"ro"` +} + +// CreateComputePolicyWithAccountParameters - The parameters used to create a new compute policy while creating a new Data Lake Analytics account. +type CreateComputePolicyWithAccountParameters struct { + // REQUIRED; The unique name of the compute policy to create. + Name *string `json:"name,omitempty"` + + // REQUIRED; The compute policy properties to use when creating a new compute policy. + Properties *CreateOrUpdateComputePolicyProperties `json:"properties,omitempty"` +} + +// CreateDataLakeAnalyticsAccountParameters - The parameters to use for creating a Data Lake Analytics account. +type CreateDataLakeAnalyticsAccountParameters struct { + // REQUIRED; The resource location. + Location *string `json:"location,omitempty"` + + // REQUIRED; The Data Lake Analytics account properties to use for creating. + Properties *CreateDataLakeAnalyticsAccountProperties `json:"properties,omitempty"` + + // The resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateDataLakeAnalyticsAccountParameters. +func (c CreateDataLakeAnalyticsAccountParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "location", c.Location) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "tags", c.Tags) + return json.Marshal(objectMap) +} + +type CreateDataLakeAnalyticsAccountProperties struct { + // REQUIRED; The list of Data Lake Store accounts associated with this account. + DataLakeStoreAccounts []*AddDataLakeStoreWithAccountParameters `json:"dataLakeStoreAccounts,omitempty"` + + // REQUIRED; The default Data Lake Store account associated with this account. + DefaultDataLakeStoreAccount *string `json:"defaultDataLakeStoreAccount,omitempty"` + + // The list of compute policies associated with this account. + ComputePolicies []*CreateComputePolicyWithAccountParameters `json:"computePolicies,omitempty"` + + // The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. + FirewallAllowAzureIPs *FirewallAllowAzureIPsState `json:"firewallAllowAzureIps,omitempty"` + + // The list of firewall rules associated with this account. + FirewallRules []*CreateFirewallRuleWithAccountParameters `json:"firewallRules,omitempty"` + + // The current state of the IP address firewall for this account. + FirewallState *FirewallState `json:"firewallState,omitempty"` + + // The maximum supported degree of parallelism for this account. + MaxDegreeOfParallelism *int32 `json:"maxDegreeOfParallelism,omitempty"` + + // The maximum supported degree of parallelism per job for this account. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty"` + + // The maximum supported jobs running under the account at the same time. + MaxJobCount *int32 `json:"maxJobCount,omitempty"` + + // The minimum supported priority per job for this account. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty"` + + // The commitment tier for the next month. + NewTier *TierType `json:"newTier,omitempty"` + + // The number of days that job metadata is retained. + QueryStoreRetention *int32 `json:"queryStoreRetention,omitempty"` + + // The list of Azure Blob Storage accounts associated with this account. + StorageAccounts []*AddStorageAccountWithAccountParameters `json:"storageAccounts,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateDataLakeAnalyticsAccountProperties. +func (c CreateDataLakeAnalyticsAccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "computePolicies", c.ComputePolicies) + populate(objectMap, "dataLakeStoreAccounts", c.DataLakeStoreAccounts) + populate(objectMap, "defaultDataLakeStoreAccount", c.DefaultDataLakeStoreAccount) + populate(objectMap, "firewallAllowAzureIps", c.FirewallAllowAzureIPs) + populate(objectMap, "firewallRules", c.FirewallRules) + populate(objectMap, "firewallState", c.FirewallState) + populate(objectMap, "maxDegreeOfParallelism", c.MaxDegreeOfParallelism) + populate(objectMap, "maxDegreeOfParallelismPerJob", c.MaxDegreeOfParallelismPerJob) + populate(objectMap, "maxJobCount", c.MaxJobCount) + populate(objectMap, "minPriorityPerJob", c.MinPriorityPerJob) + populate(objectMap, "newTier", c.NewTier) + populate(objectMap, "queryStoreRetention", c.QueryStoreRetention) + populate(objectMap, "storageAccounts", c.StorageAccounts) + return json.Marshal(objectMap) +} + +// CreateFirewallRuleWithAccountParameters - The parameters used to create a new firewall rule while creating a new Data Lake Analytics account. +type CreateFirewallRuleWithAccountParameters struct { + // REQUIRED; The unique name of the firewall rule to create. + Name *string `json:"name,omitempty"` + + // REQUIRED; The firewall rule properties to use when creating a new firewall rule. + Properties *CreateOrUpdateFirewallRuleProperties `json:"properties,omitempty"` +} + +// CreateOrUpdateComputePolicyParameters - The parameters used to create a new compute policy. +type CreateOrUpdateComputePolicyParameters struct { + // REQUIRED; The compute policy properties to use when creating a new compute policy. + Properties *CreateOrUpdateComputePolicyProperties `json:"properties,omitempty"` +} + +// CreateOrUpdateComputePolicyProperties - The compute policy properties to use when creating a new compute policy. +type CreateOrUpdateComputePolicyProperties struct { + // REQUIRED; The AAD object identifier for the entity to create a policy for. + ObjectID *string `json:"objectId,omitempty"` + + // REQUIRED; The type of AAD object the object identifier refers to. + ObjectType *AADObjectType `json:"objectType,omitempty"` + + // The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty"` + + // The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty"` +} + +// CreateOrUpdateFirewallRuleParameters - The parameters used to create a new firewall rule. +type CreateOrUpdateFirewallRuleParameters struct { + // REQUIRED; The firewall rule properties to use when creating a new firewall rule. + Properties *CreateOrUpdateFirewallRuleProperties `json:"properties,omitempty"` +} + +// CreateOrUpdateFirewallRuleProperties - The firewall rule properties to use when creating a new firewall rule. +type CreateOrUpdateFirewallRuleProperties struct { + // REQUIRED; The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + EndIPAddress *string `json:"endIpAddress,omitempty"` + + // REQUIRED; The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + StartIPAddress *string `json:"startIpAddress,omitempty"` +} + +// DataLakeAnalyticsAccount - A Data Lake Analytics account object, containing all information associated with the named Data Lake Analytics account. +type DataLakeAnalyticsAccount struct { + Resource + // READ-ONLY; The properties defined by Data Lake Analytics all properties are specific to each resource provider. + Properties *DataLakeAnalyticsAccountProperties `json:"properties,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeAnalyticsAccount. +func (d DataLakeAnalyticsAccount) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", d.Properties) + return json.Marshal(objectMap) +} + +// DataLakeAnalyticsAccountBasic - A Data Lake Analytics account object, containing all information associated with the named Data Lake Analytics account. +type DataLakeAnalyticsAccountBasic struct { + Resource + // READ-ONLY; The properties defined by Data Lake Analytics all properties are specific to each resource provider. + Properties *DataLakeAnalyticsAccountPropertiesBasic `json:"properties,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeAnalyticsAccountBasic. +func (d DataLakeAnalyticsAccountBasic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", d.Properties) + return json.Marshal(objectMap) +} + +// DataLakeAnalyticsAccountListResult - Data Lake Analytics account list information. +type DataLakeAnalyticsAccountListResult struct { + // READ-ONLY; The current number of data lake analytics accounts under this subscription. + Count *int32 `json:"count,omitempty" azure:"ro"` + + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*DataLakeAnalyticsAccountBasic `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeAnalyticsAccountListResult. +func (d DataLakeAnalyticsAccountListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", d.Count) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// DataLakeAnalyticsAccountProperties - The account specific properties that are associated with an underlying Data Lake Analytics account. Returned only +// when retrieving a specific account. +type DataLakeAnalyticsAccountProperties struct { + DataLakeAnalyticsAccountPropertiesBasic + // The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. + FirewallAllowAzureIPs *FirewallAllowAzureIPsState `json:"firewallAllowAzureIps,omitempty"` + + // The current state of the IP address firewall for this account. + FirewallState *FirewallState `json:"firewallState,omitempty"` + + // The maximum supported degree of parallelism for this account. + MaxDegreeOfParallelism *int32 `json:"maxDegreeOfParallelism,omitempty"` + + // The maximum supported degree of parallelism per job for this account. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty"` + + // The maximum supported jobs running under the account at the same time. + MaxJobCount *int32 `json:"maxJobCount,omitempty"` + + // The commitment tier for the next month. + NewTier *TierType `json:"newTier,omitempty"` + + // The list of Data Lake Store accounts associated with this account. + PublicDataLakeStoreAccounts []*DataLakeStoreAccountInformation `json:"publicDataLakeStoreAccounts,omitempty"` + + // The number of days that job metadata is retained. + QueryStoreRetention *int32 `json:"queryStoreRetention,omitempty"` + + // READ-ONLY; The list of compute policies associated with this account. + ComputePolicies []*ComputePolicy `json:"computePolicies,omitempty" azure:"ro"` + + // READ-ONLY; The commitment tier in use for the current month. + CurrentTier *TierType `json:"currentTier,omitempty" azure:"ro"` + + // READ-ONLY; The list of Data Lake Store accounts associated with this account. + DataLakeStoreAccounts []*DataLakeStoreAccountInformation `json:"dataLakeStoreAccounts,omitempty" azure:"ro"` + + // READ-ONLY; The current state of the DebugDataAccessLevel for this account. + DebugDataAccessLevel *DebugDataAccessLevel `json:"debugDataAccessLevel,omitempty" azure:"ro"` + + // READ-ONLY; The default Data Lake Store account associated with this account. + DefaultDataLakeStoreAccount *string `json:"defaultDataLakeStoreAccount,omitempty" azure:"ro"` + + // READ-ONLY; The type of the default Data Lake Store account associated with this account. + DefaultDataLakeStoreAccountType *string `json:"defaultDataLakeStoreAccountType,omitempty" azure:"ro"` + + // READ-ONLY; The list of firewall rules associated with this account. + FirewallRules []*FirewallRule `json:"firewallRules,omitempty" azure:"ro"` + + // READ-ONLY; The list of hiveMetastores associated with this account. + HiveMetastores []*HiveMetastore `json:"hiveMetastores,omitempty" azure:"ro"` + + // READ-ONLY; The maximum supported active jobs under the account at the same time. + MaxActiveJobCountPerUser *int32 `json:"maxActiveJobCountPerUser,omitempty" azure:"ro"` + + // READ-ONLY; The maximum supported active jobs under the account at the same time. + MaxJobRunningTimeInMin *int32 `json:"maxJobRunningTimeInMin,omitempty" azure:"ro"` + + // READ-ONLY; The maximum supported jobs queued under the account at the same time. + MaxQueuedJobCountPerUser *int32 `json:"maxQueuedJobCountPerUser,omitempty" azure:"ro"` + + // READ-ONLY; The minimum supported priority per job for this account. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty" azure:"ro"` + + // READ-ONLY; The list of Azure Blob Storage accounts associated with this account. + StorageAccounts []*StorageAccountInformation `json:"storageAccounts,omitempty" azure:"ro"` + + // READ-ONLY; The system defined maximum supported degree of parallelism for this account, which restricts the maximum value of parallelism the user can + // set for the account. + SystemMaxDegreeOfParallelism *int32 `json:"systemMaxDegreeOfParallelism,omitempty" azure:"ro"` + + // READ-ONLY; The system defined maximum supported jobs running under the account at the same time, which restricts the maximum number of running jobs the + // user can set for the account. + SystemMaxJobCount *int32 `json:"systemMaxJobCount,omitempty" azure:"ro"` + + // READ-ONLY; The list of virtualNetwork rules associated with this account. + VirtualNetworkRules []*VirtualNetworkRule `json:"virtualNetworkRules,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeAnalyticsAccountProperties. +func (d DataLakeAnalyticsAccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.DataLakeAnalyticsAccountPropertiesBasic.marshalInternal(objectMap) + populate(objectMap, "computePolicies", d.ComputePolicies) + populate(objectMap, "currentTier", d.CurrentTier) + populate(objectMap, "dataLakeStoreAccounts", d.DataLakeStoreAccounts) + populate(objectMap, "debugDataAccessLevel", d.DebugDataAccessLevel) + populate(objectMap, "defaultDataLakeStoreAccount", d.DefaultDataLakeStoreAccount) + populate(objectMap, "defaultDataLakeStoreAccountType", d.DefaultDataLakeStoreAccountType) + populate(objectMap, "firewallAllowAzureIps", d.FirewallAllowAzureIPs) + populate(objectMap, "firewallRules", d.FirewallRules) + populate(objectMap, "firewallState", d.FirewallState) + populate(objectMap, "hiveMetastores", d.HiveMetastores) + populate(objectMap, "maxActiveJobCountPerUser", d.MaxActiveJobCountPerUser) + populate(objectMap, "maxDegreeOfParallelism", d.MaxDegreeOfParallelism) + populate(objectMap, "maxDegreeOfParallelismPerJob", d.MaxDegreeOfParallelismPerJob) + populate(objectMap, "maxJobCount", d.MaxJobCount) + populate(objectMap, "maxJobRunningTimeInMin", d.MaxJobRunningTimeInMin) + populate(objectMap, "maxQueuedJobCountPerUser", d.MaxQueuedJobCountPerUser) + populate(objectMap, "minPriorityPerJob", d.MinPriorityPerJob) + populate(objectMap, "newTier", d.NewTier) + populate(objectMap, "publicDataLakeStoreAccounts", d.PublicDataLakeStoreAccounts) + populate(objectMap, "queryStoreRetention", d.QueryStoreRetention) + populate(objectMap, "storageAccounts", d.StorageAccounts) + populate(objectMap, "systemMaxDegreeOfParallelism", d.SystemMaxDegreeOfParallelism) + populate(objectMap, "systemMaxJobCount", d.SystemMaxJobCount) + populate(objectMap, "virtualNetworkRules", d.VirtualNetworkRules) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataLakeAnalyticsAccountProperties. +func (d *DataLakeAnalyticsAccountProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "computePolicies": + err = unpopulate(val, &d.ComputePolicies) + delete(rawMsg, key) + case "currentTier": + err = unpopulate(val, &d.CurrentTier) + delete(rawMsg, key) + case "dataLakeStoreAccounts": + err = unpopulate(val, &d.DataLakeStoreAccounts) + delete(rawMsg, key) + case "debugDataAccessLevel": + err = unpopulate(val, &d.DebugDataAccessLevel) + delete(rawMsg, key) + case "defaultDataLakeStoreAccount": + err = unpopulate(val, &d.DefaultDataLakeStoreAccount) + delete(rawMsg, key) + case "defaultDataLakeStoreAccountType": + err = unpopulate(val, &d.DefaultDataLakeStoreAccountType) + delete(rawMsg, key) + case "firewallAllowAzureIps": + err = unpopulate(val, &d.FirewallAllowAzureIPs) + delete(rawMsg, key) + case "firewallRules": + err = unpopulate(val, &d.FirewallRules) + delete(rawMsg, key) + case "firewallState": + err = unpopulate(val, &d.FirewallState) + delete(rawMsg, key) + case "hiveMetastores": + err = unpopulate(val, &d.HiveMetastores) + delete(rawMsg, key) + case "maxActiveJobCountPerUser": + err = unpopulate(val, &d.MaxActiveJobCountPerUser) + delete(rawMsg, key) + case "maxDegreeOfParallelism": + err = unpopulate(val, &d.MaxDegreeOfParallelism) + delete(rawMsg, key) + case "maxDegreeOfParallelismPerJob": + err = unpopulate(val, &d.MaxDegreeOfParallelismPerJob) + delete(rawMsg, key) + case "maxJobCount": + err = unpopulate(val, &d.MaxJobCount) + delete(rawMsg, key) + case "maxJobRunningTimeInMin": + err = unpopulate(val, &d.MaxJobRunningTimeInMin) + delete(rawMsg, key) + case "maxQueuedJobCountPerUser": + err = unpopulate(val, &d.MaxQueuedJobCountPerUser) + delete(rawMsg, key) + case "minPriorityPerJob": + err = unpopulate(val, &d.MinPriorityPerJob) + delete(rawMsg, key) + case "newTier": + err = unpopulate(val, &d.NewTier) + delete(rawMsg, key) + case "publicDataLakeStoreAccounts": + err = unpopulate(val, &d.PublicDataLakeStoreAccounts) + delete(rawMsg, key) + case "queryStoreRetention": + err = unpopulate(val, &d.QueryStoreRetention) + delete(rawMsg, key) + case "storageAccounts": + err = unpopulate(val, &d.StorageAccounts) + delete(rawMsg, key) + case "systemMaxDegreeOfParallelism": + err = unpopulate(val, &d.SystemMaxDegreeOfParallelism) + delete(rawMsg, key) + case "systemMaxJobCount": + err = unpopulate(val, &d.SystemMaxJobCount) + delete(rawMsg, key) + case "virtualNetworkRules": + err = unpopulate(val, &d.VirtualNetworkRules) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := d.DataLakeAnalyticsAccountPropertiesBasic.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// DataLakeAnalyticsAccountPropertiesBasic - The basic account specific properties that are associated with an underlying Data Lake Analytics account. +type DataLakeAnalyticsAccountPropertiesBasic struct { + // READ-ONLY; The unique identifier associated with this Data Lake Analytics account. + AccountID *string `json:"accountId,omitempty" azure:"ro"` + + // READ-ONLY; The account creation time. + CreationTime *time.Time `json:"creationTime,omitempty" azure:"ro"` + + // READ-ONLY; The full CName endpoint for this account. + Endpoint *string `json:"endpoint,omitempty" azure:"ro"` + + // READ-ONLY; The account last modified time. + LastModifiedTime *time.Time `json:"lastModifiedTime,omitempty" azure:"ro"` + + // READ-ONLY; The provisioning status of the Data Lake Analytics account. + ProvisioningState *DataLakeAnalyticsAccountStatus `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The state of the Data Lake Analytics account. + State *DataLakeAnalyticsAccountState `json:"state,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeAnalyticsAccountPropertiesBasic. +func (d DataLakeAnalyticsAccountPropertiesBasic) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DataLakeAnalyticsAccountPropertiesBasic. +func (d *DataLakeAnalyticsAccountPropertiesBasic) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return d.unmarshalInternal(rawMsg) +} + +func (d DataLakeAnalyticsAccountPropertiesBasic) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "accountId", d.AccountID) + populate(objectMap, "creationTime", (*timeRFC3339)(d.CreationTime)) + populate(objectMap, "endpoint", d.Endpoint) + populate(objectMap, "lastModifiedTime", (*timeRFC3339)(d.LastModifiedTime)) + populate(objectMap, "provisioningState", d.ProvisioningState) + populate(objectMap, "state", d.State) +} + +func (d *DataLakeAnalyticsAccountPropertiesBasic) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "accountId": + err = unpopulate(val, &d.AccountID) + delete(rawMsg, key) + case "creationTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + d.CreationTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "endpoint": + err = unpopulate(val, &d.Endpoint) + delete(rawMsg, key) + case "lastModifiedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + d.LastModifiedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &d.ProvisioningState) + delete(rawMsg, key) + case "state": + err = unpopulate(val, &d.State) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// DataLakeStoreAccountInformation - Data Lake Store account information. +type DataLakeStoreAccountInformation struct { + SubResource + // The Data Lake Store account properties. + Properties *DataLakeStoreAccountInformationProperties `json:"properties,omitempty"` +} + +// DataLakeStoreAccountInformationListResult - Data Lake Store account list information. +type DataLakeStoreAccountInformationListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*DataLakeStoreAccountInformation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DataLakeStoreAccountInformationListResult. +func (d DataLakeStoreAccountInformationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// DataLakeStoreAccountInformationProperties - The Data Lake Store account properties. +type DataLakeStoreAccountInformationProperties struct { + // READ-ONLY; The optional suffix for the Data Lake Store account. + Suffix *string `json:"suffix,omitempty" azure:"ro"` +} + +// DataLakeStoreAccountsAddOptions contains the optional parameters for the DataLakeStoreAccounts.Add method. +type DataLakeStoreAccountsAddOptions struct { + // The details of the Data Lake Store account. + Parameters *AddDataLakeStoreParameters +} + +// DataLakeStoreAccountsDeleteOptions contains the optional parameters for the DataLakeStoreAccounts.Delete method. +type DataLakeStoreAccountsDeleteOptions struct { + // placeholder for future optional parameters +} + +// DataLakeStoreAccountsGetOptions contains the optional parameters for the DataLakeStoreAccounts.Get method. +type DataLakeStoreAccountsGetOptions struct { + // placeholder for future optional parameters +} + +// DataLakeStoreAccountsListByAccountOptions contains the optional parameters for the DataLakeStoreAccounts.ListByAccount method. +type DataLakeStoreAccountsListByAccountOptions struct { + // The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. + // Optional. + Count *bool + // OData filter. Optional. + Filter *string + // OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, + // e.g. Categories?$orderby=CategoryName desc. Optional. + Orderby *string + // OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. + Select *string + // The number of items to skip over before returning elements. Optional. + Skip *int32 + // The number of items to return. Optional. + Top *int32 +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info map[string]interface{} `json:"info,omitempty" azure:"ro"` + + // READ-ONLY; The additional info type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo `json:"additionalInfo,omitempty" azure:"ro"` + + // READ-ONLY; The error code. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; The error details. + Details []*ErrorDetail `json:"details,omitempty" azure:"ro"` + + // READ-ONLY; The error message. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The error target. + Target *string `json:"target,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponse - Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData +// error response format.). +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // The error object. + InnerError *ErrorDetail `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// FirewallRule - Data Lake Analytics firewall rule information. +type FirewallRule struct { + SubResource + // READ-ONLY; The firewall rule properties. + Properties *FirewallRuleProperties `json:"properties,omitempty" azure:"ro"` +} + +// FirewallRuleListResult - Data Lake Analytics firewall rule list information. +type FirewallRuleListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*FirewallRule `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type FirewallRuleListResult. +func (f FirewallRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// FirewallRuleProperties - The firewall rule properties. +type FirewallRuleProperties struct { + // READ-ONLY; The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + EndIPAddress *string `json:"endIpAddress,omitempty" azure:"ro"` + + // READ-ONLY; The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + StartIPAddress *string `json:"startIpAddress,omitempty" azure:"ro"` +} + +// FirewallRulesCreateOrUpdateOptions contains the optional parameters for the FirewallRules.CreateOrUpdate method. +type FirewallRulesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesDeleteOptions contains the optional parameters for the FirewallRules.Delete method. +type FirewallRulesDeleteOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesGetOptions contains the optional parameters for the FirewallRules.Get method. +type FirewallRulesGetOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesListByAccountOptions contains the optional parameters for the FirewallRules.ListByAccount method. +type FirewallRulesListByAccountOptions struct { + // placeholder for future optional parameters +} + +// FirewallRulesUpdateOptions contains the optional parameters for the FirewallRules.Update method. +type FirewallRulesUpdateOptions struct { + // Parameters supplied to update the firewall rule. + Parameters *UpdateFirewallRuleParameters +} + +type HiveMetastore struct { + SubResource + // READ-ONLY; The HiveMetastoreProperties rule properties. + Properties *HiveMetastoreProperties `json:"properties,omitempty" azure:"ro"` +} + +// HiveMetastoreListResult - Data Lake Analytics HiveMetastore list information. +type HiveMetastoreListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*HiveMetastore `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type HiveMetastoreListResult. +func (h HiveMetastoreListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", h.NextLink) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// HiveMetastoreProperties - The HiveMetastore properties. +type HiveMetastoreProperties struct { + // READ-ONLY; The databaseName for the Hive MetaStore + DatabaseName *string `json:"databaseName,omitempty" azure:"ro"` + + // READ-ONLY; The current state of the NestedResource + NestedResourceProvisioningState *NestedResourceProvisioningState `json:"nestedResourceProvisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The password for the Hive MetaStore + Password *string `json:"password,omitempty" azure:"ro"` + + // READ-ONLY; The runtimeVersion for the Hive MetaStore + RuntimeVersion *string `json:"runtimeVersion,omitempty" azure:"ro"` + + // READ-ONLY; The serverUri for the Hive MetaStore + ServerURI *string `json:"serverUri,omitempty" azure:"ro"` + + // READ-ONLY; The userName for the Hive MetaStore + UserName *string `json:"userName,omitempty" azure:"ro"` +} + +// LocationsGetCapabilityOptions contains the optional parameters for the Locations.GetCapability method. +type LocationsGetCapabilityOptions struct { + // placeholder for future optional parameters +} + +// NameAvailabilityInformation - Data Lake Analytics account name availability result information. +type NameAvailabilityInformation struct { + // READ-ONLY; The message describing why the Data Lake Analytics account name is not available, if nameAvailable is false. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The Boolean value of true or false to indicate whether the Data Lake Analytics account name is available or not. + NameAvailable *bool `json:"nameAvailable,omitempty" azure:"ro"` + + // READ-ONLY; The reason why the Data Lake Analytics account name is not available, if nameAvailable is false. + Reason *string `json:"reason,omitempty" azure:"ro"` +} + +// Operation - An available operation for Data Lake Analytics. +type Operation struct { + // READ-ONLY; The display information for the operation. + Display *OperationDisplay `json:"display,omitempty" azure:"ro"` + + // READ-ONLY; The name of the operation. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The intended executor of the operation. + Origin *OperationOrigin `json:"origin,omitempty" azure:"ro"` + + // READ-ONLY; The OperationMetaPropertyInfo for the operation. + Properties *OperationMetaPropertyInfo `json:"properties,omitempty" azure:"ro"` +} + +// OperationDisplay - The display information for a particular operation. +type OperationDisplay struct { + // READ-ONLY; A friendly description of the operation. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; A friendly name of the operation. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; The resource provider of the operation. + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; The resource type of the operation. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - The list of available operations for Data Lake Analytics. +type OperationListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +type OperationMetaLogSpecification struct { + // The blobDuration for OperationMetaLogSpecification. + BlobDuration *string `json:"blobDuration,omitempty"` + + // The displayName for OperationMetaLogSpecification. + DisplayName *string `json:"displayName,omitempty"` + + // The name for OperationMetaLogSpecification. + Name *string `json:"name,omitempty"` +} + +type OperationMetaMetricAvailabilitiesSpecification struct { + // The blobDuration for OperationMetaMetricAvailabilitiesSpecification. + BlobDuration *string `json:"blobDuration,omitempty"` + + // The timegrain for OperationMetaMetricAvailabilitiesSpecification. + TimeGrain *string `json:"timeGrain,omitempty"` +} + +type OperationMetaMetricSpecification struct { + // The aggregationType for OperationMetaMetricSpecification. + AggregationType *string `json:"aggregationType,omitempty"` + + // The availabilities for OperationMetaMetricSpecification. + Availabilities []*OperationMetaMetricAvailabilitiesSpecification `json:"availabilities,omitempty"` + + // The displayName for OperationMetaMetricSpecification. + DisplayDescription *string `json:"displayDescription,omitempty"` + + // The displayName for OperationMetaMetricSpecification. + DisplayName *string `json:"displayName,omitempty"` + + // The name for OperationMetaMetricSpecification. + Name *string `json:"name,omitempty"` + + // The unit for OperationMetaMetricSpecification. + Unit *string `json:"unit,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationMetaMetricSpecification. +func (o OperationMetaMetricSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "aggregationType", o.AggregationType) + populate(objectMap, "availabilities", o.Availabilities) + populate(objectMap, "displayDescription", o.DisplayDescription) + populate(objectMap, "displayName", o.DisplayName) + populate(objectMap, "name", o.Name) + populate(objectMap, "unit", o.Unit) + return json.Marshal(objectMap) +} + +type OperationMetaPropertyInfo struct { + // The operations OperationMetaServiceSpecification. + ServiceSpecification *OperationMetaServiceSpecification `json:"serviceSpecification,omitempty"` +} + +type OperationMetaServiceSpecification struct { + // The logSpecifications for OperationMetaServiceSpecification. + LogSpecifications []*OperationMetaLogSpecification `json:"logSpecifications,omitempty"` + + // The metricSpecifications for OperationMetaServiceSpecification. + MetricSpecifications []*OperationMetaMetricSpecification `json:"metricSpecifications,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationMetaServiceSpecification. +func (o OperationMetaServiceSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "logSpecifications", o.LogSpecifications) + populate(objectMap, "metricSpecifications", o.MetricSpecifications) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// Resource - The resource model definition. +type Resource struct { + // READ-ONLY; The resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The resource location. + Location *string `json:"location,omitempty" azure:"ro"` + + // READ-ONLY; The resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The resource tags. + Tags map[string]*string `json:"tags,omitempty" azure:"ro"` + + // READ-ONLY; The resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) +} + +// SasTokenInformation - SAS token information. +type SasTokenInformation struct { + // READ-ONLY; The access token for the associated Azure Storage Container. + AccessToken *string `json:"accessToken,omitempty" azure:"ro"` +} + +// SasTokenInformationListResult - The SAS response that contains the storage account, container and associated SAS token for connection use. +type SasTokenInformationListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*SasTokenInformation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SasTokenInformationListResult. +func (s SasTokenInformationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StorageAccountInformation - Azure Storage account information. +type StorageAccountInformation struct { + SubResource + // READ-ONLY; The Azure Storage account properties. + Properties *StorageAccountInformationProperties `json:"properties,omitempty" azure:"ro"` +} + +// StorageAccountInformationListResult - Azure Storage account list information. +type StorageAccountInformationListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*StorageAccountInformation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StorageAccountInformationListResult. +func (s StorageAccountInformationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StorageAccountInformationProperties - The Azure Storage account properties. +type StorageAccountInformationProperties struct { + // READ-ONLY; The optional suffix for the storage account. + Suffix *string `json:"suffix,omitempty" azure:"ro"` +} + +// StorageAccountsAddOptions contains the optional parameters for the StorageAccounts.Add method. +type StorageAccountsAddOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsDeleteOptions contains the optional parameters for the StorageAccounts.Delete method. +type StorageAccountsDeleteOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsGetOptions contains the optional parameters for the StorageAccounts.Get method. +type StorageAccountsGetOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsGetStorageContainerOptions contains the optional parameters for the StorageAccounts.GetStorageContainer method. +type StorageAccountsGetStorageContainerOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsListByAccountOptions contains the optional parameters for the StorageAccounts.ListByAccount method. +type StorageAccountsListByAccountOptions struct { + // The Boolean value of true or false to request a count of the matching resources included with the resources in the response, e.g. Categories?$count=true. + // Optional. + Count *bool + // The OData filter. Optional. + Filter *string + // OrderBy clause. One or more comma-separated expressions with an optional "asc" (the default) or "desc" depending on the order you'd like the values sorted, + // e.g. Categories?$orderby=CategoryName desc. Optional. + Orderby *string + // OData Select statement. Limits the properties on each entry to just those requested, e.g. Categories?$select=CategoryName,Description. Optional. + Select *string + // The number of items to skip over before returning elements. Optional. + Skip *int32 + // The number of items to return. Optional. + Top *int32 +} + +// StorageAccountsListSasTokensOptions contains the optional parameters for the StorageAccounts.ListSasTokens method. +type StorageAccountsListSasTokensOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsListStorageContainersOptions contains the optional parameters for the StorageAccounts.ListStorageContainers method. +type StorageAccountsListStorageContainersOptions struct { + // placeholder for future optional parameters +} + +// StorageAccountsUpdateOptions contains the optional parameters for the StorageAccounts.Update method. +type StorageAccountsUpdateOptions struct { + // The parameters containing the access key and suffix to update the storage account with, if any. Passing nothing results in no change. + Parameters *UpdateStorageAccountParameters +} + +// StorageContainer - Azure Storage blob container information. +type StorageContainer struct { + SubResource + // READ-ONLY; The properties of the blob container. + Properties *StorageContainerProperties `json:"properties,omitempty" azure:"ro"` +} + +// StorageContainerListResult - The list of blob containers associated with the storage account attached to the Data Lake Analytics account. +type StorageContainerListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*StorageContainer `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StorageContainerListResult. +func (s StorageContainerListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StorageContainerProperties - Azure Storage blob container properties information. +type StorageContainerProperties struct { + // READ-ONLY; The last modified time of the blob container. + LastModifiedTime *time.Time `json:"lastModifiedTime,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StorageContainerProperties. +func (s StorageContainerProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "lastModifiedTime", (*timeRFC3339)(s.LastModifiedTime)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageContainerProperties. +func (s *StorageContainerProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "lastModifiedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedTime = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// SubResource - The resource model definition for a nested resource. +type SubResource struct { + // READ-ONLY; The resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// UpdateComputePolicyParameters - The parameters used to update a compute policy. +type UpdateComputePolicyParameters struct { + // The compute policy properties to use when updating a compute policy. + Properties *UpdateComputePolicyProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateComputePolicyParameters. +func (u UpdateComputePolicyParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", u.Properties) + return json.Marshal(objectMap) +} + +// UpdateComputePolicyProperties - The compute policy properties to use when updating a compute policy. +type UpdateComputePolicyProperties struct { + // The maximum degree of parallelism per job this user can use to submit jobs. This property, the min priority per job property, or both must be passed. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty"` + + // The minimum priority per job this user can use to submit jobs. This property, the max degree of parallelism per job property, or both must be passed. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty"` + + // The AAD object identifier for the entity to create a policy for. + ObjectID *string `json:"objectId,omitempty"` + + // The type of AAD object the object identifier refers to. + ObjectType *AADObjectType `json:"objectType,omitempty"` +} + +// UpdateComputePolicyWithAccountParameters - The parameters used to update a compute policy while updating a Data Lake Analytics account. +type UpdateComputePolicyWithAccountParameters struct { + // REQUIRED; The unique name of the compute policy to update. + Name *string `json:"name,omitempty"` + + // The compute policy properties to use when updating a compute policy. + Properties *UpdateComputePolicyProperties `json:"properties,omitempty"` +} + +// UpdateDataLakeAnalyticsAccountParameters - The parameters that can be used to update an existing Data Lake Analytics account. +type UpdateDataLakeAnalyticsAccountParameters struct { + // The properties that can be updated in an existing Data Lake Analytics account. + Properties *UpdateDataLakeAnalyticsAccountProperties `json:"properties,omitempty"` + + // The resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateDataLakeAnalyticsAccountParameters. +func (u UpdateDataLakeAnalyticsAccountParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", u.Properties) + populate(objectMap, "tags", u.Tags) + return json.Marshal(objectMap) +} + +// UpdateDataLakeAnalyticsAccountProperties - The properties to update that are associated with an underlying Data Lake Analytics account. +type UpdateDataLakeAnalyticsAccountProperties struct { + // The list of compute policies associated with this account. + ComputePolicies []*UpdateComputePolicyWithAccountParameters `json:"computePolicies,omitempty"` + + // The list of Data Lake Store accounts associated with this account. + DataLakeStoreAccounts []*UpdateDataLakeStoreWithAccountParameters `json:"dataLakeStoreAccounts,omitempty"` + + // The current state of allowing or disallowing IPs originating within Azure through the firewall. If the firewall is disabled, this is not enforced. + FirewallAllowAzureIPs *FirewallAllowAzureIPsState `json:"firewallAllowAzureIps,omitempty"` + + // The list of firewall rules associated with this account. + FirewallRules []*UpdateFirewallRuleWithAccountParameters `json:"firewallRules,omitempty"` + + // The current state of the IP address firewall for this account. Disabling the firewall does not remove existing rules, they will just be ignored until + // the firewall is re-enabled. + FirewallState *FirewallState `json:"firewallState,omitempty"` + + // The maximum supported degree of parallelism for this account. + MaxDegreeOfParallelism *int32 `json:"maxDegreeOfParallelism,omitempty"` + + // The maximum supported degree of parallelism per job for this account. + MaxDegreeOfParallelismPerJob *int32 `json:"maxDegreeOfParallelismPerJob,omitempty"` + + // The maximum supported jobs running under the account at the same time. + MaxJobCount *int32 `json:"maxJobCount,omitempty"` + + // The minimum supported priority per job for this account. + MinPriorityPerJob *int32 `json:"minPriorityPerJob,omitempty"` + + // The commitment tier to use for next month. + NewTier *TierType `json:"newTier,omitempty"` + + // The number of days that job metadata is retained. + QueryStoreRetention *int32 `json:"queryStoreRetention,omitempty"` + + // The list of Azure Blob storage accounts associated with this account. + StorageAccounts []*UpdateStorageAccountWithAccountParameters `json:"storageAccounts,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateDataLakeAnalyticsAccountProperties. +func (u UpdateDataLakeAnalyticsAccountProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "computePolicies", u.ComputePolicies) + populate(objectMap, "dataLakeStoreAccounts", u.DataLakeStoreAccounts) + populate(objectMap, "firewallAllowAzureIps", u.FirewallAllowAzureIPs) + populate(objectMap, "firewallRules", u.FirewallRules) + populate(objectMap, "firewallState", u.FirewallState) + populate(objectMap, "maxDegreeOfParallelism", u.MaxDegreeOfParallelism) + populate(objectMap, "maxDegreeOfParallelismPerJob", u.MaxDegreeOfParallelismPerJob) + populate(objectMap, "maxJobCount", u.MaxJobCount) + populate(objectMap, "minPriorityPerJob", u.MinPriorityPerJob) + populate(objectMap, "newTier", u.NewTier) + populate(objectMap, "queryStoreRetention", u.QueryStoreRetention) + populate(objectMap, "storageAccounts", u.StorageAccounts) + return json.Marshal(objectMap) +} + +// UpdateDataLakeStoreProperties - The Data Lake Store account properties to use when updating a Data Lake Store account. +type UpdateDataLakeStoreProperties struct { + // The optional suffix for the Data Lake Store account. + Suffix *string `json:"suffix,omitempty"` +} + +// UpdateDataLakeStoreWithAccountParameters - The parameters used to update a Data Lake Store account while updating a Data Lake Analytics account. +type UpdateDataLakeStoreWithAccountParameters struct { + // REQUIRED; The unique name of the Data Lake Store account to update. + Name *string `json:"name,omitempty"` + + // The Data Lake Store account properties to use when updating a Data Lake Store account. + Properties *UpdateDataLakeStoreProperties `json:"properties,omitempty"` +} + +// UpdateFirewallRuleParameters - The parameters used to update a firewall rule. +type UpdateFirewallRuleParameters struct { + // The firewall rule properties to use when updating a firewall rule. + Properties *UpdateFirewallRuleProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateFirewallRuleParameters. +func (u UpdateFirewallRuleParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", u.Properties) + return json.Marshal(objectMap) +} + +// UpdateFirewallRuleProperties - The firewall rule properties to use when updating a firewall rule. +type UpdateFirewallRuleProperties struct { + // The end IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + EndIPAddress *string `json:"endIpAddress,omitempty"` + + // The start IP address for the firewall rule. This can be either ipv4 or ipv6. Start and End should be in the same protocol. + StartIPAddress *string `json:"startIpAddress,omitempty"` +} + +// UpdateFirewallRuleWithAccountParameters - The parameters used to update a firewall rule while updating a Data Lake Analytics account. +type UpdateFirewallRuleWithAccountParameters struct { + // REQUIRED; The unique name of the firewall rule to update. + Name *string `json:"name,omitempty"` + + // The firewall rule properties to use when updating a firewall rule. + Properties *UpdateFirewallRuleProperties `json:"properties,omitempty"` +} + +// UpdateStorageAccountParameters - The parameters used to update an Azure Storage account. +type UpdateStorageAccountParameters struct { + // The Azure Storage account properties to use when updating an Azure Storage account. + Properties *UpdateStorageAccountProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UpdateStorageAccountParameters. +func (u UpdateStorageAccountParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", u.Properties) + return json.Marshal(objectMap) +} + +// UpdateStorageAccountProperties - The Azure Storage account properties to use when updating an Azure Storage account. +type UpdateStorageAccountProperties struct { + // The updated access key associated with this Azure Storage account that will be used to connect to it. + AccessKey *string `json:"accessKey,omitempty"` + + // The optional suffix for the storage account. + Suffix *string `json:"suffix,omitempty"` +} + +// UpdateStorageAccountWithAccountParameters - The parameters used to update an Azure Storage account while updating a Data Lake Analytics account. +type UpdateStorageAccountWithAccountParameters struct { + // REQUIRED; The unique name of the Azure Storage account to update. + Name *string `json:"name,omitempty"` + + // The Azure Storage account properties to use when updating an Azure Storage account. + Properties *UpdateStorageAccountProperties `json:"properties,omitempty"` +} + +// VirtualNetworkRule - Data Lake Analytics VirtualNetwork Rule information. +type VirtualNetworkRule struct { + SubResource + // READ-ONLY; The VirtualNetwork rule properties. + Properties *VirtualNetworkRuleProperties `json:"properties,omitempty" azure:"ro"` +} + +// VirtualNetworkRuleListResult - Data Lake Analytics VirtualNetwork rule list information. +type VirtualNetworkRuleListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The results of the list operation. + Value []*VirtualNetworkRule `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type VirtualNetworkRuleListResult. +func (v VirtualNetworkRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", v.NextLink) + populate(objectMap, "value", v.Value) + return json.Marshal(objectMap) +} + +// VirtualNetworkRuleProperties - The VirtualNetwork Rule properties. +type VirtualNetworkRuleProperties struct { + // READ-ONLY; The resource identifier for the subnet + SubnetID *string `json:"subnetId,omitempty" azure:"ro"` + + // READ-ONLY; The current state of the VirtualNetwork Rule + VirtualNetworkRuleState *VirtualNetworkRuleState `json:"virtualNetworkRuleState,omitempty" azure:"ro"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_operations_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_operations_client.go new file mode 100644 index 000000000000..31367720a412 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_operations_client.go @@ -0,0 +1,84 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available Data Lake Analytics REST API operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(ctx context.Context, options *OperationsListOptions) (OperationsListResponse, error) { + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OperationsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OperationsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.DataLakeAnalytics/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pagers.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pagers.go new file mode 100644 index 000000000000..914c4731a853 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pagers.go @@ -0,0 +1,450 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountsListByResourceGroupPager provides operations for iterating over paged responses. +type AccountsListByResourceGroupPager struct { + client *AccountsClient + current AccountsListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AccountsListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AccountsListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AccountsListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.DataLakeAnalyticsAccountListResult.NextLink == nil || len(*p.current.DataLakeAnalyticsAccountListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AccountsListByResourceGroupResponse page. +func (p *AccountsListByResourceGroupPager) PageResponse() AccountsListByResourceGroupResponse { + return p.current +} + +// AccountsListPager provides operations for iterating over paged responses. +type AccountsListPager struct { + client *AccountsClient + current AccountsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AccountsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AccountsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AccountsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.DataLakeAnalyticsAccountListResult.NextLink == nil || len(*p.current.DataLakeAnalyticsAccountListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AccountsListResponse page. +func (p *AccountsListPager) PageResponse() AccountsListResponse { + return p.current +} + +// ComputePoliciesListByAccountPager provides operations for iterating over paged responses. +type ComputePoliciesListByAccountPager struct { + client *ComputePoliciesClient + current ComputePoliciesListByAccountResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ComputePoliciesListByAccountResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ComputePoliciesListByAccountPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ComputePoliciesListByAccountPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ComputePolicyListResult.NextLink == nil || len(*p.current.ComputePolicyListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByAccountHandleError(resp) + return false + } + result, err := p.client.listByAccountHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ComputePoliciesListByAccountResponse page. +func (p *ComputePoliciesListByAccountPager) PageResponse() ComputePoliciesListByAccountResponse { + return p.current +} + +// DataLakeStoreAccountsListByAccountPager provides operations for iterating over paged responses. +type DataLakeStoreAccountsListByAccountPager struct { + client *DataLakeStoreAccountsClient + current DataLakeStoreAccountsListByAccountResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, DataLakeStoreAccountsListByAccountResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *DataLakeStoreAccountsListByAccountPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *DataLakeStoreAccountsListByAccountPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.DataLakeStoreAccountInformationListResult.NextLink == nil || len(*p.current.DataLakeStoreAccountInformationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByAccountHandleError(resp) + return false + } + result, err := p.client.listByAccountHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current DataLakeStoreAccountsListByAccountResponse page. +func (p *DataLakeStoreAccountsListByAccountPager) PageResponse() DataLakeStoreAccountsListByAccountResponse { + return p.current +} + +// FirewallRulesListByAccountPager provides operations for iterating over paged responses. +type FirewallRulesListByAccountPager struct { + client *FirewallRulesClient + current FirewallRulesListByAccountResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, FirewallRulesListByAccountResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *FirewallRulesListByAccountPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *FirewallRulesListByAccountPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.FirewallRuleListResult.NextLink == nil || len(*p.current.FirewallRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByAccountHandleError(resp) + return false + } + result, err := p.client.listByAccountHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current FirewallRulesListByAccountResponse page. +func (p *FirewallRulesListByAccountPager) PageResponse() FirewallRulesListByAccountResponse { + return p.current +} + +// StorageAccountsListByAccountPager provides operations for iterating over paged responses. +type StorageAccountsListByAccountPager struct { + client *StorageAccountsClient + current StorageAccountsListByAccountResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StorageAccountsListByAccountResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StorageAccountsListByAccountPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StorageAccountsListByAccountPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StorageAccountInformationListResult.NextLink == nil || len(*p.current.StorageAccountInformationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByAccountHandleError(resp) + return false + } + result, err := p.client.listByAccountHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StorageAccountsListByAccountResponse page. +func (p *StorageAccountsListByAccountPager) PageResponse() StorageAccountsListByAccountResponse { + return p.current +} + +// StorageAccountsListSasTokensPager provides operations for iterating over paged responses. +type StorageAccountsListSasTokensPager struct { + client *StorageAccountsClient + current StorageAccountsListSasTokensResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StorageAccountsListSasTokensResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StorageAccountsListSasTokensPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StorageAccountsListSasTokensPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SasTokenInformationListResult.NextLink == nil || len(*p.current.SasTokenInformationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listSasTokensHandleError(resp) + return false + } + result, err := p.client.listSasTokensHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StorageAccountsListSasTokensResponse page. +func (p *StorageAccountsListSasTokensPager) PageResponse() StorageAccountsListSasTokensResponse { + return p.current +} + +// StorageAccountsListStorageContainersPager provides operations for iterating over paged responses. +type StorageAccountsListStorageContainersPager struct { + client *StorageAccountsClient + current StorageAccountsListStorageContainersResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StorageAccountsListStorageContainersResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StorageAccountsListStorageContainersPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StorageAccountsListStorageContainersPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StorageContainerListResult.NextLink == nil || len(*p.current.StorageContainerListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listStorageContainersHandleError(resp) + return false + } + result, err := p.client.listStorageContainersHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StorageAccountsListStorageContainersResponse page. +func (p *StorageAccountsListStorageContainersPager) PageResponse() StorageAccountsListStorageContainersResponse { + return p.current +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pollers.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pollers.go new file mode 100644 index 000000000000..28b75d90dffa --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_pollers.go @@ -0,0 +1,145 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AccountsCreatePoller provides polling facilities until the operation reaches a terminal state. +type AccountsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsCreateResponse will be returned. +func (p *AccountsCreatePoller) FinalResponse(ctx context.Context) (AccountsCreateResponse, error) { + respType := AccountsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.DataLakeAnalyticsAccount) + if err != nil { + return AccountsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// AccountsDeletePoller provides polling facilities until the operation reaches a terminal state. +type AccountsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsDeleteResponse will be returned. +func (p *AccountsDeletePoller) FinalResponse(ctx context.Context) (AccountsDeleteResponse, error) { + respType := AccountsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return AccountsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// AccountsUpdatePoller provides polling facilities until the operation reaches a terminal state. +type AccountsUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *AccountsUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *AccountsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final AccountsUpdateResponse will be returned. +func (p *AccountsUpdatePoller) FinalResponse(ctx context.Context) (AccountsUpdateResponse, error) { + respType := AccountsUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.DataLakeAnalyticsAccount) + if err != nil { + return AccountsUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *AccountsUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_response_types.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_response_types.go new file mode 100644 index 000000000000..d2850eebf94c --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_response_types.go @@ -0,0 +1,455 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// AccountsCheckNameAvailabilityResponse contains the response from method Accounts.CheckNameAvailability. +type AccountsCheckNameAvailabilityResponse struct { + AccountsCheckNameAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsCheckNameAvailabilityResult contains the result from method Accounts.CheckNameAvailability. +type AccountsCheckNameAvailabilityResult struct { + NameAvailabilityInformation +} + +// AccountsCreatePollerResponse contains the response from method Accounts.Create. +type AccountsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsCreateResponse, error) { + respType := AccountsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.DataLakeAnalyticsAccount) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsCreatePollerResponse from the provided client and resume token. +func (l *AccountsCreatePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &AccountsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsCreateResponse contains the response from method Accounts.Create. +type AccountsCreateResponse struct { + AccountsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsCreateResult contains the result from method Accounts.Create. +type AccountsCreateResult struct { + DataLakeAnalyticsAccount +} + +// AccountsDeletePollerResponse contains the response from method Accounts.Delete. +type AccountsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsDeleteResponse, error) { + respType := AccountsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsDeletePollerResponse from the provided client and resume token. +func (l *AccountsDeletePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &AccountsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsDeleteResponse contains the response from method Accounts.Delete. +type AccountsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsGetResponse contains the response from method Accounts.Get. +type AccountsGetResponse struct { + AccountsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsGetResult contains the result from method Accounts.Get. +type AccountsGetResult struct { + DataLakeAnalyticsAccount +} + +// AccountsListByResourceGroupResponse contains the response from method Accounts.ListByResourceGroup. +type AccountsListByResourceGroupResponse struct { + AccountsListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListByResourceGroupResult contains the result from method Accounts.ListByResourceGroup. +type AccountsListByResourceGroupResult struct { + DataLakeAnalyticsAccountListResult +} + +// AccountsListResponse contains the response from method Accounts.List. +type AccountsListResponse struct { + AccountsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsListResult contains the result from method Accounts.List. +type AccountsListResult struct { + DataLakeAnalyticsAccountListResult +} + +// AccountsUpdatePollerResponse contains the response from method Accounts.Update. +type AccountsUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *AccountsUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l AccountsUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (AccountsUpdateResponse, error) { + respType := AccountsUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.DataLakeAnalyticsAccount) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a AccountsUpdatePollerResponse from the provided client and resume token. +func (l *AccountsUpdatePollerResponse) Resume(ctx context.Context, client *AccountsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("AccountsClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &AccountsUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// AccountsUpdateResponse contains the response from method Accounts.Update. +type AccountsUpdateResponse struct { + AccountsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountsUpdateResult contains the result from method Accounts.Update. +type AccountsUpdateResult struct { + DataLakeAnalyticsAccount +} + +// ComputePoliciesCreateOrUpdateResponse contains the response from method ComputePolicies.CreateOrUpdate. +type ComputePoliciesCreateOrUpdateResponse struct { + ComputePoliciesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ComputePoliciesCreateOrUpdateResult contains the result from method ComputePolicies.CreateOrUpdate. +type ComputePoliciesCreateOrUpdateResult struct { + ComputePolicy +} + +// ComputePoliciesDeleteResponse contains the response from method ComputePolicies.Delete. +type ComputePoliciesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ComputePoliciesGetResponse contains the response from method ComputePolicies.Get. +type ComputePoliciesGetResponse struct { + ComputePoliciesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ComputePoliciesGetResult contains the result from method ComputePolicies.Get. +type ComputePoliciesGetResult struct { + ComputePolicy +} + +// ComputePoliciesListByAccountResponse contains the response from method ComputePolicies.ListByAccount. +type ComputePoliciesListByAccountResponse struct { + ComputePoliciesListByAccountResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ComputePoliciesListByAccountResult contains the result from method ComputePolicies.ListByAccount. +type ComputePoliciesListByAccountResult struct { + ComputePolicyListResult +} + +// ComputePoliciesUpdateResponse contains the response from method ComputePolicies.Update. +type ComputePoliciesUpdateResponse struct { + ComputePoliciesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ComputePoliciesUpdateResult contains the result from method ComputePolicies.Update. +type ComputePoliciesUpdateResult struct { + ComputePolicy +} + +// DataLakeStoreAccountsAddResponse contains the response from method DataLakeStoreAccounts.Add. +type DataLakeStoreAccountsAddResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DataLakeStoreAccountsDeleteResponse contains the response from method DataLakeStoreAccounts.Delete. +type DataLakeStoreAccountsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DataLakeStoreAccountsGetResponse contains the response from method DataLakeStoreAccounts.Get. +type DataLakeStoreAccountsGetResponse struct { + DataLakeStoreAccountsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DataLakeStoreAccountsGetResult contains the result from method DataLakeStoreAccounts.Get. +type DataLakeStoreAccountsGetResult struct { + DataLakeStoreAccountInformation +} + +// DataLakeStoreAccountsListByAccountResponse contains the response from method DataLakeStoreAccounts.ListByAccount. +type DataLakeStoreAccountsListByAccountResponse struct { + DataLakeStoreAccountsListByAccountResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// DataLakeStoreAccountsListByAccountResult contains the result from method DataLakeStoreAccounts.ListByAccount. +type DataLakeStoreAccountsListByAccountResult struct { + DataLakeStoreAccountInformationListResult +} + +// FirewallRulesCreateOrUpdateResponse contains the response from method FirewallRules.CreateOrUpdate. +type FirewallRulesCreateOrUpdateResponse struct { + FirewallRulesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FirewallRulesCreateOrUpdateResult contains the result from method FirewallRules.CreateOrUpdate. +type FirewallRulesCreateOrUpdateResult struct { + FirewallRule +} + +// FirewallRulesDeleteResponse contains the response from method FirewallRules.Delete. +type FirewallRulesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FirewallRulesGetResponse contains the response from method FirewallRules.Get. +type FirewallRulesGetResponse struct { + FirewallRulesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FirewallRulesGetResult contains the result from method FirewallRules.Get. +type FirewallRulesGetResult struct { + FirewallRule +} + +// FirewallRulesListByAccountResponse contains the response from method FirewallRules.ListByAccount. +type FirewallRulesListByAccountResponse struct { + FirewallRulesListByAccountResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FirewallRulesListByAccountResult contains the result from method FirewallRules.ListByAccount. +type FirewallRulesListByAccountResult struct { + FirewallRuleListResult +} + +// FirewallRulesUpdateResponse contains the response from method FirewallRules.Update. +type FirewallRulesUpdateResponse struct { + FirewallRulesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FirewallRulesUpdateResult contains the result from method FirewallRules.Update. +type FirewallRulesUpdateResult struct { + FirewallRule +} + +// LocationsGetCapabilityResponse contains the response from method Locations.GetCapability. +type LocationsGetCapabilityResponse struct { + LocationsGetCapabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LocationsGetCapabilityResult contains the result from method Locations.GetCapability. +type LocationsGetCapabilityResult struct { + CapabilityInformation +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// StorageAccountsAddResponse contains the response from method StorageAccounts.Add. +type StorageAccountsAddResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsDeleteResponse contains the response from method StorageAccounts.Delete. +type StorageAccountsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsGetResponse contains the response from method StorageAccounts.Get. +type StorageAccountsGetResponse struct { + StorageAccountsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsGetResult contains the result from method StorageAccounts.Get. +type StorageAccountsGetResult struct { + StorageAccountInformation +} + +// StorageAccountsGetStorageContainerResponse contains the response from method StorageAccounts.GetStorageContainer. +type StorageAccountsGetStorageContainerResponse struct { + StorageAccountsGetStorageContainerResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsGetStorageContainerResult contains the result from method StorageAccounts.GetStorageContainer. +type StorageAccountsGetStorageContainerResult struct { + StorageContainer +} + +// StorageAccountsListByAccountResponse contains the response from method StorageAccounts.ListByAccount. +type StorageAccountsListByAccountResponse struct { + StorageAccountsListByAccountResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsListByAccountResult contains the result from method StorageAccounts.ListByAccount. +type StorageAccountsListByAccountResult struct { + StorageAccountInformationListResult +} + +// StorageAccountsListSasTokensResponse contains the response from method StorageAccounts.ListSasTokens. +type StorageAccountsListSasTokensResponse struct { + StorageAccountsListSasTokensResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsListSasTokensResult contains the result from method StorageAccounts.ListSasTokens. +type StorageAccountsListSasTokensResult struct { + SasTokenInformationListResult +} + +// StorageAccountsListStorageContainersResponse contains the response from method StorageAccounts.ListStorageContainers. +type StorageAccountsListStorageContainersResponse struct { + StorageAccountsListStorageContainersResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StorageAccountsListStorageContainersResult contains the result from method StorageAccounts.ListStorageContainers. +type StorageAccountsListStorageContainersResult struct { + StorageContainerListResult +} + +// StorageAccountsUpdateResponse contains the response from method StorageAccounts.Update. +type StorageAccountsUpdateResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_storageaccounts_client.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_storageaccounts_client.go new file mode 100644 index 000000000000..be4b56f7d51e --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_storageaccounts_client.go @@ -0,0 +1,579 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// StorageAccountsClient contains the methods for the StorageAccounts group. +// Don't use this type directly, use NewStorageAccountsClient() instead. +type StorageAccountsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewStorageAccountsClient creates a new instance of StorageAccountsClient with the specified values. +func NewStorageAccountsClient(con *arm.Connection, subscriptionID string) *StorageAccountsClient { + return &StorageAccountsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Add - Updates the specified Data Lake Analytics account to add an Azure Storage account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) Add(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, parameters AddStorageAccountParameters, options *StorageAccountsAddOptions) (StorageAccountsAddResponse, error) { + req, err := client.addCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, parameters, options) + if err != nil { + return StorageAccountsAddResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StorageAccountsAddResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StorageAccountsAddResponse{}, client.addHandleError(resp) + } + return StorageAccountsAddResponse{RawResponse: resp}, nil +} + +// addCreateRequest creates the Add request. +func (client *StorageAccountsClient) addCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, parameters AddStorageAccountParameters, options *StorageAccountsAddOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// addHandleError handles the Add error response. +func (client *StorageAccountsClient) addHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Updates the specified Data Lake Analytics account to remove an Azure Storage account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsDeleteOptions) (StorageAccountsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, options) + if err != nil { + return StorageAccountsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StorageAccountsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StorageAccountsDeleteResponse{}, client.deleteHandleError(resp) + } + return StorageAccountsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StorageAccountsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *StorageAccountsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the specified Azure Storage account linked to the given Data Lake Analytics account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) Get(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsGetOptions) (StorageAccountsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, options) + if err != nil { + return StorageAccountsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StorageAccountsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StorageAccountsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *StorageAccountsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StorageAccountsClient) getHandleResponse(resp *http.Response) (StorageAccountsGetResponse, error) { + result := StorageAccountsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageAccountInformation); err != nil { + return StorageAccountsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *StorageAccountsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetStorageContainer - Gets the specified Azure Storage container associated with the given Data Lake Analytics and Azure Storage accounts. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) GetStorageContainer(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, containerName string, options *StorageAccountsGetStorageContainerOptions) (StorageAccountsGetStorageContainerResponse, error) { + req, err := client.getStorageContainerCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, containerName, options) + if err != nil { + return StorageAccountsGetStorageContainerResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StorageAccountsGetStorageContainerResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StorageAccountsGetStorageContainerResponse{}, client.getStorageContainerHandleError(resp) + } + return client.getStorageContainerHandleResponse(resp) +} + +// getStorageContainerCreateRequest creates the GetStorageContainer request. +func (client *StorageAccountsClient) getStorageContainerCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, containerName string, options *StorageAccountsGetStorageContainerOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}/containers/{containerName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getStorageContainerHandleResponse handles the GetStorageContainer response. +func (client *StorageAccountsClient) getStorageContainerHandleResponse(resp *http.Response) (StorageAccountsGetStorageContainerResponse, error) { + result := StorageAccountsGetStorageContainerResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageContainer); err != nil { + return StorageAccountsGetStorageContainerResponse{}, err + } + return result, nil +} + +// getStorageContainerHandleError handles the GetStorageContainer error response. +func (client *StorageAccountsClient) getStorageContainerHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByAccount - Gets the first page of Azure Storage accounts, if any, linked to the specified Data Lake Analytics account. The response includes a link +// to the next page, if any. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) ListByAccount(resourceGroupName string, accountName string, options *StorageAccountsListByAccountOptions) *StorageAccountsListByAccountPager { + return &StorageAccountsListByAccountPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByAccountCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp StorageAccountsListByAccountResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StorageAccountInformationListResult.NextLink) + }, + } +} + +// listByAccountCreateRequest creates the ListByAccount request. +func (client *StorageAccountsClient) listByAccountCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *StorageAccountsListByAccountOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + if options != nil && options.Count != nil { + reqQP.Set("$count", strconv.FormatBool(*options.Count)) + } + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByAccountHandleResponse handles the ListByAccount response. +func (client *StorageAccountsClient) listByAccountHandleResponse(resp *http.Response) (StorageAccountsListByAccountResponse, error) { + result := StorageAccountsListByAccountResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageAccountInformationListResult); err != nil { + return StorageAccountsListByAccountResponse{}, err + } + return result, nil +} + +// listByAccountHandleError handles the ListByAccount error response. +func (client *StorageAccountsClient) listByAccountHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListSasTokens - Gets the SAS token associated with the specified Data Lake Analytics and Azure Storage account and container combination. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) ListSasTokens(resourceGroupName string, accountName string, storageAccountName string, containerName string, options *StorageAccountsListSasTokensOptions) *StorageAccountsListSasTokensPager { + return &StorageAccountsListSasTokensPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listSasTokensCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, containerName, options) + }, + advancer: func(ctx context.Context, resp StorageAccountsListSasTokensResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SasTokenInformationListResult.NextLink) + }, + } +} + +// listSasTokensCreateRequest creates the ListSasTokens request. +func (client *StorageAccountsClient) listSasTokensCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, containerName string, options *StorageAccountsListSasTokensOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}/containers/{containerName}/listSasTokens" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + if containerName == "" { + return nil, errors.New("parameter containerName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{containerName}", url.PathEscape(containerName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listSasTokensHandleResponse handles the ListSasTokens response. +func (client *StorageAccountsClient) listSasTokensHandleResponse(resp *http.Response) (StorageAccountsListSasTokensResponse, error) { + result := StorageAccountsListSasTokensResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SasTokenInformationListResult); err != nil { + return StorageAccountsListSasTokensResponse{}, err + } + return result, nil +} + +// listSasTokensHandleError handles the ListSasTokens error response. +func (client *StorageAccountsClient) listSasTokensHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListStorageContainers - Lists the Azure Storage containers, if any, associated with the specified Data Lake Analytics and Azure Storage account combination. +// The response includes a link to the next page of results, if any. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) ListStorageContainers(resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsListStorageContainersOptions) *StorageAccountsListStorageContainersPager { + return &StorageAccountsListStorageContainersPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listStorageContainersCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, options) + }, + advancer: func(ctx context.Context, resp StorageAccountsListStorageContainersResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StorageContainerListResult.NextLink) + }, + } +} + +// listStorageContainersCreateRequest creates the ListStorageContainers request. +func (client *StorageAccountsClient) listStorageContainersCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsListStorageContainersOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}/containers" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listStorageContainersHandleResponse handles the ListStorageContainers response. +func (client *StorageAccountsClient) listStorageContainersHandleResponse(resp *http.Response) (StorageAccountsListStorageContainersResponse, error) { + result := StorageAccountsListStorageContainersResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageContainerListResult); err != nil { + return StorageAccountsListStorageContainersResponse{}, err + } + return result, nil +} + +// listStorageContainersHandleError handles the ListStorageContainers error response. +func (client *StorageAccountsClient) listStorageContainersHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates the Data Lake Analytics account to replace Azure Storage blob account details, such as the access key and/or suffix. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StorageAccountsClient) Update(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsUpdateOptions) (StorageAccountsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, storageAccountName, options) + if err != nil { + return StorageAccountsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StorageAccountsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StorageAccountsUpdateResponse{}, client.updateHandleError(resp) + } + return StorageAccountsUpdateResponse{RawResponse: resp}, nil +} + +// updateCreateRequest creates the Update request. +func (client *StorageAccountsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, storageAccountName string, options *StorageAccountsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeAnalytics/accounts/{accountName}/storageAccounts/{storageAccountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if storageAccountName == "" { + return nil, errors.New("parameter storageAccountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{storageAccountName}", url.PathEscape(storageAccountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2019-11-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// updateHandleError handles the Update error response. +func (client *StorageAccountsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_time_rfc3339.go b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..096825079f28 --- /dev/null +++ b/sdk/resourcemanager/datalake-analytics/armdatalakeanalytics/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armdatalakeanalytics + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/datalake-store/armdatalakestore/CHANGELOG.md b/sdk/resourcemanager/datalake-store/armdatalakestore/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/datalake-store/armdatalakestore/CHANGELOG.md +++ b/sdk/resourcemanager/datalake-store/armdatalakestore/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/datalake-store/armdatalakestore/zz_generated_constants.go b/sdk/resourcemanager/datalake-store/armdatalakestore/zz_generated_constants.go index bfe99b678506..6337d2872129 100644 --- a/sdk/resourcemanager/datalake-store/armdatalakestore/zz_generated_constants.go +++ b/sdk/resourcemanager/datalake-store/armdatalakestore/zz_generated_constants.go @@ -10,7 +10,7 @@ package armdatalakestore const ( module = "armdatalakestore" - version = "v0.1.0" + version = "v0.1.1" ) // CheckNameAvailabilityParametersType - The resource type. Note: This should not be set by the user, as the constant value is Microsoft.DataLakeStore/accounts diff --git a/sdk/resourcemanager/iothub/armiothub/CHANGELOG.md b/sdk/resourcemanager/iothub/armiothub/CHANGELOG.md index 40d6546e9d37..6cd92f6efa2d 100644 --- a/sdk/resourcemanager/iothub/armiothub/CHANGELOG.md +++ b/sdk/resourcemanager/iothub/armiothub/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-18) - Initial preview release. diff --git a/sdk/resourcemanager/iothub/armiothub/autorest.md b/sdk/resourcemanager/iothub/armiothub/autorest.md index 78c473362c15..d2ef2c1d94ea 100644 --- a/sdk/resourcemanager/iothub/armiothub/autorest.md +++ b/sdk/resourcemanager/iothub/armiothub/autorest.md @@ -8,5 +8,5 @@ require: - https://github.com/Azure/azure-rest-api-specs/blob/a7e864e0ea1b7a3133d3f1def968985d117aa2f2/specification/iothub/resource-manager/readme.md - https://github.com/Azure/azure-rest-api-specs/blob/a7e864e0ea1b7a3133d3f1def968985d117aa2f2/specification/iothub/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 0.1.0 +module-version: 0.1.1 ``` \ No newline at end of file diff --git a/sdk/resourcemanager/iothub/armiothub/zz_generated_constants.go b/sdk/resourcemanager/iothub/armiothub/zz_generated_constants.go index f5cfa38c1b06..1e4b9cf4ef19 100644 --- a/sdk/resourcemanager/iothub/armiothub/zz_generated_constants.go +++ b/sdk/resourcemanager/iothub/armiothub/zz_generated_constants.go @@ -10,7 +10,7 @@ package armiothub const ( module = "armiothub" - version = "v0.1.0" + version = "v0.1.1" ) // AccessRights - The permissions assigned to the shared access policy. diff --git a/sdk/resourcemanager/logic/armlogic/autorest.md b/sdk/resourcemanager/logic/armlogic/autorest.md index 9da4fe0ad6b3..bd24ff7a4656 100644 --- a/sdk/resourcemanager/logic/armlogic/autorest.md +++ b/sdk/resourcemanager/logic/armlogic/autorest.md @@ -8,5 +8,5 @@ require: - https://github.com/Azure/azure-rest-api-specs/blob/3eaa729b3686f20817145e771a8ab707c739dbbd/specification/logic/resource-manager/readme.md - https://github.com/Azure/azure-rest-api-specs/blob/3eaa729b3686f20817145e771a8ab707c739dbbd/specification/logic/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 0.1.0 +module-version: 0.1.1 ``` \ No newline at end of file diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/CHANGELOG.md b/sdk/resourcemanager/managementgroups/armmanagementgroups/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/LICENSE.txt b/sdk/resourcemanager/managementgroups/armmanagementgroups/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/README.md b/sdk/resourcemanager/managementgroups/armmanagementgroups/README.md new file mode 100644 index 000000000000..512caf665c88 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/README.md @@ -0,0 +1,76 @@ +# Azure Management Groups Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups) + +The `armmanagementgroups` module provides operations for working with Azure Management Groups. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/managementgroups/armmanagementgroups) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Management Groups module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Management Groups. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Management Groups + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Management Groups modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armmanagementgroups.NewOperationsClient(con) +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Management Groups` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/autorest.md b/sdk/resourcemanager/managementgroups/armmanagementgroups/autorest.md new file mode 100644 index 000000000000..8fcc2434a01c --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/4aebac1bd77282ae8efe3dd2886e864537d31762/specification/managementgroups/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/4aebac1bd77282ae8efe3dd2886e864537d31762/specification/managementgroups/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/build.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/build.go new file mode 100644 index 000000000000..5dedc4677f5d --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/managementgroups/armmanagementgroups + +package armmanagementgroups diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/ci.yml b/sdk/resourcemanager/managementgroups/armmanagementgroups/ci.yml new file mode 100644 index 000000000000..b3871741b886 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/managementgroups/armmanagementgroups/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/managementgroups/armmanagementgroups/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/managementgroups/armmanagementgroups' diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/go.mod b/sdk/resourcemanager/managementgroups/armmanagementgroups/go.mod new file mode 100644 index 000000000000..9fb28f78dd96 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/managementgroups/armmanagementgroups + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.3.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/go.sum b/sdk/resourcemanager/managementgroups/armmanagementgroups/go.sum new file mode 100644 index 000000000000..af10d0f1292e --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible h1:lb9OWePNuJMiibdxg9XvdbiOldR0Yifge37L4LoOxIs= +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/go_mod_tidy_hack.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/go_mod_tidy_hack.go new file mode 100644 index 000000000000..1c1429b2ee5f --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armmanagementgroups + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_constants.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_constants.go new file mode 100644 index 000000000000..87a102b52d41 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_constants.go @@ -0,0 +1,184 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +const ( + module = "armmanagementgroups" + version = "v0.1.1" +) + +type Enum0 string + +const ( + Enum0Ancestors Enum0 = "ancestors" + Enum0Children Enum0 = "children" + Enum0Path Enum0 = "path" +) + +// PossibleEnum0Values returns the possible values for the Enum0 const type. +func PossibleEnum0Values() []Enum0 { + return []Enum0{ + Enum0Ancestors, + Enum0Children, + Enum0Path, + } +} + +// ToPtr returns a *Enum0 pointing to the current value. +func (c Enum0) ToPtr() *Enum0 { + return &c +} + +type Enum2 string + +const ( + Enum2AllowedChildren Enum2 = "AllowedChildren" + Enum2AllowedParents Enum2 = "AllowedParents" + Enum2ChildrenOnly Enum2 = "ChildrenOnly" + Enum2ParentAndFirstLevelChildren Enum2 = "ParentAndFirstLevelChildren" + Enum2ParentOnly Enum2 = "ParentOnly" +) + +// PossibleEnum2Values returns the possible values for the Enum2 const type. +func PossibleEnum2Values() []Enum2 { + return []Enum2{ + Enum2AllowedChildren, + Enum2AllowedParents, + Enum2ChildrenOnly, + Enum2ParentAndFirstLevelChildren, + Enum2ParentOnly, + } +} + +// ToPtr returns a *Enum2 pointing to the current value. +func (c Enum2) ToPtr() *Enum2 { + return &c +} + +type Enum3 string + +const ( + Enum3Audit Enum3 = "Audit" + Enum3FullHierarchy Enum3 = "FullHierarchy" + Enum3GroupsOnly Enum3 = "GroupsOnly" + Enum3SubscriptionsOnly Enum3 = "SubscriptionsOnly" +) + +// PossibleEnum3Values returns the possible values for the Enum3 const type. +func PossibleEnum3Values() []Enum3 { + return []Enum3{ + Enum3Audit, + Enum3FullHierarchy, + Enum3GroupsOnly, + Enum3SubscriptionsOnly, + } +} + +// ToPtr returns a *Enum3 pointing to the current value. +func (c Enum3) ToPtr() *Enum3 { + return &c +} + +// ManagementGroupChildType - The type of child resource. +type ManagementGroupChildType string + +const ( + ManagementGroupChildTypeMicrosoftManagementManagementGroups ManagementGroupChildType = "Microsoft.Management/managementGroups" + ManagementGroupChildTypeSubscriptions ManagementGroupChildType = "/subscriptions" +) + +// PossibleManagementGroupChildTypeValues returns the possible values for the ManagementGroupChildType const type. +func PossibleManagementGroupChildTypeValues() []ManagementGroupChildType { + return []ManagementGroupChildType{ + ManagementGroupChildTypeMicrosoftManagementManagementGroups, + ManagementGroupChildTypeSubscriptions, + } +} + +// ToPtr returns a *ManagementGroupChildType pointing to the current value. +func (c ManagementGroupChildType) ToPtr() *ManagementGroupChildType { + return &c +} + +// Permissions - The users specific permissions to this item. +type Permissions string + +const ( + PermissionsDelete Permissions = "delete" + PermissionsEdit Permissions = "edit" + PermissionsNoaccess Permissions = "noaccess" + PermissionsView Permissions = "view" +) + +// PossiblePermissionsValues returns the possible values for the Permissions const type. +func PossiblePermissionsValues() []Permissions { + return []Permissions{ + PermissionsDelete, + PermissionsEdit, + PermissionsNoaccess, + PermissionsView, + } +} + +// ToPtr returns a *Permissions pointing to the current value. +func (c Permissions) ToPtr() *Permissions { + return &c +} + +// Reason - Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect +// length, unsupported characters, etc.) AlreadyExists +// indicates that the name is already in use and is therefore unavailable. +type Reason string + +const ( + ReasonInvalid Reason = "Invalid" + ReasonAlreadyExists Reason = "AlreadyExists" +) + +// PossibleReasonValues returns the possible values for the Reason const type. +func PossibleReasonValues() []Reason { + return []Reason{ + ReasonInvalid, + ReasonAlreadyExists, + } +} + +// ToPtr returns a *Reason pointing to the current value. +func (c Reason) ToPtr() *Reason { + return &c +} + +// Status - The status of the Tenant Backfill +type Status string + +const ( + StatusNotStarted Status = "NotStarted" + StatusNotStartedButGroupsExist Status = "NotStartedButGroupsExist" + StatusStarted Status = "Started" + StatusFailed Status = "Failed" + StatusCancelled Status = "Cancelled" + StatusCompleted Status = "Completed" +) + +// PossibleStatusValues returns the possible values for the Status const type. +func PossibleStatusValues() []Status { + return []Status{ + StatusNotStarted, + StatusNotStartedButGroupsExist, + StatusStarted, + StatusFailed, + StatusCancelled, + StatusCompleted, + } +} + +// ToPtr returns a *Status pointing to the current value. +func (c Status) ToPtr() *Status { + return &c +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_entities_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_entities_client.go new file mode 100644 index 000000000000..796b709ae3f4 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_entities_client.go @@ -0,0 +1,109 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "fmt" + "net/http" + "strconv" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// EntitiesClient contains the methods for the Entities group. +// Don't use this type directly, use NewEntitiesClient() instead. +type EntitiesClient struct { + ep string + pl runtime.Pipeline +} + +// NewEntitiesClient creates a new instance of EntitiesClient with the specified values. +func NewEntitiesClient(con *arm.Connection) *EntitiesClient { + return &EntitiesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - List all entities (Management Groups, Subscriptions, etc.) for the authenticated user. +// If the operation fails it returns the *ErrorResponse error type. +func (client *EntitiesClient) List(options *EntitiesListOptions) *EntitiesListPager { + return &EntitiesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp EntitiesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.EntityListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *EntitiesClient) listCreateRequest(ctx context.Context, options *EntitiesListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/getEntities" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + if options != nil && options.Search != nil { + reqQP.Set("$search", string(*options.Search)) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.View != nil { + reqQP.Set("$view", string(*options.View)) + } + if options != nil && options.GroupName != nil { + reqQP.Set("groupName", *options.GroupName) + } + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *EntitiesClient) listHandleResponse(resp *http.Response) (EntitiesListResponse, error) { + result := EntitiesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.EntityListResult); err != nil { + return EntitiesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *EntitiesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_hierarchysettings_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_hierarchysettings_client.go new file mode 100644 index 000000000000..93a98163ad68 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_hierarchysettings_client.go @@ -0,0 +1,310 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// HierarchySettingsClient contains the methods for the HierarchySettings group. +// Don't use this type directly, use NewHierarchySettingsClient() instead. +type HierarchySettingsClient struct { + ep string + pl runtime.Pipeline +} + +// NewHierarchySettingsClient creates a new instance of HierarchySettingsClient with the specified values. +func NewHierarchySettingsClient(con *arm.Connection) *HierarchySettingsClient { + return &HierarchySettingsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// CreateOrUpdate - Creates or updates the hierarchy settings defined at the Management Group level. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HierarchySettingsClient) CreateOrUpdate(ctx context.Context, groupID string, createTenantSettingsRequest CreateOrUpdateSettingsRequest, options *HierarchySettingsCreateOrUpdateOptions) (HierarchySettingsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, groupID, createTenantSettingsRequest, options) + if err != nil { + return HierarchySettingsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HierarchySettingsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HierarchySettingsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *HierarchySettingsClient) createOrUpdateCreateRequest(ctx context.Context, groupID string, createTenantSettingsRequest CreateOrUpdateSettingsRequest, options *HierarchySettingsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, createTenantSettingsRequest) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *HierarchySettingsClient) createOrUpdateHandleResponse(resp *http.Response) (HierarchySettingsCreateOrUpdateResponse, error) { + result := HierarchySettingsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HierarchySettings); err != nil { + return HierarchySettingsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *HierarchySettingsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes the hierarchy settings defined at the Management Group level. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HierarchySettingsClient) Delete(ctx context.Context, groupID string, options *HierarchySettingsDeleteOptions) (HierarchySettingsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, groupID, options) + if err != nil { + return HierarchySettingsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HierarchySettingsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HierarchySettingsDeleteResponse{}, client.deleteHandleError(resp) + } + return HierarchySettingsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *HierarchySettingsClient) deleteCreateRequest(ctx context.Context, groupID string, options *HierarchySettingsDeleteOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *HierarchySettingsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the hierarchy settings defined at the Management Group level. Settings can only be set on the root Management Group of the hierarchy. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HierarchySettingsClient) Get(ctx context.Context, groupID string, options *HierarchySettingsGetOptions) (HierarchySettingsGetResponse, error) { + req, err := client.getCreateRequest(ctx, groupID, options) + if err != nil { + return HierarchySettingsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HierarchySettingsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HierarchySettingsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *HierarchySettingsClient) getCreateRequest(ctx context.Context, groupID string, options *HierarchySettingsGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HierarchySettingsClient) getHandleResponse(resp *http.Response) (HierarchySettingsGetResponse, error) { + result := HierarchySettingsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HierarchySettings); err != nil { + return HierarchySettingsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *HierarchySettingsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Gets all the hierarchy settings defined at the Management Group level. Settings can only be set on the root Management Group of the hierarchy. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HierarchySettingsClient) List(ctx context.Context, groupID string, options *HierarchySettingsListOptions) (HierarchySettingsListResponse, error) { + req, err := client.listCreateRequest(ctx, groupID, options) + if err != nil { + return HierarchySettingsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HierarchySettingsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HierarchySettingsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *HierarchySettingsClient) listCreateRequest(ctx context.Context, groupID string, options *HierarchySettingsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/settings" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *HierarchySettingsClient) listHandleResponse(resp *http.Response) (HierarchySettingsListResponse, error) { + result := HierarchySettingsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HierarchySettingsList); err != nil { + return HierarchySettingsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *HierarchySettingsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates the hierarchy settings defined at the Management Group level. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HierarchySettingsClient) Update(ctx context.Context, groupID string, createTenantSettingsRequest CreateOrUpdateSettingsRequest, options *HierarchySettingsUpdateOptions) (HierarchySettingsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, groupID, createTenantSettingsRequest, options) + if err != nil { + return HierarchySettingsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HierarchySettingsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HierarchySettingsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *HierarchySettingsClient) updateCreateRequest(ctx context.Context, groupID string, createTenantSettingsRequest CreateOrUpdateSettingsRequest, options *HierarchySettingsUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/settings/default" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, createTenantSettingsRequest) +} + +// updateHandleResponse handles the Update response. +func (client *HierarchySettingsClient) updateHandleResponse(resp *http.Response) (HierarchySettingsUpdateResponse, error) { + result := HierarchySettingsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HierarchySettings); err != nil { + return HierarchySettingsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *HierarchySettingsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroups_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroups_client.go new file mode 100644 index 000000000000..6a85cd1aa352 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroups_client.go @@ -0,0 +1,425 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ManagementGroupsClient contains the methods for the ManagementGroups group. +// Don't use this type directly, use NewManagementGroupsClient() instead. +type ManagementGroupsClient struct { + ep string + pl runtime.Pipeline +} + +// NewManagementGroupsClient creates a new instance of ManagementGroupsClient with the specified values. +func NewManagementGroupsClient(con *arm.Connection) *ManagementGroupsClient { + return &ManagementGroupsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// BeginCreateOrUpdate - Create or update a management group. If a management group is already created and a subsequent create request is issued with different +// properties, the management group properties will be updated. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) BeginCreateOrUpdate(ctx context.Context, groupID string, createManagementGroupRequest CreateManagementGroupRequest, options *ManagementGroupsBeginCreateOrUpdateOptions) (ManagementGroupsCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, groupID, createManagementGroupRequest, options) + if err != nil { + return ManagementGroupsCreateOrUpdatePollerResponse{}, err + } + result := ManagementGroupsCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ManagementGroupsClient.CreateOrUpdate", "azure-async-operation", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return ManagementGroupsCreateOrUpdatePollerResponse{}, err + } + result.Poller = &ManagementGroupsCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Create or update a management group. If a management group is already created and a subsequent create request is issued with different +// properties, the management group properties will be updated. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) createOrUpdate(ctx context.Context, groupID string, createManagementGroupRequest CreateManagementGroupRequest, options *ManagementGroupsBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, groupID, createManagementGroupRequest, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ManagementGroupsClient) createOrUpdateCreateRequest(ctx context.Context, groupID string, createManagementGroupRequest CreateManagementGroupRequest, options *ManagementGroupsBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, createManagementGroupRequest) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *ManagementGroupsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Delete management group. If a management group contains child resources, the request will fail. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) BeginDelete(ctx context.Context, groupID string, options *ManagementGroupsBeginDeleteOptions) (ManagementGroupsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, groupID, options) + if err != nil { + return ManagementGroupsDeletePollerResponse{}, err + } + result := ManagementGroupsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ManagementGroupsClient.Delete", "azure-async-operation", resp, client.pl, client.deleteHandleError) + if err != nil { + return ManagementGroupsDeletePollerResponse{}, err + } + result.Poller = &ManagementGroupsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Delete management group. If a management group contains child resources, the request will fail. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) deleteOperation(ctx context.Context, groupID string, options *ManagementGroupsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, groupID, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagementGroupsClient) deleteCreateRequest(ctx context.Context, groupID string, options *ManagementGroupsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ManagementGroupsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of the management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) Get(ctx context.Context, groupID string, options *ManagementGroupsGetOptions) (ManagementGroupsGetResponse, error) { + req, err := client.getCreateRequest(ctx, groupID, options) + if err != nil { + return ManagementGroupsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *ManagementGroupsClient) getCreateRequest(ctx context.Context, groupID string, options *ManagementGroupsGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + if options != nil && options.Expand != nil { + reqQP.Set("$expand", string(*options.Expand)) + } + if options != nil && options.Recurse != nil { + reqQP.Set("$recurse", strconv.FormatBool(*options.Recurse)) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ManagementGroupsClient) getHandleResponse(resp *http.Response) (ManagementGroupsGetResponse, error) { + result := ManagementGroupsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagementGroup); err != nil { + return ManagementGroupsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *ManagementGroupsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetDescendants - List all entities that descend from a management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) GetDescendants(groupID string, options *ManagementGroupsGetDescendantsOptions) *ManagementGroupsGetDescendantsPager { + return &ManagementGroupsGetDescendantsPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.getDescendantsCreateRequest(ctx, groupID, options) + }, + advancer: func(ctx context.Context, resp ManagementGroupsGetDescendantsResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.DescendantListResult.NextLink) + }, + } +} + +// getDescendantsCreateRequest creates the GetDescendants request. +func (client *ManagementGroupsClient) getDescendantsCreateRequest(ctx context.Context, groupID string, options *ManagementGroupsGetDescendantsOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/descendants" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getDescendantsHandleResponse handles the GetDescendants response. +func (client *ManagementGroupsClient) getDescendantsHandleResponse(resp *http.Response) (ManagementGroupsGetDescendantsResponse, error) { + result := ManagementGroupsGetDescendantsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DescendantListResult); err != nil { + return ManagementGroupsGetDescendantsResponse{}, err + } + return result, nil +} + +// getDescendantsHandleError handles the GetDescendants error response. +func (client *ManagementGroupsClient) getDescendantsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List management groups for the authenticated user. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) List(options *ManagementGroupsListOptions) *ManagementGroupsListPager { + return &ManagementGroupsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp ManagementGroupsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ManagementGroupListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *ManagementGroupsClient) listCreateRequest(ctx context.Context, options *ManagementGroupsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ManagementGroupsClient) listHandleResponse(resp *http.Response) (ManagementGroupsListResponse, error) { + result := ManagementGroupsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagementGroupListResult); err != nil { + return ManagementGroupsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *ManagementGroupsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Update a management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsClient) Update(ctx context.Context, groupID string, patchGroupRequest PatchManagementGroupRequest, options *ManagementGroupsUpdateOptions) (ManagementGroupsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, groupID, patchGroupRequest, options) + if err != nil { + return ManagementGroupsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *ManagementGroupsClient) updateCreateRequest(ctx context.Context, groupID string, patchGroupRequest PatchManagementGroupRequest, options *ManagementGroupsUpdateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, patchGroupRequest) +} + +// updateHandleResponse handles the Update response. +func (client *ManagementGroupsClient) updateHandleResponse(resp *http.Response) (ManagementGroupsUpdateResponse, error) { + result := ManagementGroupsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ManagementGroup); err != nil { + return ManagementGroupsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *ManagementGroupsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsapi_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsapi_client.go new file mode 100644 index 000000000000..84fa10a06def --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsapi_client.go @@ -0,0 +1,190 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ManagementGroupsAPIClient contains the methods for the ManagementGroupsAPI group. +// Don't use this type directly, use NewManagementGroupsAPIClient() instead. +type ManagementGroupsAPIClient struct { + ep string + pl runtime.Pipeline +} + +// NewManagementGroupsAPIClient creates a new instance of ManagementGroupsAPIClient with the specified values. +func NewManagementGroupsAPIClient(con *arm.Connection) *ManagementGroupsAPIClient { + return &ManagementGroupsAPIClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// CheckNameAvailability - Checks if the specified management group name is valid and unique +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsAPIClient) CheckNameAvailability(ctx context.Context, checkNameAvailabilityRequest CheckNameAvailabilityRequest, options *ManagementGroupsAPICheckNameAvailabilityOptions) (ManagementGroupsAPICheckNameAvailabilityResponse, error) { + req, err := client.checkNameAvailabilityCreateRequest(ctx, checkNameAvailabilityRequest, options) + if err != nil { + return ManagementGroupsAPICheckNameAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupsAPICheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupsAPICheckNameAvailabilityResponse{}, client.checkNameAvailabilityHandleError(resp) + } + return client.checkNameAvailabilityHandleResponse(resp) +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *ManagementGroupsAPIClient) checkNameAvailabilityCreateRequest(ctx context.Context, checkNameAvailabilityRequest CheckNameAvailabilityRequest, options *ManagementGroupsAPICheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/checkNameAvailability" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, checkNameAvailabilityRequest) +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *ManagementGroupsAPIClient) checkNameAvailabilityHandleResponse(resp *http.Response) (ManagementGroupsAPICheckNameAvailabilityResponse, error) { + result := ManagementGroupsAPICheckNameAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return ManagementGroupsAPICheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// checkNameAvailabilityHandleError handles the CheckNameAvailability error response. +func (client *ManagementGroupsAPIClient) checkNameAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// StartTenantBackfill - Starts backfilling subscriptions for the Tenant. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsAPIClient) StartTenantBackfill(ctx context.Context, options *ManagementGroupsAPIStartTenantBackfillOptions) (ManagementGroupsAPIStartTenantBackfillResponse, error) { + req, err := client.startTenantBackfillCreateRequest(ctx, options) + if err != nil { + return ManagementGroupsAPIStartTenantBackfillResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupsAPIStartTenantBackfillResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupsAPIStartTenantBackfillResponse{}, client.startTenantBackfillHandleError(resp) + } + return client.startTenantBackfillHandleResponse(resp) +} + +// startTenantBackfillCreateRequest creates the StartTenantBackfill request. +func (client *ManagementGroupsAPIClient) startTenantBackfillCreateRequest(ctx context.Context, options *ManagementGroupsAPIStartTenantBackfillOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/startTenantBackfill" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// startTenantBackfillHandleResponse handles the StartTenantBackfill response. +func (client *ManagementGroupsAPIClient) startTenantBackfillHandleResponse(resp *http.Response) (ManagementGroupsAPIStartTenantBackfillResponse, error) { + result := ManagementGroupsAPIStartTenantBackfillResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantBackfillStatusResult); err != nil { + return ManagementGroupsAPIStartTenantBackfillResponse{}, err + } + return result, nil +} + +// startTenantBackfillHandleError handles the StartTenantBackfill error response. +func (client *ManagementGroupsAPIClient) startTenantBackfillHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// TenantBackfillStatus - Gets tenant backfill status +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupsAPIClient) TenantBackfillStatus(ctx context.Context, options *ManagementGroupsAPITenantBackfillStatusOptions) (ManagementGroupsAPITenantBackfillStatusResponse, error) { + req, err := client.tenantBackfillStatusCreateRequest(ctx, options) + if err != nil { + return ManagementGroupsAPITenantBackfillStatusResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupsAPITenantBackfillStatusResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupsAPITenantBackfillStatusResponse{}, client.tenantBackfillStatusHandleError(resp) + } + return client.tenantBackfillStatusHandleResponse(resp) +} + +// tenantBackfillStatusCreateRequest creates the TenantBackfillStatus request. +func (client *ManagementGroupsAPIClient) tenantBackfillStatusCreateRequest(ctx context.Context, options *ManagementGroupsAPITenantBackfillStatusOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/tenantBackfillStatus" + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// tenantBackfillStatusHandleResponse handles the TenantBackfillStatus response. +func (client *ManagementGroupsAPIClient) tenantBackfillStatusHandleResponse(resp *http.Response) (ManagementGroupsAPITenantBackfillStatusResponse, error) { + result := ManagementGroupsAPITenantBackfillStatusResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.TenantBackfillStatusResult); err != nil { + return ManagementGroupsAPITenantBackfillStatusResponse{}, err + } + return result, nil +} + +// tenantBackfillStatusHandleError handles the TenantBackfillStatus error response. +func (client *ManagementGroupsAPIClient) tenantBackfillStatusHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsubscriptions_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsubscriptions_client.go new file mode 100644 index 000000000000..d9d4f84c13a4 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_managementgroupsubscriptions_client.go @@ -0,0 +1,274 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ManagementGroupSubscriptionsClient contains the methods for the ManagementGroupSubscriptions group. +// Don't use this type directly, use NewManagementGroupSubscriptionsClient() instead. +type ManagementGroupSubscriptionsClient struct { + ep string + pl runtime.Pipeline +} + +// NewManagementGroupSubscriptionsClient creates a new instance of ManagementGroupSubscriptionsClient with the specified values. +func NewManagementGroupSubscriptionsClient(con *arm.Connection) *ManagementGroupSubscriptionsClient { + return &ManagementGroupSubscriptionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// Create - Associates existing subscription with the management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupSubscriptionsClient) Create(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsCreateOptions) (ManagementGroupSubscriptionsCreateResponse, error) { + req, err := client.createCreateRequest(ctx, groupID, subscriptionID, options) + if err != nil { + return ManagementGroupSubscriptionsCreateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupSubscriptionsCreateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupSubscriptionsCreateResponse{}, client.createHandleError(resp) + } + return client.createHandleResponse(resp) +} + +// createCreateRequest creates the Create request. +func (client *ManagementGroupSubscriptionsClient) createCreateRequest(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsCreateOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *ManagementGroupSubscriptionsClient) createHandleResponse(resp *http.Response) (ManagementGroupSubscriptionsCreateResponse, error) { + result := ManagementGroupSubscriptionsCreateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionUnderManagementGroup); err != nil { + return ManagementGroupSubscriptionsCreateResponse{}, err + } + return result, nil +} + +// createHandleError handles the Create error response. +func (client *ManagementGroupSubscriptionsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - De-associates subscription from the management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupSubscriptionsClient) Delete(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsDeleteOptions) (ManagementGroupSubscriptionsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, groupID, subscriptionID, options) + if err != nil { + return ManagementGroupSubscriptionsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupSubscriptionsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return ManagementGroupSubscriptionsDeleteResponse{}, client.deleteHandleError(resp) + } + return ManagementGroupSubscriptionsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ManagementGroupSubscriptionsClient) deleteCreateRequest(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsDeleteOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ManagementGroupSubscriptionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetSubscription - Retrieves details about given subscription which is associated with the management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupSubscriptionsClient) GetSubscription(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsGetSubscriptionOptions) (ManagementGroupSubscriptionsGetSubscriptionResponse, error) { + req, err := client.getSubscriptionCreateRequest(ctx, groupID, subscriptionID, options) + if err != nil { + return ManagementGroupSubscriptionsGetSubscriptionResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ManagementGroupSubscriptionsGetSubscriptionResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ManagementGroupSubscriptionsGetSubscriptionResponse{}, client.getSubscriptionHandleError(resp) + } + return client.getSubscriptionHandleResponse(resp) +} + +// getSubscriptionCreateRequest creates the GetSubscription request. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionCreateRequest(ctx context.Context, groupID string, subscriptionID string, options *ManagementGroupSubscriptionsGetSubscriptionOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions/{subscriptionId}" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + if subscriptionID == "" { + return nil, errors.New("parameter subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.CacheControl != nil { + req.Raw().Header.Set("Cache-Control", *options.CacheControl) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getSubscriptionHandleResponse handles the GetSubscription response. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionHandleResponse(resp *http.Response) (ManagementGroupSubscriptionsGetSubscriptionResponse, error) { + result := ManagementGroupSubscriptionsGetSubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionUnderManagementGroup); err != nil { + return ManagementGroupSubscriptionsGetSubscriptionResponse{}, err + } + return result, nil +} + +// getSubscriptionHandleError handles the GetSubscription error response. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetSubscriptionsUnderManagementGroup - Retrieves details about all subscriptions which are associated with the management group. +// If the operation fails it returns the *ErrorResponse error type. +func (client *ManagementGroupSubscriptionsClient) GetSubscriptionsUnderManagementGroup(groupID string, options *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupOptions) *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager { + return &ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.getSubscriptionsUnderManagementGroupCreateRequest(ctx, groupID, options) + }, + advancer: func(ctx context.Context, resp ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ListSubscriptionUnderManagementGroup.NextLink) + }, + } +} + +// getSubscriptionsUnderManagementGroupCreateRequest creates the GetSubscriptionsUnderManagementGroup request. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionsUnderManagementGroupCreateRequest(ctx context.Context, groupID string, options *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/managementGroups/{groupId}/subscriptions" + if groupID == "" { + return nil, errors.New("parameter groupID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{groupId}", url.PathEscape(groupID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + if options != nil && options.Skiptoken != nil { + reqQP.Set("$skiptoken", *options.Skiptoken) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getSubscriptionsUnderManagementGroupHandleResponse handles the GetSubscriptionsUnderManagementGroup response. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionsUnderManagementGroupHandleResponse(resp *http.Response) (ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse, error) { + result := ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ListSubscriptionUnderManagementGroup); err != nil { + return ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse{}, err + } + return result, nil +} + +// getSubscriptionsUnderManagementGroupHandleError handles the GetSubscriptionsUnderManagementGroup error response. +func (client *ManagementGroupSubscriptionsClient) getSubscriptionsUnderManagementGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_models.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_models.go new file mode 100644 index 000000000000..0a8991f58bcc --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_models.go @@ -0,0 +1,998 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AzureAsyncOperationResults - The results of Azure-AsyncOperation. +type AzureAsyncOperationResults struct { + // The generic properties of a management group. + Properties *ManagementGroupInfoProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The current status of the asynchronous operation performed . For example, Running, Succeeded, Failed + Status *string `json:"status,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// CheckNameAvailabilityRequest - Management group name availability check parameters. +type CheckNameAvailabilityRequest struct { + // the name to check for availability + Name *string `json:"name,omitempty"` + + // fully qualified resource type which includes provider namespace + Type *string `json:"type,omitempty"` +} + +// CheckNameAvailabilityResult - Describes the result of the request to check management group name availability. +type CheckNameAvailabilityResult struct { + // READ-ONLY; Required if nameAvailable == false. Localized. 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 is already in use, and direct them to select a different name. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; Required. True indicates name is valid and available. False indicates the name is invalid, unavailable, or both. + NameAvailable *bool `json:"nameAvailable,omitempty" azure:"ro"` + + // READ-ONLY; Required if nameAvailable == false. Invalid indicates the name provided does not match the resource provider's naming requirements (incorrect + // length, unsupported characters, etc.) AlreadyExists + // indicates that the name is already in use and is therefore unavailable. + Reason *Reason `json:"reason,omitempty" azure:"ro"` +} + +// CreateManagementGroupChildInfo - The child information of a management group used during creation. +type CreateManagementGroupChildInfo struct { + // READ-ONLY; The list of children. + Children []*CreateManagementGroupChildInfo `json:"children,omitempty" azure:"ro"` + + // READ-ONLY; The friendly name of the child resource. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the child entity. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups) + Type *ManagementGroupChildType `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateManagementGroupChildInfo. +func (c CreateManagementGroupChildInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "children", c.Children) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "id", c.ID) + populate(objectMap, "name", c.Name) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// CreateManagementGroupDetails - The details of a management group used during creation. +type CreateManagementGroupDetails struct { + // (Optional) The ID of the parent management group used during creation. + Parent *CreateParentGroupInfo `json:"parent,omitempty"` + + // READ-ONLY; The identity of the principal or process that updated the object. + UpdatedBy *string `json:"updatedBy,omitempty" azure:"ro"` + + // READ-ONLY; The date and time when this object was last updated. + UpdatedTime *time.Time `json:"updatedTime,omitempty" azure:"ro"` + + // READ-ONLY; The version number of the object. + Version *int32 `json:"version,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateManagementGroupDetails. +func (c CreateManagementGroupDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "parent", c.Parent) + populate(objectMap, "updatedBy", c.UpdatedBy) + populate(objectMap, "updatedTime", (*timeRFC3339)(c.UpdatedTime)) + populate(objectMap, "version", c.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CreateManagementGroupDetails. +func (c *CreateManagementGroupDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "parent": + err = unpopulate(val, &c.Parent) + delete(rawMsg, key) + case "updatedBy": + err = unpopulate(val, &c.UpdatedBy) + delete(rawMsg, key) + case "updatedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.UpdatedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "version": + err = unpopulate(val, &c.Version) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// CreateManagementGroupProperties - The generic properties of a management group used during creation. +type CreateManagementGroupProperties struct { + // The details of a management group used during creation. + Details *CreateManagementGroupDetails `json:"details,omitempty"` + + // The friendly name of the management group. If no value is passed then this field will be set to the groupId. + DisplayName *string `json:"displayName,omitempty"` + + // READ-ONLY; The list of children. + Children []*CreateManagementGroupChildInfo `json:"children,omitempty" azure:"ro"` + + // READ-ONLY; The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateManagementGroupProperties. +func (c CreateManagementGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "children", c.Children) + populate(objectMap, "details", c.Details) + populate(objectMap, "displayName", c.DisplayName) + populate(objectMap, "tenantId", c.TenantID) + return json.Marshal(objectMap) +} + +// CreateManagementGroupRequest - Management group creation parameters. +type CreateManagementGroupRequest struct { + // The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty"` + + // The generic properties of a management group used during creation. + Properties *CreateManagementGroupProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// CreateOrUpdateSettingsProperties - The properties of the request to create or update Management Group settings +type CreateOrUpdateSettingsProperties struct { + // Settings that sets the default Management Group under which new subscriptions get added in this tenant. For example, /providers/Microsoft.Management/managementGroups/defaultGroup + DefaultManagementGroup *string `json:"defaultManagementGroup,omitempty"` + + // Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require Microsoft.Management/managementGroups/write + // action on the root + // Management Group scope in order to create new Groups directly under the root. This will prevent new users from creating new Management Groups, unless + // they are given access. + RequireAuthorizationForGroupCreation *bool `json:"requireAuthorizationForGroupCreation,omitempty"` +} + +// CreateOrUpdateSettingsRequest - Parameters for creating or updating Management Group settings +type CreateOrUpdateSettingsRequest struct { + // The properties of the request to create or update Management Group settings + Properties *CreateOrUpdateSettingsProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CreateOrUpdateSettingsRequest. +func (c CreateOrUpdateSettingsRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// CreateParentGroupInfo - (Optional) The ID of the parent management group used during creation. +type CreateParentGroupInfo struct { + // The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty"` + + // READ-ONLY; The friendly name of the parent management group. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; The name of the parent management group + Name *string `json:"name,omitempty" azure:"ro"` +} + +// DescendantInfo - The descendant. +type DescendantInfo struct { + // The generic properties of an descendant. + Properties *DescendantInfoProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the descendant. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + // or /subscriptions/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the descendant. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups or /subscriptions + Type *string `json:"type,omitempty" azure:"ro"` +} + +// DescendantInfoProperties - The generic properties of an descendant. +type DescendantInfoProperties struct { + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // The ID of the parent management group. + Parent *DescendantParentGroupInfo `json:"parent,omitempty"` +} + +// DescendantListResult - Describes the result of the request to view descendants. +type DescendantListResult struct { + // The list of descendants. + Value []*DescendantInfo `json:"value,omitempty"` + + // READ-ONLY; The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type DescendantListResult. +func (d DescendantListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", d.NextLink) + populate(objectMap, "value", d.Value) + return json.Marshal(objectMap) +} + +// DescendantParentGroupInfo - The ID of the parent management group. +type DescendantParentGroupInfo struct { + // The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty"` +} + +// EntitiesListOptions contains the optional parameters for the Entities.List method. +type EntitiesListOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string + // The filter parameter allows you to filter on the the name or display name fields. You can check for equality on the name field (e.g. name eq '{entityName}') + // and you can check for substrings on either the name or display name fields(e.g. contains(name, '{substringToSearch}'), contains(displayName, '{substringToSearch')). + // Note that the '{entityName}' and '{substringToSearch}' fields are checked case insensitively. + Filter *string + // A filter which allows the get entities call to focus on a particular group (i.e. "$filter=name eq 'groupName'") + GroupName *string + // The $search parameter is used in conjunction with the $filter parameter to return three different outputs depending on the parameter passed in. + // With $search=AllowedParents the API will return the entity info of all groups that the requested entity will be able to reparent to as determined by + // the user's permissions. + // With $search=AllowedChildren the API will return the entity info of all entities that can be added as children of the requested entity. + // With $search=ParentAndFirstLevelChildren the API will return the parent and first level of children that the user has either direct access to or indirect + // access via one of their descendants. + // With $search=ParentOnly the API will return only the group if the user has access to at least one of the descendants of the group. + // With $search=ChildrenOnly the API will return only the first level of children of the group entity info specified in $filter. The user must have direct + // access to the children entities or one of it's descendants for it to show up in the results. + Search *Enum2 + // This parameter specifies the fields to include in the response. Can include any combination of Name,DisplayName,Type,ParentDisplayNameChain,ParentChain, + // e.g. '$select=Name,DisplayName,Type,ParentDisplayNameChain,ParentNameChain'. When specified the $select parameter can override select in $skipToken. + Select *string + // Number of entities to skip over when retrieving results. Passing this in will override $skipToken. + Skip *int32 + // Page continuation token is only used if a previous operation returned a partial result. + // If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point + // to use for subsequent calls. + Skiptoken *string + // Number of elements to return when retrieving results. Passing this in will override $skipToken. + Top *int32 + // The view parameter allows clients to filter the type of data that is returned by the getEntities call. + View *Enum3 +} + +// EntityHierarchyItem - The management group details for the hierarchy view. +type EntityHierarchyItem struct { + // The generic properties of a management group. + Properties *EntityHierarchyItemProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// EntityHierarchyItemProperties - The generic properties of a management group. +type EntityHierarchyItemProperties struct { + // The list of children. + Children []*EntityHierarchyItem `json:"children,omitempty"` + + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // The users specific permissions to this item. + Permissions *Permissions `json:"permissions,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EntityHierarchyItemProperties. +func (e EntityHierarchyItemProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "children", e.Children) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "permissions", e.Permissions) + return json.Marshal(objectMap) +} + +// EntityInfo - The entity. +type EntityInfo struct { + // The generic properties of an entity. + Properties *EntityInfoProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the entity. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the entity. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// EntityInfoProperties - The generic properties of an entity. +type EntityInfoProperties struct { + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // The users specific permissions to this item. + InheritedPermissions *Permissions `json:"inheritedPermissions,omitempty"` + + // Number of children is the number of Groups that are exactly one level underneath the current Group. + NumberOfChildGroups *int32 `json:"numberOfChildGroups,omitempty"` + + // Number of children is the number of Groups and Subscriptions that are exactly one level underneath the current Group. + NumberOfChildren *int32 `json:"numberOfChildren,omitempty"` + + // Number of Descendants + NumberOfDescendants *int32 `json:"numberOfDescendants,omitempty"` + + // (Optional) The ID of the parent management group. + Parent *EntityParentGroupInfo `json:"parent,omitempty"` + + // The parent display name chain from the root group to the immediate parent + ParentDisplayNameChain []*string `json:"parentDisplayNameChain,omitempty"` + + // The parent name chain from the root group to the immediate parent + ParentNameChain []*string `json:"parentNameChain,omitempty"` + + // The users specific permissions to this item. + Permissions *Permissions `json:"permissions,omitempty"` + + // The AAD Tenant ID associated with the entity. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EntityInfoProperties. +func (e EntityInfoProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "displayName", e.DisplayName) + populate(objectMap, "inheritedPermissions", e.InheritedPermissions) + populate(objectMap, "numberOfChildGroups", e.NumberOfChildGroups) + populate(objectMap, "numberOfChildren", e.NumberOfChildren) + populate(objectMap, "numberOfDescendants", e.NumberOfDescendants) + populate(objectMap, "parent", e.Parent) + populate(objectMap, "parentDisplayNameChain", e.ParentDisplayNameChain) + populate(objectMap, "parentNameChain", e.ParentNameChain) + populate(objectMap, "permissions", e.Permissions) + populate(objectMap, "tenantId", e.TenantID) + return json.Marshal(objectMap) +} + +// EntityListResult - Describes the result of the request to view entities. +type EntityListResult struct { + // The list of entities. + Value []*EntityInfo `json:"value,omitempty"` + + // READ-ONLY; Total count of records that match the filter + Count *int32 `json:"count,omitempty" azure:"ro"` + + // READ-ONLY; The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type EntityListResult. +func (e EntityListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", e.Count) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// EntityParentGroupInfo - (Optional) The ID of the parent management group. +type EntityParentGroupInfo struct { + // The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty"` +} + +// ErrorDetails - The details of the error. +type ErrorDetails struct { + // One of a server-defined set of error codes. + Code *string `json:"code,omitempty"` + + // A human-readable representation of the error's details. + Details *string `json:"details,omitempty"` + + // A human-readable representation of the error. + Message *string `json:"message,omitempty"` +} + +// ErrorResponse - The error object. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // The details of the error. + InnerError *ErrorDetails `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// HierarchySettings - Settings defined at the Management Group scope. +type HierarchySettings struct { + // The generic properties of hierarchy settings. + Properties *HierarchySettingsProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the settings object. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/settings/default. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the object. In this case, default. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups/settings. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// HierarchySettingsCreateOrUpdateOptions contains the optional parameters for the HierarchySettings.CreateOrUpdate method. +type HierarchySettingsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// HierarchySettingsDeleteOptions contains the optional parameters for the HierarchySettings.Delete method. +type HierarchySettingsDeleteOptions struct { + // placeholder for future optional parameters +} + +// HierarchySettingsGetOptions contains the optional parameters for the HierarchySettings.Get method. +type HierarchySettingsGetOptions struct { + // placeholder for future optional parameters +} + +// HierarchySettingsInfo - The hierarchy settings resource. +type HierarchySettingsInfo struct { + // The generic properties of hierarchy settings. + Properties *HierarchySettingsProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the settings object. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/settings/default. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the object. In this case, default. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups/settings. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// HierarchySettingsList - Lists all hierarchy settings. +type HierarchySettingsList struct { + // The list of hierarchy settings. + Value []*HierarchySettingsInfo `json:"value,omitempty"` + + // READ-ONLY; The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type HierarchySettingsList. +func (h HierarchySettingsList) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", h.NextLink) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// HierarchySettingsListOptions contains the optional parameters for the HierarchySettings.List method. +type HierarchySettingsListOptions struct { + // placeholder for future optional parameters +} + +// HierarchySettingsProperties - The generic properties of hierarchy settings. +type HierarchySettingsProperties struct { + // Settings that sets the default Management Group under which new subscriptions get added in this tenant. For example, /providers/Microsoft.Management/managementGroups/defaultGroup + DefaultManagementGroup *string `json:"defaultManagementGroup,omitempty"` + + // Indicates whether RBAC access is required upon group creation under the root Management Group. If set to true, user will require Microsoft.Management/managementGroups/write + // action on the root + // Management Group scope in order to create new Groups directly under the root. This will prevent new users from creating new Management Groups, unless + // they are given access. + RequireAuthorizationForGroupCreation *bool `json:"requireAuthorizationForGroupCreation,omitempty"` + + // The AAD Tenant ID associated with the hierarchy settings. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty"` +} + +// HierarchySettingsUpdateOptions contains the optional parameters for the HierarchySettings.Update method. +type HierarchySettingsUpdateOptions struct { + // placeholder for future optional parameters +} + +// ListSubscriptionUnderManagementGroup - The details of all subscriptions under management group. +type ListSubscriptionUnderManagementGroup struct { + // The list of subscriptions. + Value []*SubscriptionUnderManagementGroup `json:"value,omitempty"` + + // READ-ONLY; The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListSubscriptionUnderManagementGroup. +func (l ListSubscriptionUnderManagementGroup) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// ManagementGroup - The management group details. +type ManagementGroup struct { + // The generic properties of a management group. + Properties *ManagementGroupProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ManagementGroupChildInfo - The child information of a management group. +type ManagementGroupChildInfo struct { + // The list of children. + Children []*ManagementGroupChildInfo `json:"children,omitempty"` + + // The friendly name of the child resource. + DisplayName *string `json:"displayName,omitempty"` + + // The fully qualified ID for the child resource (management group or subscription). For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty"` + + // The name of the child entity. + Name *string `json:"name,omitempty"` + + // The fully qualified resource type which includes provider namespace (e.g. Microsoft.Management/managementGroups) + Type *ManagementGroupChildType `json:"type,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementGroupChildInfo. +func (m ManagementGroupChildInfo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "children", m.Children) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "id", m.ID) + populate(objectMap, "name", m.Name) + populate(objectMap, "type", m.Type) + return json.Marshal(objectMap) +} + +// ManagementGroupDetails - The details of a management group. +type ManagementGroupDetails struct { + // The ancestors of the management group. + ManagementGroupAncestors []*string `json:"managementGroupAncestors,omitempty"` + + // The ancestors of the management group displayed in reversed order, from immediate parent to the root. + ManagementGroupAncestorsChain []*ManagementGroupPathElement `json:"managementGroupAncestorsChain,omitempty"` + + // (Optional) The ID of the parent management group. + Parent *ParentGroupInfo `json:"parent,omitempty"` + + // The path from the root to the current group. + Path []*ManagementGroupPathElement `json:"path,omitempty"` + + // The identity of the principal or process that updated the object. + UpdatedBy *string `json:"updatedBy,omitempty"` + + // The date and time when this object was last updated. + UpdatedTime *time.Time `json:"updatedTime,omitempty"` + + // The version number of the object. + Version *int32 `json:"version,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementGroupDetails. +func (m ManagementGroupDetails) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "managementGroupAncestors", m.ManagementGroupAncestors) + populate(objectMap, "managementGroupAncestorsChain", m.ManagementGroupAncestorsChain) + populate(objectMap, "parent", m.Parent) + populate(objectMap, "path", m.Path) + populate(objectMap, "updatedBy", m.UpdatedBy) + populate(objectMap, "updatedTime", (*timeRFC3339)(m.UpdatedTime)) + populate(objectMap, "version", m.Version) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ManagementGroupDetails. +func (m *ManagementGroupDetails) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "managementGroupAncestors": + err = unpopulate(val, &m.ManagementGroupAncestors) + delete(rawMsg, key) + case "managementGroupAncestorsChain": + err = unpopulate(val, &m.ManagementGroupAncestorsChain) + delete(rawMsg, key) + case "parent": + err = unpopulate(val, &m.Parent) + delete(rawMsg, key) + case "path": + err = unpopulate(val, &m.Path) + delete(rawMsg, key) + case "updatedBy": + err = unpopulate(val, &m.UpdatedBy) + delete(rawMsg, key) + case "updatedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + m.UpdatedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "version": + err = unpopulate(val, &m.Version) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ManagementGroupInfo - The management group resource. +type ManagementGroupInfo struct { + // The generic properties of a management group. + Properties *ManagementGroupInfoProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ManagementGroupInfoProperties - The generic properties of a management group. +type ManagementGroupInfoProperties struct { + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty"` +} + +// ManagementGroupListResult - Describes the result of the request to list management groups. +type ManagementGroupListResult struct { + // The list of management groups. + Value []*ManagementGroupInfo `json:"value,omitempty"` + + // READ-ONLY; The URL to use for getting the next set of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementGroupListResult. +func (m ManagementGroupListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", m.NextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +// ManagementGroupPathElement - A path element of a management group ancestors. +type ManagementGroupPathElement struct { + // The friendly name of the group. + DisplayName *string `json:"displayName,omitempty"` + + // The name of the group. + Name *string `json:"name,omitempty"` +} + +// ManagementGroupProperties - The generic properties of a management group. +type ManagementGroupProperties struct { + // The list of children. + Children []*ManagementGroupChildInfo `json:"children,omitempty"` + + // The details of a management group. + Details *ManagementGroupDetails `json:"details,omitempty"` + + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ManagementGroupProperties. +func (m ManagementGroupProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "children", m.Children) + populate(objectMap, "details", m.Details) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "tenantId", m.TenantID) + return json.Marshal(objectMap) +} + +// ManagementGroupSubscriptionsCreateOptions contains the optional parameters for the ManagementGroupSubscriptions.Create method. +type ManagementGroupSubscriptionsCreateOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// ManagementGroupSubscriptionsDeleteOptions contains the optional parameters for the ManagementGroupSubscriptions.Delete method. +type ManagementGroupSubscriptionsDeleteOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// ManagementGroupSubscriptionsGetSubscriptionOptions contains the optional parameters for the ManagementGroupSubscriptions.GetSubscription method. +type ManagementGroupSubscriptionsGetSubscriptionOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupOptions contains the optional parameters for the ManagementGroupSubscriptions.GetSubscriptionsUnderManagementGroup +// method. +type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupOptions struct { + // Page continuation token is only used if a previous operation returned a partial result. + // If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point + // to use for subsequent calls. + Skiptoken *string +} + +// ManagementGroupsAPICheckNameAvailabilityOptions contains the optional parameters for the ManagementGroupsAPI.CheckNameAvailability method. +type ManagementGroupsAPICheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupsAPIStartTenantBackfillOptions contains the optional parameters for the ManagementGroupsAPI.StartTenantBackfill method. +type ManagementGroupsAPIStartTenantBackfillOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupsAPITenantBackfillStatusOptions contains the optional parameters for the ManagementGroupsAPI.TenantBackfillStatus method. +type ManagementGroupsAPITenantBackfillStatusOptions struct { + // placeholder for future optional parameters +} + +// ManagementGroupsBeginCreateOrUpdateOptions contains the optional parameters for the ManagementGroups.BeginCreateOrUpdate method. +type ManagementGroupsBeginCreateOrUpdateOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// ManagementGroupsBeginDeleteOptions contains the optional parameters for the ManagementGroups.BeginDelete method. +type ManagementGroupsBeginDeleteOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// ManagementGroupsGetDescendantsOptions contains the optional parameters for the ManagementGroups.GetDescendants method. +type ManagementGroupsGetDescendantsOptions struct { + // Page continuation token is only used if a previous operation returned a partial result. + // If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point + // to use for subsequent calls. + Skiptoken *string + // Number of elements to return when retrieving results. Passing this in will override $skipToken. + Top *int32 +} + +// ManagementGroupsGetOptions contains the optional parameters for the ManagementGroups.Get method. +type ManagementGroupsGetOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string + // The $expand=children query string parameter allows clients to request inclusion of children in the response payload. $expand=path includes the path from + // the root group to the current group. $expand=ancestors includes the ancestor Ids of the current group. + Expand *Enum0 + // A filter which allows the exclusion of subscriptions from results (i.e. '$filter=children.childType ne Subscription') + Filter *string + // The $recurse=true query string parameter allows clients to request inclusion of entire hierarchy in the response payload. Note that $expand=children + // must be passed up if $recurse is set to true. + Recurse *bool +} + +// ManagementGroupsListOptions contains the optional parameters for the ManagementGroups.List method. +type ManagementGroupsListOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string + // Page continuation token is only used if a previous operation returned a partial result. + // If a previous response contains a nextLink element, the value of the nextLink element will include a token parameter that specifies a starting point + // to use for subsequent calls. + Skiptoken *string +} + +// ManagementGroupsUpdateOptions contains the optional parameters for the ManagementGroups.Update method. +type ManagementGroupsUpdateOptions struct { + // Indicates whether the request should utilize any caches. Populate the header with 'no-cache' value to bypass existing caches. + CacheControl *string +} + +// Operation supported by the Microsoft.Management resource provider. +type Operation struct { + // The object that represents the operation. + Display *OperationDisplayProperties `json:"display,omitempty"` + + // READ-ONLY; Operation name: {provider}/{resource}/{operation}. + Name *string `json:"name,omitempty" azure:"ro"` +} + +// OperationDisplayProperties - The object that represents the operation. +type OperationDisplayProperties struct { + // READ-ONLY; Operation description. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; The operation that can be performed. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; The name of the provider. + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; The resource on which the operation is performed. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - Describes the result of the request to list Microsoft.Management operations. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; List of operations supported by the Microsoft.Management resource provider. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationResults - The results of an asynchronous operation. +type OperationResults struct { + // The generic properties of a management group. + Properties *ManagementGroupInfoProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the management group. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups + Type *string `json:"type,omitempty" azure:"ro"` +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// ParentGroupInfo - (Optional) The ID of the parent management group. +type ParentGroupInfo struct { + // The friendly name of the parent management group. + DisplayName *string `json:"displayName,omitempty"` + + // The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ID *string `json:"id,omitempty"` + + // The name of the parent management group + Name *string `json:"name,omitempty"` +} + +// PatchManagementGroupRequest - Management group patch parameters. +type PatchManagementGroupRequest struct { + // The friendly name of the management group. + DisplayName *string `json:"displayName,omitempty"` + + // (Optional) The fully qualified ID for the parent management group. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000 + ParentGroupID *string `json:"parentGroupId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PatchManagementGroupRequest. +func (p PatchManagementGroupRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "displayName", p.DisplayName) + populate(objectMap, "parentGroupId", p.ParentGroupID) + return json.Marshal(objectMap) +} + +// SubscriptionUnderManagementGroup - The details of subscription under management group. +type SubscriptionUnderManagementGroup struct { + // The generic properties of subscription under a management group. + Properties *SubscriptionUnderManagementGroupProperties `json:"properties,omitempty"` + + // READ-ONLY; The fully qualified ID for the subscription. For example, /providers/Microsoft.Management/managementGroups/0000000-0000-0000-0000-000000000000/subscriptions/0000000-0000-0000-0000-000000000001 + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The stringified id of the subscription. For example, 00000000-0000-0000-0000-000000000000 + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. For example, Microsoft.Management/managementGroups/subscriptions + Type *string `json:"type,omitempty" azure:"ro"` +} + +// SubscriptionUnderManagementGroupProperties - The generic properties of subscription under a management group. +type SubscriptionUnderManagementGroupProperties struct { + // The friendly name of the subscription. + DisplayName *string `json:"displayName,omitempty"` + + // The ID of the parent management group. + Parent *DescendantParentGroupInfo `json:"parent,omitempty"` + + // The state of the subscription. + State *string `json:"state,omitempty"` + + // The AAD Tenant ID associated with the subscription. For example, 00000000-0000-0000-0000-000000000000 + Tenant *string `json:"tenant,omitempty"` +} + +// TenantBackfillStatusResult - The tenant backfill status +type TenantBackfillStatusResult struct { + // READ-ONLY; The status of the Tenant Backfill + Status *Status `json:"status,omitempty" azure:"ro"` + + // READ-ONLY; The AAD Tenant ID associated with the management group. For example, 00000000-0000-0000-0000-000000000000 + TenantID *string `json:"tenantId,omitempty" azure:"ro"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_operations_client.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_operations_client.go new file mode 100644 index 000000000000..7b1f9955d427 --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available Management REST API operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Management/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pagers.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pagers.go new file mode 100644 index 000000000000..f8ee85597c9e --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pagers.go @@ -0,0 +1,288 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// EntitiesListPager provides operations for iterating over paged responses. +type EntitiesListPager struct { + client *EntitiesClient + current EntitiesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, EntitiesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *EntitiesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *EntitiesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.EntityListResult.NextLink == nil || len(*p.current.EntityListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current EntitiesListResponse page. +func (p *EntitiesListPager) PageResponse() EntitiesListResponse { + return p.current +} + +// ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager provides operations for iterating over paged responses. +type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager struct { + client *ManagementGroupSubscriptionsClient + current ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ListSubscriptionUnderManagementGroup.NextLink == nil || len(*p.current.ListSubscriptionUnderManagementGroup.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.getSubscriptionsUnderManagementGroupHandleError(resp) + return false + } + result, err := p.client.getSubscriptionsUnderManagementGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse page. +func (p *ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupPager) PageResponse() ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse { + return p.current +} + +// ManagementGroupsGetDescendantsPager provides operations for iterating over paged responses. +type ManagementGroupsGetDescendantsPager struct { + client *ManagementGroupsClient + current ManagementGroupsGetDescendantsResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ManagementGroupsGetDescendantsResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ManagementGroupsGetDescendantsPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ManagementGroupsGetDescendantsPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.DescendantListResult.NextLink == nil || len(*p.current.DescendantListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.getDescendantsHandleError(resp) + return false + } + result, err := p.client.getDescendantsHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ManagementGroupsGetDescendantsResponse page. +func (p *ManagementGroupsGetDescendantsPager) PageResponse() ManagementGroupsGetDescendantsResponse { + return p.current +} + +// ManagementGroupsListPager provides operations for iterating over paged responses. +type ManagementGroupsListPager struct { + client *ManagementGroupsClient + current ManagementGroupsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ManagementGroupsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ManagementGroupsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ManagementGroupsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ManagementGroupListResult.NextLink == nil || len(*p.current.ManagementGroupListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ManagementGroupsListResponse page. +func (p *ManagementGroupsListPager) PageResponse() ManagementGroupsListResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pollers.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pollers.go new file mode 100644 index 000000000000..d3656a55e60e --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_pollers.go @@ -0,0 +1,102 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// ManagementGroupsCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type ManagementGroupsCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ManagementGroupsCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ManagementGroupsCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ManagementGroupsCreateOrUpdateResponse will be returned. +func (p *ManagementGroupsCreateOrUpdatePoller) FinalResponse(ctx context.Context) (ManagementGroupsCreateOrUpdateResponse, error) { + respType := ManagementGroupsCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.ManagementGroup) + if err != nil { + return ManagementGroupsCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ManagementGroupsCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// ManagementGroupsDeletePoller provides polling facilities until the operation reaches a terminal state. +type ManagementGroupsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ManagementGroupsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ManagementGroupsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ManagementGroupsDeleteResponse will be returned. +func (p *ManagementGroupsDeletePoller) FinalResponse(ctx context.Context) (ManagementGroupsDeleteResponse, error) { + respType := ManagementGroupsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.AzureAsyncOperationResults) + if err != nil { + return ManagementGroupsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ManagementGroupsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_response_types.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_response_types.go new file mode 100644 index 000000000000..ee1026b5fcda --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_response_types.go @@ -0,0 +1,321 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// EntitiesListResponse contains the response from method Entities.List. +type EntitiesListResponse struct { + EntitiesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// EntitiesListResult contains the result from method Entities.List. +type EntitiesListResult struct { + EntityListResult +} + +// HierarchySettingsCreateOrUpdateResponse contains the response from method HierarchySettings.CreateOrUpdate. +type HierarchySettingsCreateOrUpdateResponse struct { + HierarchySettingsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HierarchySettingsCreateOrUpdateResult contains the result from method HierarchySettings.CreateOrUpdate. +type HierarchySettingsCreateOrUpdateResult struct { + HierarchySettings +} + +// HierarchySettingsDeleteResponse contains the response from method HierarchySettings.Delete. +type HierarchySettingsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HierarchySettingsGetResponse contains the response from method HierarchySettings.Get. +type HierarchySettingsGetResponse struct { + HierarchySettingsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HierarchySettingsGetResult contains the result from method HierarchySettings.Get. +type HierarchySettingsGetResult struct { + HierarchySettings +} + +// HierarchySettingsListResponse contains the response from method HierarchySettings.List. +type HierarchySettingsListResponse struct { + HierarchySettingsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HierarchySettingsListResult contains the result from method HierarchySettings.List. +type HierarchySettingsListResult struct { + HierarchySettingsList +} + +// HierarchySettingsUpdateResponse contains the response from method HierarchySettings.Update. +type HierarchySettingsUpdateResponse struct { + HierarchySettingsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HierarchySettingsUpdateResult contains the result from method HierarchySettings.Update. +type HierarchySettingsUpdateResult struct { + HierarchySettings +} + +// ManagementGroupSubscriptionsCreateResponse contains the response from method ManagementGroupSubscriptions.Create. +type ManagementGroupSubscriptionsCreateResponse struct { + ManagementGroupSubscriptionsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupSubscriptionsCreateResult contains the result from method ManagementGroupSubscriptions.Create. +type ManagementGroupSubscriptionsCreateResult struct { + SubscriptionUnderManagementGroup +} + +// ManagementGroupSubscriptionsDeleteResponse contains the response from method ManagementGroupSubscriptions.Delete. +type ManagementGroupSubscriptionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupSubscriptionsGetSubscriptionResponse contains the response from method ManagementGroupSubscriptions.GetSubscription. +type ManagementGroupSubscriptionsGetSubscriptionResponse struct { + ManagementGroupSubscriptionsGetSubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupSubscriptionsGetSubscriptionResult contains the result from method ManagementGroupSubscriptions.GetSubscription. +type ManagementGroupSubscriptionsGetSubscriptionResult struct { + SubscriptionUnderManagementGroup +} + +// ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse contains the response from method ManagementGroupSubscriptions.GetSubscriptionsUnderManagementGroup. +type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResponse struct { + ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResult contains the result from method ManagementGroupSubscriptions.GetSubscriptionsUnderManagementGroup. +type ManagementGroupSubscriptionsGetSubscriptionsUnderManagementGroupResult struct { + ListSubscriptionUnderManagementGroup +} + +// ManagementGroupsAPICheckNameAvailabilityResponse contains the response from method ManagementGroupsAPI.CheckNameAvailability. +type ManagementGroupsAPICheckNameAvailabilityResponse struct { + ManagementGroupsAPICheckNameAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsAPICheckNameAvailabilityResult contains the result from method ManagementGroupsAPI.CheckNameAvailability. +type ManagementGroupsAPICheckNameAvailabilityResult struct { + CheckNameAvailabilityResult +} + +// ManagementGroupsAPIStartTenantBackfillResponse contains the response from method ManagementGroupsAPI.StartTenantBackfill. +type ManagementGroupsAPIStartTenantBackfillResponse struct { + ManagementGroupsAPIStartTenantBackfillResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsAPIStartTenantBackfillResult contains the result from method ManagementGroupsAPI.StartTenantBackfill. +type ManagementGroupsAPIStartTenantBackfillResult struct { + TenantBackfillStatusResult +} + +// ManagementGroupsAPITenantBackfillStatusResponse contains the response from method ManagementGroupsAPI.TenantBackfillStatus. +type ManagementGroupsAPITenantBackfillStatusResponse struct { + ManagementGroupsAPITenantBackfillStatusResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsAPITenantBackfillStatusResult contains the result from method ManagementGroupsAPI.TenantBackfillStatus. +type ManagementGroupsAPITenantBackfillStatusResult struct { + TenantBackfillStatusResult +} + +// ManagementGroupsCreateOrUpdatePollerResponse contains the response from method ManagementGroups.CreateOrUpdate. +type ManagementGroupsCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *ManagementGroupsCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ManagementGroupsCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ManagementGroupsCreateOrUpdateResponse, error) { + respType := ManagementGroupsCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.ManagementGroup) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ManagementGroupsCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *ManagementGroupsCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *ManagementGroupsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ManagementGroupsClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &ManagementGroupsCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ManagementGroupsCreateOrUpdateResponse contains the response from method ManagementGroups.CreateOrUpdate. +type ManagementGroupsCreateOrUpdateResponse struct { + ManagementGroupsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsCreateOrUpdateResult contains the result from method ManagementGroups.CreateOrUpdate. +type ManagementGroupsCreateOrUpdateResult struct { + ManagementGroup +} + +// ManagementGroupsDeletePollerResponse contains the response from method ManagementGroups.Delete. +type ManagementGroupsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *ManagementGroupsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ManagementGroupsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ManagementGroupsDeleteResponse, error) { + respType := ManagementGroupsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.AzureAsyncOperationResults) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ManagementGroupsDeletePollerResponse from the provided client and resume token. +func (l *ManagementGroupsDeletePollerResponse) Resume(ctx context.Context, client *ManagementGroupsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ManagementGroupsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &ManagementGroupsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ManagementGroupsDeleteResponse contains the response from method ManagementGroups.Delete. +type ManagementGroupsDeleteResponse struct { + ManagementGroupsDeleteResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsDeleteResult contains the result from method ManagementGroups.Delete. +type ManagementGroupsDeleteResult struct { + AzureAsyncOperationResults +} + +// ManagementGroupsGetDescendantsResponse contains the response from method ManagementGroups.GetDescendants. +type ManagementGroupsGetDescendantsResponse struct { + ManagementGroupsGetDescendantsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsGetDescendantsResult contains the result from method ManagementGroups.GetDescendants. +type ManagementGroupsGetDescendantsResult struct { + DescendantListResult +} + +// ManagementGroupsGetResponse contains the response from method ManagementGroups.Get. +type ManagementGroupsGetResponse struct { + ManagementGroupsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsGetResult contains the result from method ManagementGroups.Get. +type ManagementGroupsGetResult struct { + ManagementGroup +} + +// ManagementGroupsListResponse contains the response from method ManagementGroups.List. +type ManagementGroupsListResponse struct { + ManagementGroupsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsListResult contains the result from method ManagementGroups.List. +type ManagementGroupsListResult struct { + ManagementGroupListResult +} + +// ManagementGroupsUpdateResponse contains the response from method ManagementGroups.Update. +type ManagementGroupsUpdateResponse struct { + ManagementGroupsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ManagementGroupsUpdateResult contains the result from method ManagementGroups.Update. +type ManagementGroupsUpdateResult struct { + ManagementGroup +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} diff --git a/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_time_rfc3339.go b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..c23b6f58e1cc --- /dev/null +++ b/sdk/resourcemanager/managementgroups/armmanagementgroups/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmanagementgroups + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/CHANGELOG.md b/sdk/resourcemanager/mediaservices/armmediaservices/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/LICENSE.txt b/sdk/resourcemanager/mediaservices/armmediaservices/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/README.md b/sdk/resourcemanager/mediaservices/armmediaservices/README.md new file mode 100644 index 000000000000..59d2b3101e54 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/README.md @@ -0,0 +1,76 @@ +# Azure Media Services Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mediaservices/armmediaservices)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mediaservices/armmediaservices) + +The `armmediaservices` module provides operations for working with Azure Media Services. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/mediaservices/armmediaservices) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Media Services module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mediaservices/armmediaservices +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Media Services. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Media Services + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Media Services modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armmediaservices.NewMediaservicesClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Media Services` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/autorest.md b/sdk/resourcemanager/mediaservices/armmediaservices/autorest.md new file mode 100644 index 000000000000..b7fc4b3f3366 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/c4d19b8362dfa8001c78062659ab88c529ece7b6/specification/mediaservices/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/c4d19b8362dfa8001c78062659ab88c529ece7b6/specification/mediaservices/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/build.go b/sdk/resourcemanager/mediaservices/armmediaservices/build.go new file mode 100644 index 000000000000..eb6d2010cdab --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/mediaservices/armmediaservices + +package armmediaservices diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/ci.yml b/sdk/resourcemanager/mediaservices/armmediaservices/ci.yml new file mode 100644 index 000000000000..fa0bee0d64e5 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/mediaservices/armmediaservices/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/mediaservices/armmediaservices/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/mediaservices/armmediaservices' diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/go.mod b/sdk/resourcemanager/mediaservices/armmediaservices/go.mod new file mode 100644 index 000000000000..25a425916f0e --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/mediaservices/armmediaservices + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/go.sum b/sdk/resourcemanager/mediaservices/armmediaservices/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/go_mod_tidy_hack.go b/sdk/resourcemanager/mediaservices/armmediaservices/go_mod_tidy_hack.go new file mode 100644 index 000000000000..3703fe755035 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armmediaservices + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_accountfilters_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_accountfilters_client.go new file mode 100644 index 000000000000..a8009fff16ea --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_accountfilters_client.go @@ -0,0 +1,364 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountFiltersClient contains the methods for the AccountFilters group. +// Don't use this type directly, use NewAccountFiltersClient() instead. +type AccountFiltersClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAccountFiltersClient creates a new instance of AccountFiltersClient with the specified values. +func NewAccountFiltersClient(con *arm.Connection, subscriptionID string) *AccountFiltersClient { + return &AccountFiltersClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates an Account Filter in the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountFiltersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, filterName string, parameters AccountFilter, options *AccountFiltersCreateOrUpdateOptions) (AccountFiltersCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, filterName, parameters, options) + if err != nil { + return AccountFiltersCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountFiltersCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return AccountFiltersCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AccountFiltersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, filterName string, parameters AccountFilter, options *AccountFiltersCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/accountFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AccountFiltersClient) createOrUpdateHandleResponse(resp *http.Response) (AccountFiltersCreateOrUpdateResponse, error) { + result := AccountFiltersCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountFilter); err != nil { + return AccountFiltersCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *AccountFiltersClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes an Account Filter in the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountFiltersClient) Delete(ctx context.Context, resourceGroupName string, accountName string, filterName string, options *AccountFiltersDeleteOptions) (AccountFiltersDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, filterName, options) + if err != nil { + return AccountFiltersDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountFiltersDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return AccountFiltersDeleteResponse{}, client.deleteHandleError(resp) + } + return AccountFiltersDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AccountFiltersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, filterName string, options *AccountFiltersDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/accountFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *AccountFiltersClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of an Account Filter in the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountFiltersClient) Get(ctx context.Context, resourceGroupName string, accountName string, filterName string, options *AccountFiltersGetOptions) (AccountFiltersGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, filterName, options) + if err != nil { + return AccountFiltersGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountFiltersGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountFiltersGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AccountFiltersClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, filterName string, options *AccountFiltersGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/accountFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AccountFiltersClient) getHandleResponse(resp *http.Response) (AccountFiltersGetResponse, error) { + result := AccountFiltersGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountFilter); err != nil { + return AccountFiltersGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AccountFiltersClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List Account Filters in the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountFiltersClient) List(resourceGroupName string, accountName string, options *AccountFiltersListOptions) *AccountFiltersListPager { + return &AccountFiltersListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp AccountFiltersListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AccountFilterCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AccountFiltersClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AccountFiltersListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/accountFilters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AccountFiltersClient) listHandleResponse(resp *http.Response) (AccountFiltersListResponse, error) { + result := AccountFiltersListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountFilterCollection); err != nil { + return AccountFiltersListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AccountFiltersClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing Account Filter in the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AccountFiltersClient) Update(ctx context.Context, resourceGroupName string, accountName string, filterName string, parameters AccountFilter, options *AccountFiltersUpdateOptions) (AccountFiltersUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, filterName, parameters, options) + if err != nil { + return AccountFiltersUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AccountFiltersUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AccountFiltersUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *AccountFiltersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, filterName string, parameters AccountFilter, options *AccountFiltersUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/accountFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *AccountFiltersClient) updateHandleResponse(resp *http.Response) (AccountFiltersUpdateResponse, error) { + result := AccountFiltersUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccountFilter); err != nil { + return AccountFiltersUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *AccountFiltersClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assetfilters_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assetfilters_client.go new file mode 100644 index 000000000000..fbdc8ce546fd --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assetfilters_client.go @@ -0,0 +1,384 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AssetFiltersClient contains the methods for the AssetFilters group. +// Don't use this type directly, use NewAssetFiltersClient() instead. +type AssetFiltersClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAssetFiltersClient creates a new instance of AssetFiltersClient with the specified values. +func NewAssetFiltersClient(con *arm.Connection, subscriptionID string) *AssetFiltersClient { + return &AssetFiltersClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates an Asset Filter associated with the specified Asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetFiltersClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, parameters AssetFilter, options *AssetFiltersCreateOrUpdateOptions) (AssetFiltersCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, assetName, filterName, parameters, options) + if err != nil { + return AssetFiltersCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetFiltersCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return AssetFiltersCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AssetFiltersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, parameters AssetFilter, options *AssetFiltersCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AssetFiltersClient) createOrUpdateHandleResponse(resp *http.Response) (AssetFiltersCreateOrUpdateResponse, error) { + result := AssetFiltersCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetFilter); err != nil { + return AssetFiltersCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *AssetFiltersClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes an Asset Filter associated with the specified Asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetFiltersClient) Delete(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, options *AssetFiltersDeleteOptions) (AssetFiltersDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, assetName, filterName, options) + if err != nil { + return AssetFiltersDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetFiltersDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return AssetFiltersDeleteResponse{}, client.deleteHandleError(resp) + } + return AssetFiltersDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AssetFiltersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, options *AssetFiltersDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *AssetFiltersClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of an Asset Filter associated with the specified Asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetFiltersClient) Get(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, options *AssetFiltersGetOptions) (AssetFiltersGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, assetName, filterName, options) + if err != nil { + return AssetFiltersGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetFiltersGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetFiltersGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AssetFiltersClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, options *AssetFiltersGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AssetFiltersClient) getHandleResponse(resp *http.Response) (AssetFiltersGetResponse, error) { + result := AssetFiltersGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetFilter); err != nil { + return AssetFiltersGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AssetFiltersClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List Asset Filters associated with the specified Asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetFiltersClient) List(resourceGroupName string, accountName string, assetName string, options *AssetFiltersListOptions) *AssetFiltersListPager { + return &AssetFiltersListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, assetName, options) + }, + advancer: func(ctx context.Context, resp AssetFiltersListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AssetFilterCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AssetFiltersClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetFiltersListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AssetFiltersClient) listHandleResponse(resp *http.Response) (AssetFiltersListResponse, error) { + result := AssetFiltersListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetFilterCollection); err != nil { + return AssetFiltersListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AssetFiltersClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing Asset Filter associated with the specified Asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetFiltersClient) Update(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, parameters AssetFilter, options *AssetFiltersUpdateOptions) (AssetFiltersUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, assetName, filterName, parameters, options) + if err != nil { + return AssetFiltersUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetFiltersUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetFiltersUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *AssetFiltersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, filterName string, parameters AssetFilter, options *AssetFiltersUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/assetFilters/{filterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + if filterName == "" { + return nil, errors.New("parameter filterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{filterName}", url.PathEscape(filterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *AssetFiltersClient) updateHandleResponse(resp *http.Response) (AssetFiltersUpdateResponse, error) { + result := AssetFiltersUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetFilter); err != nil { + return AssetFiltersUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *AssetFiltersClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assets_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assets_client.go new file mode 100644 index 000000000000..b22519a586ea --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_assets_client.go @@ -0,0 +1,582 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AssetsClient contains the methods for the Assets group. +// Don't use this type directly, use NewAssetsClient() instead. +type AssetsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAssetsClient creates a new instance of AssetsClient with the specified values. +func NewAssetsClient(con *arm.Connection, subscriptionID string) *AssetsClient { + return &AssetsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates an Asset in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters Asset, options *AssetsCreateOrUpdateOptions) (AssetsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, assetName, parameters, options) + if err != nil { + return AssetsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return AssetsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *AssetsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters Asset, options *AssetsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *AssetsClient) createOrUpdateHandleResponse(resp *http.Response) (AssetsCreateOrUpdateResponse, error) { + result := AssetsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Asset); err != nil { + return AssetsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *AssetsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes an Asset in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsDeleteOptions) (AssetsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, assetName, options) + if err != nil { + return AssetsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return AssetsDeleteResponse{}, client.deleteHandleError(resp) + } + return AssetsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *AssetsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *AssetsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of an Asset in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) Get(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsGetOptions) (AssetsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, assetName, options) + if err != nil { + return AssetsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AssetsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AssetsClient) getHandleResponse(resp *http.Response) (AssetsGetResponse, error) { + result := AssetsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Asset); err != nil { + return AssetsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AssetsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetEncryptionKey - Gets the Asset storage encryption keys used to decrypt content created by version 2 of the Media Services API +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) GetEncryptionKey(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsGetEncryptionKeyOptions) (AssetsGetEncryptionKeyResponse, error) { + req, err := client.getEncryptionKeyCreateRequest(ctx, resourceGroupName, accountName, assetName, options) + if err != nil { + return AssetsGetEncryptionKeyResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsGetEncryptionKeyResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetsGetEncryptionKeyResponse{}, client.getEncryptionKeyHandleError(resp) + } + return client.getEncryptionKeyHandleResponse(resp) +} + +// getEncryptionKeyCreateRequest creates the GetEncryptionKey request. +func (client *AssetsClient) getEncryptionKeyCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsGetEncryptionKeyOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/getEncryptionKey" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getEncryptionKeyHandleResponse handles the GetEncryptionKey response. +func (client *AssetsClient) getEncryptionKeyHandleResponse(resp *http.Response) (AssetsGetEncryptionKeyResponse, error) { + result := AssetsGetEncryptionKeyResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StorageEncryptedAssetDecryptionData); err != nil { + return AssetsGetEncryptionKeyResponse{}, err + } + return result, nil +} + +// getEncryptionKeyHandleError handles the GetEncryptionKey error response. +func (client *AssetsClient) getEncryptionKeyHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List Assets in the Media Services account with optional filtering and ordering +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) List(resourceGroupName string, accountName string, options *AssetsListOptions) *AssetsListPager { + return &AssetsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp AssetsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AssetCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AssetsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *AssetsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AssetsClient) listHandleResponse(resp *http.Response) (AssetsListResponse, error) { + result := AssetsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetCollection); err != nil { + return AssetsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AssetsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListContainerSas - Lists storage container URLs with shared access signatures (SAS) for uploading and downloading Asset content. The signatures are derived +// from the storage account keys. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) ListContainerSas(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters ListContainerSasInput, options *AssetsListContainerSasOptions) (AssetsListContainerSasResponse, error) { + req, err := client.listContainerSasCreateRequest(ctx, resourceGroupName, accountName, assetName, parameters, options) + if err != nil { + return AssetsListContainerSasResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsListContainerSasResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetsListContainerSasResponse{}, client.listContainerSasHandleError(resp) + } + return client.listContainerSasHandleResponse(resp) +} + +// listContainerSasCreateRequest creates the ListContainerSas request. +func (client *AssetsClient) listContainerSasCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters ListContainerSasInput, options *AssetsListContainerSasOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/listContainerSas" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// listContainerSasHandleResponse handles the ListContainerSas response. +func (client *AssetsClient) listContainerSasHandleResponse(resp *http.Response) (AssetsListContainerSasResponse, error) { + result := AssetsListContainerSasResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AssetContainerSas); err != nil { + return AssetsListContainerSasResponse{}, err + } + return result, nil +} + +// listContainerSasHandleError handles the ListContainerSas error response. +func (client *AssetsClient) listContainerSasHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListStreamingLocators - Lists Streaming Locators which are associated with this asset. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) ListStreamingLocators(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsListStreamingLocatorsOptions) (AssetsListStreamingLocatorsResponse, error) { + req, err := client.listStreamingLocatorsCreateRequest(ctx, resourceGroupName, accountName, assetName, options) + if err != nil { + return AssetsListStreamingLocatorsResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsListStreamingLocatorsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetsListStreamingLocatorsResponse{}, client.listStreamingLocatorsHandleError(resp) + } + return client.listStreamingLocatorsHandleResponse(resp) +} + +// listStreamingLocatorsCreateRequest creates the ListStreamingLocators request. +func (client *AssetsClient) listStreamingLocatorsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, options *AssetsListStreamingLocatorsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}/listStreamingLocators" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listStreamingLocatorsHandleResponse handles the ListStreamingLocators response. +func (client *AssetsClient) listStreamingLocatorsHandleResponse(resp *http.Response) (AssetsListStreamingLocatorsResponse, error) { + result := AssetsListStreamingLocatorsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ListStreamingLocatorsResponse); err != nil { + return AssetsListStreamingLocatorsResponse{}, err + } + return result, nil +} + +// listStreamingLocatorsHandleError handles the ListStreamingLocators error response. +func (client *AssetsClient) listStreamingLocatorsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing Asset in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *AssetsClient) Update(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters Asset, options *AssetsUpdateOptions) (AssetsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, assetName, parameters, options) + if err != nil { + return AssetsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AssetsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AssetsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *AssetsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, assetName string, parameters Asset, options *AssetsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/assets/{assetName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if assetName == "" { + return nil, errors.New("parameter assetName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{assetName}", url.PathEscape(assetName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *AssetsClient) updateHandleResponse(resp *http.Response) (AssetsUpdateResponse, error) { + result := AssetsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Asset); err != nil { + return AssetsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *AssetsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_constants.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_constants.go new file mode 100644 index 000000000000..444387ff1ed8 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_constants.go @@ -0,0 +1,1737 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +const ( + module = "armmediaservices" + version = "v0.1.1" +) + +// AacAudioProfile - The encoding profile to be used when encoding audio with AAC. +type AacAudioProfile string + +const ( + // AacAudioProfileAacLc - Specifies that the output audio is to be encoded into AAC Low Complexity profile (AAC-LC). + AacAudioProfileAacLc AacAudioProfile = "AacLc" + // AacAudioProfileHeAacV1 - Specifies that the output audio is to be encoded into HE-AAC v1 profile. + AacAudioProfileHeAacV1 AacAudioProfile = "HeAacV1" + // AacAudioProfileHeAacV2 - Specifies that the output audio is to be encoded into HE-AAC v2 profile. + AacAudioProfileHeAacV2 AacAudioProfile = "HeAacV2" +) + +// PossibleAacAudioProfileValues returns the possible values for the AacAudioProfile const type. +func PossibleAacAudioProfileValues() []AacAudioProfile { + return []AacAudioProfile{ + AacAudioProfileAacLc, + AacAudioProfileHeAacV1, + AacAudioProfileHeAacV2, + } +} + +// ToPtr returns a *AacAudioProfile pointing to the current value. +func (c AacAudioProfile) ToPtr() *AacAudioProfile { + return &c +} + +// AccountEncryptionKeyType - The type of key used to encrypt the Account Key. +type AccountEncryptionKeyType string + +const ( + // AccountEncryptionKeyTypeCustomerKey - The Account Key is encrypted with a Customer Key. + AccountEncryptionKeyTypeCustomerKey AccountEncryptionKeyType = "CustomerKey" + // AccountEncryptionKeyTypeSystemKey - The Account Key is encrypted with a System Key. + AccountEncryptionKeyTypeSystemKey AccountEncryptionKeyType = "SystemKey" +) + +// PossibleAccountEncryptionKeyTypeValues returns the possible values for the AccountEncryptionKeyType const type. +func PossibleAccountEncryptionKeyTypeValues() []AccountEncryptionKeyType { + return []AccountEncryptionKeyType{ + AccountEncryptionKeyTypeCustomerKey, + AccountEncryptionKeyTypeSystemKey, + } +} + +// ToPtr returns a *AccountEncryptionKeyType pointing to the current value. +func (c AccountEncryptionKeyType) ToPtr() *AccountEncryptionKeyType { + return &c +} + +// ActionType - Indicates the action type. +type ActionType string + +const ( + // ActionTypeInternal - An internal action. + ActionTypeInternal ActionType = "Internal" +) + +// PossibleActionTypeValues returns the possible values for the ActionType const type. +func PossibleActionTypeValues() []ActionType { + return []ActionType{ + ActionTypeInternal, + } +} + +// ToPtr returns a *ActionType pointing to the current value. +func (c ActionType) ToPtr() *ActionType { + return &c +} + +// AnalysisResolution - 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. +type AnalysisResolution string + +const ( + AnalysisResolutionSourceResolution AnalysisResolution = "SourceResolution" + AnalysisResolutionStandardDefinition AnalysisResolution = "StandardDefinition" +) + +// PossibleAnalysisResolutionValues returns the possible values for the AnalysisResolution const type. +func PossibleAnalysisResolutionValues() []AnalysisResolution { + return []AnalysisResolution{ + AnalysisResolutionSourceResolution, + AnalysisResolutionStandardDefinition, + } +} + +// ToPtr returns a *AnalysisResolution pointing to the current value. +func (c AnalysisResolution) ToPtr() *AnalysisResolution { + return &c +} + +// AssetContainerPermission - The permissions to set on the SAS URL. +type AssetContainerPermission string + +const ( + // AssetContainerPermissionRead - The SAS URL will allow read access to the container. + AssetContainerPermissionRead AssetContainerPermission = "Read" + // AssetContainerPermissionReadWrite - The SAS URL will allow read and write access to the container. + AssetContainerPermissionReadWrite AssetContainerPermission = "ReadWrite" + // AssetContainerPermissionReadWriteDelete - The SAS URL will allow read, write and delete access to the container. + AssetContainerPermissionReadWriteDelete AssetContainerPermission = "ReadWriteDelete" +) + +// PossibleAssetContainerPermissionValues returns the possible values for the AssetContainerPermission const type. +func PossibleAssetContainerPermissionValues() []AssetContainerPermission { + return []AssetContainerPermission{ + AssetContainerPermissionRead, + AssetContainerPermissionReadWrite, + AssetContainerPermissionReadWriteDelete, + } +} + +// ToPtr returns a *AssetContainerPermission pointing to the current value. +func (c AssetContainerPermission) ToPtr() *AssetContainerPermission { + return &c +} + +// AssetStorageEncryptionFormat - The Asset encryption format. One of None or MediaStorageEncryption. +type AssetStorageEncryptionFormat string + +const ( + // AssetStorageEncryptionFormatMediaStorageClientEncryption - The Asset is encrypted with Media Services client-side encryption. + AssetStorageEncryptionFormatMediaStorageClientEncryption AssetStorageEncryptionFormat = "MediaStorageClientEncryption" + // AssetStorageEncryptionFormatNone - The Asset does not use client-side storage encryption (this is the only allowed value for new Assets). + AssetStorageEncryptionFormatNone AssetStorageEncryptionFormat = "None" +) + +// PossibleAssetStorageEncryptionFormatValues returns the possible values for the AssetStorageEncryptionFormat const type. +func PossibleAssetStorageEncryptionFormatValues() []AssetStorageEncryptionFormat { + return []AssetStorageEncryptionFormat{ + AssetStorageEncryptionFormatMediaStorageClientEncryption, + AssetStorageEncryptionFormatNone, + } +} + +// ToPtr returns a *AssetStorageEncryptionFormat pointing to the current value. +func (c AssetStorageEncryptionFormat) ToPtr() *AssetStorageEncryptionFormat { + return &c +} + +// AttributeFilter - The type of AttributeFilter to apply to the TrackAttribute in order to select the tracks. +type AttributeFilter string + +const ( + // AttributeFilterAll - All tracks will be included. + AttributeFilterAll AttributeFilter = "All" + // AttributeFilterBottom - The first track will be included when the attribute is sorted in ascending order. Generally used to select the smallest bitrate. + AttributeFilterBottom AttributeFilter = "Bottom" + // AttributeFilterTop - The first track will be included when the attribute is sorted in descending order. Generally used to select the largest bitrate. + AttributeFilterTop AttributeFilter = "Top" + // AttributeFilterValueEquals - Any tracks that have an attribute equal to the value given will be included. + AttributeFilterValueEquals AttributeFilter = "ValueEquals" +) + +// PossibleAttributeFilterValues returns the possible values for the AttributeFilter const type. +func PossibleAttributeFilterValues() []AttributeFilter { + return []AttributeFilter{ + AttributeFilterAll, + AttributeFilterBottom, + AttributeFilterTop, + AttributeFilterValueEquals, + } +} + +// ToPtr returns a *AttributeFilter pointing to the current value. +func (c AttributeFilter) ToPtr() *AttributeFilter { + return &c +} + +// AudioAnalysisMode - Determines the set of audio analysis operations to be performed. If unspecified, the Standard AudioAnalysisMode would be chosen. +type AudioAnalysisMode string + +const ( + // AudioAnalysisModeBasic - This mode performs speech-to-text transcription and generation of a VTT subtitle/caption file. The output of this mode includes + // an Insights JSON file including only the keywords, transcription,and timing information. Automatic language detection and speaker diarization are not + // included in this mode. + AudioAnalysisModeBasic AudioAnalysisMode = "Basic" + // AudioAnalysisModeStandard - Performs all operations included in the Basic mode, additionally performing language detection and speaker diarization. + AudioAnalysisModeStandard AudioAnalysisMode = "Standard" +) + +// PossibleAudioAnalysisModeValues returns the possible values for the AudioAnalysisMode const type. +func PossibleAudioAnalysisModeValues() []AudioAnalysisMode { + return []AudioAnalysisMode{ + AudioAnalysisModeBasic, + AudioAnalysisModeStandard, + } +} + +// ToPtr returns a *AudioAnalysisMode pointing to the current value. +func (c AudioAnalysisMode) ToPtr() *AudioAnalysisMode { + return &c +} + +// BlurType - Blur type +type BlurType string + +const ( + // BlurTypeBlack - Black: Black out filter + BlurTypeBlack BlurType = "Black" + // BlurTypeBox - Box: debug filter, bounding box only + BlurTypeBox BlurType = "Box" + // BlurTypeHigh - High: Confuse blur filter + BlurTypeHigh BlurType = "High" + // BlurTypeLow - Low: box-car blur filter + BlurTypeLow BlurType = "Low" + // BlurTypeMed - Med: Gaussian blur filter + BlurTypeMed BlurType = "Med" +) + +// PossibleBlurTypeValues returns the possible values for the BlurType const type. +func PossibleBlurTypeValues() []BlurType { + return []BlurType{ + BlurTypeBlack, + BlurTypeBox, + BlurTypeHigh, + BlurTypeLow, + BlurTypeMed, + } +} + +// ToPtr returns a *BlurType pointing to the current value. +func (c BlurType) ToPtr() *BlurType { + return &c +} + +// ChannelMapping - Optional designation for single channel audio tracks. Can be used to combine the tracks into stereo or multi-channel audio tracks. +type ChannelMapping string + +const ( + // ChannelMappingBackLeft - The Back Left Channel. Sometimes referred to as the Left Surround Channel. + ChannelMappingBackLeft ChannelMapping = "BackLeft" + // ChannelMappingBackRight - The Back Right Channel. Sometimes referred to as the Right Surround Channel. + ChannelMappingBackRight ChannelMapping = "BackRight" + // ChannelMappingCenter - The Center Channel. + ChannelMappingCenter ChannelMapping = "Center" + // ChannelMappingFrontLeft - The Front Left Channel. + ChannelMappingFrontLeft ChannelMapping = "FrontLeft" + // ChannelMappingFrontRight - The Front Right Channel. + ChannelMappingFrontRight ChannelMapping = "FrontRight" + // ChannelMappingLowFrequencyEffects - Low Frequency Effects Channel. Sometimes referred to as the Subwoofer. + ChannelMappingLowFrequencyEffects ChannelMapping = "LowFrequencyEffects" + // ChannelMappingStereoLeft - The Left Stereo channel. Sometimes referred to as Down Mix Left. + ChannelMappingStereoLeft ChannelMapping = "StereoLeft" + // ChannelMappingStereoRight - The Right Stereo channel. Sometimes referred to as Down Mix Right. + ChannelMappingStereoRight ChannelMapping = "StereoRight" +) + +// PossibleChannelMappingValues returns the possible values for the ChannelMapping const type. +func PossibleChannelMappingValues() []ChannelMapping { + return []ChannelMapping{ + ChannelMappingBackLeft, + ChannelMappingBackRight, + ChannelMappingCenter, + ChannelMappingFrontLeft, + ChannelMappingFrontRight, + ChannelMappingLowFrequencyEffects, + ChannelMappingStereoLeft, + ChannelMappingStereoRight, + } +} + +// ToPtr returns a *ChannelMapping pointing to the current value. +func (c ChannelMapping) ToPtr() *ChannelMapping { + return &c +} + +// Complexity - Allows you to configure the encoder settings to control the balance between speed and quality. Example: set Complexity as Speed for faster +// encoding but less compression efficiency. +type Complexity string + +const ( + // ComplexityBalanced - Configures the encoder to use settings that achieve a balance between speed and quality. + ComplexityBalanced Complexity = "Balanced" + // ComplexityQuality - Configures the encoder to use settings optimized to produce higher quality output at the expense of slower overall encode time. + ComplexityQuality Complexity = "Quality" + // ComplexitySpeed - Configures the encoder to use settings optimized for faster encoding. Quality is sacrificed to decrease encoding time. + ComplexitySpeed Complexity = "Speed" +) + +// PossibleComplexityValues returns the possible values for the Complexity const type. +func PossibleComplexityValues() []Complexity { + return []Complexity{ + ComplexityBalanced, + ComplexityQuality, + ComplexitySpeed, + } +} + +// ToPtr returns a *Complexity pointing to the current value. +func (c Complexity) ToPtr() *Complexity { + return &c +} + +// ContentKeyPolicyFairPlayRentalAndLeaseKeyType - The rental and lease key type. +type ContentKeyPolicyFairPlayRentalAndLeaseKeyType string + +const ( + // ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeDualExpiry - Dual expiry for offline rental. + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeDualExpiry ContentKeyPolicyFairPlayRentalAndLeaseKeyType = "DualExpiry" + // ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentLimited - Content key can be persisted and the valid duration is limited by the Rental Duration + // value + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentLimited ContentKeyPolicyFairPlayRentalAndLeaseKeyType = "PersistentLimited" + // ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentUnlimited - Content key can be persisted with an unlimited duration + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentUnlimited ContentKeyPolicyFairPlayRentalAndLeaseKeyType = "PersistentUnlimited" + // ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUndefined - Key duration is not specified. + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUndefined ContentKeyPolicyFairPlayRentalAndLeaseKeyType = "Undefined" + // ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUnknown - Represents a ContentKeyPolicyFairPlayRentalAndLeaseKeyType that is unavailable in current API + // version. + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUnknown ContentKeyPolicyFairPlayRentalAndLeaseKeyType = "Unknown" +) + +// PossibleContentKeyPolicyFairPlayRentalAndLeaseKeyTypeValues returns the possible values for the ContentKeyPolicyFairPlayRentalAndLeaseKeyType const type. +func PossibleContentKeyPolicyFairPlayRentalAndLeaseKeyTypeValues() []ContentKeyPolicyFairPlayRentalAndLeaseKeyType { + return []ContentKeyPolicyFairPlayRentalAndLeaseKeyType{ + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeDualExpiry, + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentLimited, + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypePersistentUnlimited, + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUndefined, + ContentKeyPolicyFairPlayRentalAndLeaseKeyTypeUnknown, + } +} + +// ToPtr returns a *ContentKeyPolicyFairPlayRentalAndLeaseKeyType pointing to the current value. +func (c ContentKeyPolicyFairPlayRentalAndLeaseKeyType) ToPtr() *ContentKeyPolicyFairPlayRentalAndLeaseKeyType { + return &c +} + +// ContentKeyPolicyPlayReadyContentType - The PlayReady content type. +type ContentKeyPolicyPlayReadyContentType string + +const ( + // ContentKeyPolicyPlayReadyContentTypeUltraVioletDownload - Ultraviolet download content type. + ContentKeyPolicyPlayReadyContentTypeUltraVioletDownload ContentKeyPolicyPlayReadyContentType = "UltraVioletDownload" + // ContentKeyPolicyPlayReadyContentTypeUltraVioletStreaming - Ultraviolet streaming content type. + ContentKeyPolicyPlayReadyContentTypeUltraVioletStreaming ContentKeyPolicyPlayReadyContentType = "UltraVioletStreaming" + // ContentKeyPolicyPlayReadyContentTypeUnknown - Represents a ContentKeyPolicyPlayReadyContentType that is unavailable in current API version. + ContentKeyPolicyPlayReadyContentTypeUnknown ContentKeyPolicyPlayReadyContentType = "Unknown" + // ContentKeyPolicyPlayReadyContentTypeUnspecified - Unspecified content type. + ContentKeyPolicyPlayReadyContentTypeUnspecified ContentKeyPolicyPlayReadyContentType = "Unspecified" +) + +// PossibleContentKeyPolicyPlayReadyContentTypeValues returns the possible values for the ContentKeyPolicyPlayReadyContentType const type. +func PossibleContentKeyPolicyPlayReadyContentTypeValues() []ContentKeyPolicyPlayReadyContentType { + return []ContentKeyPolicyPlayReadyContentType{ + ContentKeyPolicyPlayReadyContentTypeUltraVioletDownload, + ContentKeyPolicyPlayReadyContentTypeUltraVioletStreaming, + ContentKeyPolicyPlayReadyContentTypeUnknown, + ContentKeyPolicyPlayReadyContentTypeUnspecified, + } +} + +// ToPtr returns a *ContentKeyPolicyPlayReadyContentType pointing to the current value. +func (c ContentKeyPolicyPlayReadyContentType) ToPtr() *ContentKeyPolicyPlayReadyContentType { + return &c +} + +// ContentKeyPolicyPlayReadyLicenseType - The license type. +type ContentKeyPolicyPlayReadyLicenseType string + +const ( + // ContentKeyPolicyPlayReadyLicenseTypeNonPersistent - Non persistent license. + ContentKeyPolicyPlayReadyLicenseTypeNonPersistent ContentKeyPolicyPlayReadyLicenseType = "NonPersistent" + // ContentKeyPolicyPlayReadyLicenseTypePersistent - Persistent license. Allows offline playback. + ContentKeyPolicyPlayReadyLicenseTypePersistent ContentKeyPolicyPlayReadyLicenseType = "Persistent" + // ContentKeyPolicyPlayReadyLicenseTypeUnknown - Represents a ContentKeyPolicyPlayReadyLicenseType that is unavailable in current API version. + ContentKeyPolicyPlayReadyLicenseTypeUnknown ContentKeyPolicyPlayReadyLicenseType = "Unknown" +) + +// PossibleContentKeyPolicyPlayReadyLicenseTypeValues returns the possible values for the ContentKeyPolicyPlayReadyLicenseType const type. +func PossibleContentKeyPolicyPlayReadyLicenseTypeValues() []ContentKeyPolicyPlayReadyLicenseType { + return []ContentKeyPolicyPlayReadyLicenseType{ + ContentKeyPolicyPlayReadyLicenseTypeNonPersistent, + ContentKeyPolicyPlayReadyLicenseTypePersistent, + ContentKeyPolicyPlayReadyLicenseTypeUnknown, + } +} + +// ToPtr returns a *ContentKeyPolicyPlayReadyLicenseType pointing to the current value. +func (c ContentKeyPolicyPlayReadyLicenseType) ToPtr() *ContentKeyPolicyPlayReadyLicenseType { + return &c +} + +// ContentKeyPolicyPlayReadyUnknownOutputPassingOption - Configures Unknown output handling settings of the license. +type ContentKeyPolicyPlayReadyUnknownOutputPassingOption string + +const ( + // ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowed - Passing the video portion of protected content to an Unknown Output is allowed. + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowed ContentKeyPolicyPlayReadyUnknownOutputPassingOption = "Allowed" + // ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowedWithVideoConstriction - Passing the video portion of protected content to an Unknown Output + // is allowed but with constrained resolution. + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowedWithVideoConstriction ContentKeyPolicyPlayReadyUnknownOutputPassingOption = "AllowedWithVideoConstriction" + // ContentKeyPolicyPlayReadyUnknownOutputPassingOptionNotAllowed - Passing the video portion of protected content to an Unknown Output is not allowed. + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionNotAllowed ContentKeyPolicyPlayReadyUnknownOutputPassingOption = "NotAllowed" + // ContentKeyPolicyPlayReadyUnknownOutputPassingOptionUnknown - Represents a ContentKeyPolicyPlayReadyUnknownOutputPassingOption that is unavailable in + // current API version. + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionUnknown ContentKeyPolicyPlayReadyUnknownOutputPassingOption = "Unknown" +) + +// PossibleContentKeyPolicyPlayReadyUnknownOutputPassingOptionValues returns the possible values for the ContentKeyPolicyPlayReadyUnknownOutputPassingOption const type. +func PossibleContentKeyPolicyPlayReadyUnknownOutputPassingOptionValues() []ContentKeyPolicyPlayReadyUnknownOutputPassingOption { + return []ContentKeyPolicyPlayReadyUnknownOutputPassingOption{ + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowed, + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionAllowedWithVideoConstriction, + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionNotAllowed, + ContentKeyPolicyPlayReadyUnknownOutputPassingOptionUnknown, + } +} + +// ToPtr returns a *ContentKeyPolicyPlayReadyUnknownOutputPassingOption pointing to the current value. +func (c ContentKeyPolicyPlayReadyUnknownOutputPassingOption) ToPtr() *ContentKeyPolicyPlayReadyUnknownOutputPassingOption { + return &c +} + +// ContentKeyPolicyRestrictionTokenType - The type of token. +type ContentKeyPolicyRestrictionTokenType string + +const ( + // ContentKeyPolicyRestrictionTokenTypeJwt - JSON Web Token. + ContentKeyPolicyRestrictionTokenTypeJwt ContentKeyPolicyRestrictionTokenType = "Jwt" + // ContentKeyPolicyRestrictionTokenTypeSwt - Simple Web Token. + ContentKeyPolicyRestrictionTokenTypeSwt ContentKeyPolicyRestrictionTokenType = "Swt" + // ContentKeyPolicyRestrictionTokenTypeUnknown - Represents a ContentKeyPolicyRestrictionTokenType that is unavailable in current API version. + ContentKeyPolicyRestrictionTokenTypeUnknown ContentKeyPolicyRestrictionTokenType = "Unknown" +) + +// PossibleContentKeyPolicyRestrictionTokenTypeValues returns the possible values for the ContentKeyPolicyRestrictionTokenType const type. +func PossibleContentKeyPolicyRestrictionTokenTypeValues() []ContentKeyPolicyRestrictionTokenType { + return []ContentKeyPolicyRestrictionTokenType{ + ContentKeyPolicyRestrictionTokenTypeJwt, + ContentKeyPolicyRestrictionTokenTypeSwt, + ContentKeyPolicyRestrictionTokenTypeUnknown, + } +} + +// ToPtr returns a *ContentKeyPolicyRestrictionTokenType pointing to the current value. +func (c ContentKeyPolicyRestrictionTokenType) ToPtr() *ContentKeyPolicyRestrictionTokenType { + return &c +} + +// CreatedByType - The type of identity that created the resource. +type CreatedByType string + +const ( + CreatedByTypeApplication CreatedByType = "Application" + CreatedByTypeKey CreatedByType = "Key" + CreatedByTypeManagedIdentity CreatedByType = "ManagedIdentity" + CreatedByTypeUser CreatedByType = "User" +) + +// PossibleCreatedByTypeValues returns the possible values for the CreatedByType const type. +func PossibleCreatedByTypeValues() []CreatedByType { + return []CreatedByType{ + CreatedByTypeApplication, + CreatedByTypeKey, + CreatedByTypeManagedIdentity, + CreatedByTypeUser, + } +} + +// ToPtr returns a *CreatedByType pointing to the current value. +func (c CreatedByType) ToPtr() *CreatedByType { + return &c +} + +// DefaultAction - The behavior for IP access control in Key Delivery. +type DefaultAction string + +const ( + // DefaultActionAllow - All public IP addresses are allowed. + DefaultActionAllow DefaultAction = "Allow" + // DefaultActionDeny - Public IP addresses are blocked. + DefaultActionDeny DefaultAction = "Deny" +) + +// PossibleDefaultActionValues returns the possible values for the DefaultAction const type. +func PossibleDefaultActionValues() []DefaultAction { + return []DefaultAction{ + DefaultActionAllow, + DefaultActionDeny, + } +} + +// ToPtr returns a *DefaultAction pointing to the current value. +func (c DefaultAction) ToPtr() *DefaultAction { + return &c +} + +// DeinterlaceMode - The deinterlacing mode. Defaults to AutoPixelAdaptive. +type DeinterlaceMode string + +const ( + // DeinterlaceModeAutoPixelAdaptive - Apply automatic pixel adaptive de-interlacing on each frame in the input video. + DeinterlaceModeAutoPixelAdaptive DeinterlaceMode = "AutoPixelAdaptive" + // DeinterlaceModeOff - Disables de-interlacing of the source video. + DeinterlaceModeOff DeinterlaceMode = "Off" +) + +// PossibleDeinterlaceModeValues returns the possible values for the DeinterlaceMode const type. +func PossibleDeinterlaceModeValues() []DeinterlaceMode { + return []DeinterlaceMode{ + DeinterlaceModeAutoPixelAdaptive, + DeinterlaceModeOff, + } +} + +// ToPtr returns a *DeinterlaceMode pointing to the current value. +func (c DeinterlaceMode) ToPtr() *DeinterlaceMode { + return &c +} + +// DeinterlaceParity - The field parity for de-interlacing, defaults to Auto. +type DeinterlaceParity string + +const ( + // DeinterlaceParityAuto - Automatically detect the order of fields + DeinterlaceParityAuto DeinterlaceParity = "Auto" + // DeinterlaceParityBottomFieldFirst - Apply bottom field first processing of input video. + DeinterlaceParityBottomFieldFirst DeinterlaceParity = "BottomFieldFirst" + // DeinterlaceParityTopFieldFirst - Apply top field first processing of input video. + DeinterlaceParityTopFieldFirst DeinterlaceParity = "TopFieldFirst" +) + +// PossibleDeinterlaceParityValues returns the possible values for the DeinterlaceParity const type. +func PossibleDeinterlaceParityValues() []DeinterlaceParity { + return []DeinterlaceParity{ + DeinterlaceParityAuto, + DeinterlaceParityBottomFieldFirst, + DeinterlaceParityTopFieldFirst, + } +} + +// ToPtr returns a *DeinterlaceParity pointing to the current value. +func (c DeinterlaceParity) ToPtr() *DeinterlaceParity { + return &c +} + +// EncoderNamedPreset - The built-in preset to be used for encoding videos. +type EncoderNamedPreset string + +const ( + // EncoderNamedPresetAACGoodQualityAudio - Produces a single MP4 file containing only stereo audio encoded at 192 kbps. + EncoderNamedPresetAACGoodQualityAudio EncoderNamedPreset = "AACGoodQualityAudio" + // EncoderNamedPresetAdaptiveStreaming - Produces a set of GOP aligned MP4 files with H.264 video and stereo AAC audio. Auto-generates a bitrate ladder + // based on the input resolution, bitrate and frame rate. The auto-generated preset will never exceed the input resolution. For example, if the input is + // 720p, output will remain 720p at best. + EncoderNamedPresetAdaptiveStreaming EncoderNamedPreset = "AdaptiveStreaming" + // EncoderNamedPresetContentAwareEncoding - Produces a set of GOP-aligned MP4s by using content-aware encoding. Given any input content, the service performs + // an initial lightweight analysis of the input content, and uses the results to determine the optimal number of layers, appropriate bitrate and resolution + // settings for delivery by adaptive streaming. This preset is particularly effective for low and medium complexity videos, where the output files will + // be at lower bitrates but at a quality that still delivers a good experience to viewers. The output will contain MP4 files with video and audio interleaved. + EncoderNamedPresetContentAwareEncoding EncoderNamedPreset = "ContentAwareEncoding" + // EncoderNamedPresetContentAwareEncodingExperimental - Exposes an experimental preset for content-aware encoding. Given any input content, the service + // attempts to automatically determine the optimal number of layers, appropriate bitrate and resolution settings for delivery by adaptive streaming. The + // underlying algorithms will continue to evolve over time. The output will contain MP4 files with video and audio interleaved. + EncoderNamedPresetContentAwareEncodingExperimental EncoderNamedPreset = "ContentAwareEncodingExperimental" + // EncoderNamedPresetCopyAllBitrateNonInterleaved - Copy all video and audio streams from the input asset as non-interleaved video and audio output files. + // This preset can be used to clip an existing asset or convert a group of key frame (GOP) aligned MP4 files as an asset that can be streamed. + EncoderNamedPresetCopyAllBitrateNonInterleaved EncoderNamedPreset = "CopyAllBitrateNonInterleaved" + // EncoderNamedPresetH264MultipleBitrate1080P - Produces a set of 8 GOP-aligned MP4 files, ranging from 6000 kbps to 400 kbps, and stereo AAC audio. Resolution + // starts at 1080p and goes down to 180p. + EncoderNamedPresetH264MultipleBitrate1080P EncoderNamedPreset = "H264MultipleBitrate1080p" + // EncoderNamedPresetH264MultipleBitrate720P - Produces a set of 6 GOP-aligned MP4 files, ranging from 3400 kbps to 400 kbps, and stereo AAC audio. Resolution + // starts at 720p and goes down to 180p. + EncoderNamedPresetH264MultipleBitrate720P EncoderNamedPreset = "H264MultipleBitrate720p" + // EncoderNamedPresetH264MultipleBitrateSD - Produces a set of 5 GOP-aligned MP4 files, ranging from 1900kbps to 400 kbps, and stereo AAC audio. Resolution + // starts at 480p and goes down to 240p. + EncoderNamedPresetH264MultipleBitrateSD EncoderNamedPreset = "H264MultipleBitrateSD" + // EncoderNamedPresetH264SingleBitrate1080P - Produces an MP4 file where the video is encoded with H.264 codec at 6750 kbps and a picture height of 1080 + // pixels, and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH264SingleBitrate1080P EncoderNamedPreset = "H264SingleBitrate1080p" + // EncoderNamedPresetH264SingleBitrate720P - Produces an MP4 file where the video is encoded with H.264 codec at 4500 kbps and a picture height of 720 pixels, + // and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH264SingleBitrate720P EncoderNamedPreset = "H264SingleBitrate720p" + // EncoderNamedPresetH264SingleBitrateSD - Produces an MP4 file where the video is encoded with H.264 codec at 2200 kbps and a picture height of 480 pixels, + // and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH264SingleBitrateSD EncoderNamedPreset = "H264SingleBitrateSD" + // EncoderNamedPresetH265AdaptiveStreaming - Produces a set of GOP aligned MP4 files with H.265 video and stereo AAC audio. Auto-generates a bitrate ladder + // based on the input resolution, bitrate and frame rate. The auto-generated preset will never exceed the input resolution. For example, if the input is + // 720p, output will remain 720p at best. + EncoderNamedPresetH265AdaptiveStreaming EncoderNamedPreset = "H265AdaptiveStreaming" + // EncoderNamedPresetH265ContentAwareEncoding - Produces a set of GOP-aligned MP4s by using content-aware encoding. Given any input content, the service + // performs an initial lightweight analysis of the input content, and uses the results to determine the optimal number of layers, appropriate bitrate and + // resolution settings for delivery by adaptive streaming. This preset is particularly effective for low and medium complexity videos, where the output + // files will be at lower bitrates but at a quality that still delivers a good experience to viewers. The output will contain MP4 files with video and audio + // interleaved. + EncoderNamedPresetH265ContentAwareEncoding EncoderNamedPreset = "H265ContentAwareEncoding" + // EncoderNamedPresetH265SingleBitrate1080P - Produces an MP4 file where the video is encoded with H.265 codec at 3500 kbps and a picture height of 1080 + // pixels, and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH265SingleBitrate1080P EncoderNamedPreset = "H265SingleBitrate1080p" + // EncoderNamedPresetH265SingleBitrate4K - Produces an MP4 file where the video is encoded with H.265 codec at 9500 kbps and a picture height of 2160 pixels, + // and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH265SingleBitrate4K EncoderNamedPreset = "H265SingleBitrate4K" + // EncoderNamedPresetH265SingleBitrate720P - Produces an MP4 file where the video is encoded with H.265 codec at 1800 kbps and a picture height of 720 pixels, + // and the stereo audio is encoded with AAC-LC codec at 128 kbps. + EncoderNamedPresetH265SingleBitrate720P EncoderNamedPreset = "H265SingleBitrate720p" +) + +// PossibleEncoderNamedPresetValues returns the possible values for the EncoderNamedPreset const type. +func PossibleEncoderNamedPresetValues() []EncoderNamedPreset { + return []EncoderNamedPreset{ + EncoderNamedPresetAACGoodQualityAudio, + EncoderNamedPresetAdaptiveStreaming, + EncoderNamedPresetContentAwareEncoding, + EncoderNamedPresetContentAwareEncodingExperimental, + EncoderNamedPresetCopyAllBitrateNonInterleaved, + EncoderNamedPresetH264MultipleBitrate1080P, + EncoderNamedPresetH264MultipleBitrate720P, + EncoderNamedPresetH264MultipleBitrateSD, + EncoderNamedPresetH264SingleBitrate1080P, + EncoderNamedPresetH264SingleBitrate720P, + EncoderNamedPresetH264SingleBitrateSD, + EncoderNamedPresetH265AdaptiveStreaming, + EncoderNamedPresetH265ContentAwareEncoding, + EncoderNamedPresetH265SingleBitrate1080P, + EncoderNamedPresetH265SingleBitrate4K, + EncoderNamedPresetH265SingleBitrate720P, + } +} + +// ToPtr returns a *EncoderNamedPreset pointing to the current value. +func (c EncoderNamedPreset) ToPtr() *EncoderNamedPreset { + return &c +} + +// EncryptionScheme - Encryption scheme +type EncryptionScheme string + +const ( + // EncryptionSchemeCommonEncryptionCbcs - CommonEncryptionCbcs scheme + EncryptionSchemeCommonEncryptionCbcs EncryptionScheme = "CommonEncryptionCbcs" + // EncryptionSchemeCommonEncryptionCenc - CommonEncryptionCenc scheme + EncryptionSchemeCommonEncryptionCenc EncryptionScheme = "CommonEncryptionCenc" + // EncryptionSchemeEnvelopeEncryption - EnvelopeEncryption scheme + EncryptionSchemeEnvelopeEncryption EncryptionScheme = "EnvelopeEncryption" + // EncryptionSchemeNoEncryption - NoEncryption scheme + EncryptionSchemeNoEncryption EncryptionScheme = "NoEncryption" +) + +// PossibleEncryptionSchemeValues returns the possible values for the EncryptionScheme const type. +func PossibleEncryptionSchemeValues() []EncryptionScheme { + return []EncryptionScheme{ + EncryptionSchemeCommonEncryptionCbcs, + EncryptionSchemeCommonEncryptionCenc, + EncryptionSchemeEnvelopeEncryption, + EncryptionSchemeNoEncryption, + } +} + +// ToPtr returns a *EncryptionScheme pointing to the current value. +func (c EncryptionScheme) ToPtr() *EncryptionScheme { + return &c +} + +// EntropyMode - The entropy mode to be used for this layer. If not specified, the encoder chooses the mode that is appropriate for the profile and level. +type EntropyMode string + +const ( + // EntropyModeCabac - Context Adaptive Binary Arithmetic Coder (CABAC) entropy encoding. + EntropyModeCabac EntropyMode = "Cabac" + // EntropyModeCavlc - Context Adaptive Variable Length Coder (CAVLC) entropy encoding. + EntropyModeCavlc EntropyMode = "Cavlc" +) + +// PossibleEntropyModeValues returns the possible values for the EntropyMode const type. +func PossibleEntropyModeValues() []EntropyMode { + return []EntropyMode{ + EntropyModeCabac, + EntropyModeCavlc, + } +} + +// ToPtr returns a *EntropyMode pointing to the current value. +func (c EntropyMode) ToPtr() *EntropyMode { + return &c +} + +// FaceRedactorMode - This mode provides the ability to choose between the following settings: 1) Analyze - For detection only.This mode generates a metadata +// JSON file marking appearances of faces throughout the +// video.Where possible, appearances of the same person are assigned the same ID. 2) Combined - Additionally redacts(blurs) detected faces. 3) Redact - +// This enables a 2-pass process, allowing for +// selective redaction of a subset of detected faces.It takes in the metadata file from a prior analyze pass, along with the source video, and a user-selected +// subset of IDs that require redaction. +type FaceRedactorMode string + +const ( + // FaceRedactorModeAnalyze - Analyze mode detects faces and outputs a metadata file with the results. Allows editing of the metadata file before faces are + // blurred with Redact mode. + FaceRedactorModeAnalyze FaceRedactorMode = "Analyze" + // FaceRedactorModeCombined - Combined mode does the Analyze and Redact steps in one pass when editing the analyzed faces is not desired. + FaceRedactorModeCombined FaceRedactorMode = "Combined" + // FaceRedactorModeRedact - Redact mode consumes the metadata file from Analyze mode and redacts the faces found. + FaceRedactorModeRedact FaceRedactorMode = "Redact" +) + +// PossibleFaceRedactorModeValues returns the possible values for the FaceRedactorMode const type. +func PossibleFaceRedactorModeValues() []FaceRedactorMode { + return []FaceRedactorMode{ + FaceRedactorModeAnalyze, + FaceRedactorModeCombined, + FaceRedactorModeRedact, + } +} + +// ToPtr returns a *FaceRedactorMode pointing to the current value. +func (c FaceRedactorMode) ToPtr() *FaceRedactorMode { + return &c +} + +// FilterTrackPropertyCompareOperation - The track property condition operation. +type FilterTrackPropertyCompareOperation string + +const ( + // FilterTrackPropertyCompareOperationEqual - The equal operation. + FilterTrackPropertyCompareOperationEqual FilterTrackPropertyCompareOperation = "Equal" + // FilterTrackPropertyCompareOperationNotEqual - The not equal operation. + FilterTrackPropertyCompareOperationNotEqual FilterTrackPropertyCompareOperation = "NotEqual" +) + +// PossibleFilterTrackPropertyCompareOperationValues returns the possible values for the FilterTrackPropertyCompareOperation const type. +func PossibleFilterTrackPropertyCompareOperationValues() []FilterTrackPropertyCompareOperation { + return []FilterTrackPropertyCompareOperation{ + FilterTrackPropertyCompareOperationEqual, + FilterTrackPropertyCompareOperationNotEqual, + } +} + +// ToPtr returns a *FilterTrackPropertyCompareOperation pointing to the current value. +func (c FilterTrackPropertyCompareOperation) ToPtr() *FilterTrackPropertyCompareOperation { + return &c +} + +// FilterTrackPropertyType - The track property type. +type FilterTrackPropertyType string + +const ( + // FilterTrackPropertyTypeBitrate - The bitrate. + FilterTrackPropertyTypeBitrate FilterTrackPropertyType = "Bitrate" + // FilterTrackPropertyTypeFourCC - The fourCC. + FilterTrackPropertyTypeFourCC FilterTrackPropertyType = "FourCC" + // FilterTrackPropertyTypeLanguage - The language. + FilterTrackPropertyTypeLanguage FilterTrackPropertyType = "Language" + // FilterTrackPropertyTypeName - The name. + FilterTrackPropertyTypeName FilterTrackPropertyType = "Name" + // FilterTrackPropertyTypeType - The type. + FilterTrackPropertyTypeType FilterTrackPropertyType = "Type" + // FilterTrackPropertyTypeUnknown - The unknown track property type. + FilterTrackPropertyTypeUnknown FilterTrackPropertyType = "Unknown" +) + +// PossibleFilterTrackPropertyTypeValues returns the possible values for the FilterTrackPropertyType const type. +func PossibleFilterTrackPropertyTypeValues() []FilterTrackPropertyType { + return []FilterTrackPropertyType{ + FilterTrackPropertyTypeBitrate, + FilterTrackPropertyTypeFourCC, + FilterTrackPropertyTypeLanguage, + FilterTrackPropertyTypeName, + FilterTrackPropertyTypeType, + FilterTrackPropertyTypeUnknown, + } +} + +// ToPtr returns a *FilterTrackPropertyType pointing to the current value. +func (c FilterTrackPropertyType) ToPtr() *FilterTrackPropertyType { + return &c +} + +// H264Complexity - Tells the encoder how to choose its encoding settings. The default value is Balanced. +type H264Complexity string + +const ( + // H264ComplexityBalanced - Tells the encoder to use settings that achieve a balance between speed and quality. + H264ComplexityBalanced H264Complexity = "Balanced" + // H264ComplexityQuality - Tells the encoder to use settings that are optimized to produce higher quality output at the expense of slower overall encode + // time. + H264ComplexityQuality H264Complexity = "Quality" + // H264ComplexitySpeed - Tells the encoder to use settings that are optimized for faster encoding. Quality is sacrificed to decrease encoding time. + H264ComplexitySpeed H264Complexity = "Speed" +) + +// PossibleH264ComplexityValues returns the possible values for the H264Complexity const type. +func PossibleH264ComplexityValues() []H264Complexity { + return []H264Complexity{ + H264ComplexityBalanced, + H264ComplexityQuality, + H264ComplexitySpeed, + } +} + +// ToPtr returns a *H264Complexity pointing to the current value. +func (c H264Complexity) ToPtr() *H264Complexity { + return &c +} + +// H264VideoProfile - We currently support Baseline, Main, High, High422, High444. Default is Auto. +type H264VideoProfile string + +const ( + // H264VideoProfileAuto - Tells the encoder to automatically determine the appropriate H.264 profile. + H264VideoProfileAuto H264VideoProfile = "Auto" + // H264VideoProfileBaseline - Baseline profile + H264VideoProfileBaseline H264VideoProfile = "Baseline" + // H264VideoProfileHigh - High profile. + H264VideoProfileHigh H264VideoProfile = "High" + // H264VideoProfileHigh422 - High 4:2:2 profile. + H264VideoProfileHigh422 H264VideoProfile = "High422" + // H264VideoProfileHigh444 - High 4:4:4 predictive profile. + H264VideoProfileHigh444 H264VideoProfile = "High444" + // H264VideoProfileMain - Main profile + H264VideoProfileMain H264VideoProfile = "Main" +) + +// PossibleH264VideoProfileValues returns the possible values for the H264VideoProfile const type. +func PossibleH264VideoProfileValues() []H264VideoProfile { + return []H264VideoProfile{ + H264VideoProfileAuto, + H264VideoProfileBaseline, + H264VideoProfileHigh, + H264VideoProfileHigh422, + H264VideoProfileHigh444, + H264VideoProfileMain, + } +} + +// ToPtr returns a *H264VideoProfile pointing to the current value. +func (c H264VideoProfile) ToPtr() *H264VideoProfile { + return &c +} + +// H265Complexity - Tells the encoder how to choose its encoding settings. Quality will provide for a higher compression ratio but at a higher cost and +// longer compute time. Speed will produce a relatively larger file but +// is faster and more economical. The default value is Balanced. +type H265Complexity string + +const ( + // H265ComplexityBalanced - Tells the encoder to use settings that achieve a balance between speed and quality. + H265ComplexityBalanced H265Complexity = "Balanced" + // H265ComplexityQuality - Tells the encoder to use settings that are optimized to produce higher quality output at the expense of slower overall encode + // time. + H265ComplexityQuality H265Complexity = "Quality" + // H265ComplexitySpeed - Tells the encoder to use settings that are optimized for faster encoding. Quality is sacrificed to decrease encoding time. + H265ComplexitySpeed H265Complexity = "Speed" +) + +// PossibleH265ComplexityValues returns the possible values for the H265Complexity const type. +func PossibleH265ComplexityValues() []H265Complexity { + return []H265Complexity{ + H265ComplexityBalanced, + H265ComplexityQuality, + H265ComplexitySpeed, + } +} + +// ToPtr returns a *H265Complexity pointing to the current value. +func (c H265Complexity) ToPtr() *H265Complexity { + return &c +} + +// H265VideoProfile - We currently support Main. Default is Auto. +type H265VideoProfile string + +const ( + // H265VideoProfileAuto - Tells the encoder to automatically determine the appropriate H.265 profile. + H265VideoProfileAuto H265VideoProfile = "Auto" + // H265VideoProfileMain - Main profile (https://x265.readthedocs.io/en/default/cli.html?highlight=profile#profile-level-tier) + H265VideoProfileMain H265VideoProfile = "Main" +) + +// PossibleH265VideoProfileValues returns the possible values for the H265VideoProfile const type. +func PossibleH265VideoProfileValues() []H265VideoProfile { + return []H265VideoProfile{ + H265VideoProfileAuto, + H265VideoProfileMain, + } +} + +// ToPtr returns a *H265VideoProfile pointing to the current value. +func (c H265VideoProfile) ToPtr() *H265VideoProfile { + return &c +} + +// InsightsType - Defines the type of insights that you want the service to generate. The allowed values are 'AudioInsightsOnly', 'VideoInsightsOnly', and +// 'AllInsights'. The default is AllInsights. If you set this to +// AllInsights and the input is audio only, then only audio insights are generated. Similarly if the input is video only, then only video insights are generated. +// It is recommended that you not use +// AudioInsightsOnly if you expect some of your inputs to be video only; or use VideoInsightsOnly if you expect some of your inputs to be audio only. Your +// Jobs in such conditions would error out. +type InsightsType string + +const ( + // InsightsTypeAllInsights - Generate both audio and video insights. Fails if either audio or video Insights fail. + InsightsTypeAllInsights InsightsType = "AllInsights" + // InsightsTypeAudioInsightsOnly - Generate audio only insights. Ignore video even if present. Fails if no audio is present. + InsightsTypeAudioInsightsOnly InsightsType = "AudioInsightsOnly" + // InsightsTypeVideoInsightsOnly - Generate video only insights. Ignore audio if present. Fails if no video is present. + InsightsTypeVideoInsightsOnly InsightsType = "VideoInsightsOnly" +) + +// PossibleInsightsTypeValues returns the possible values for the InsightsType const type. +func PossibleInsightsTypeValues() []InsightsType { + return []InsightsType{ + InsightsTypeAllInsights, + InsightsTypeAudioInsightsOnly, + InsightsTypeVideoInsightsOnly, + } +} + +// ToPtr returns a *InsightsType pointing to the current value. +func (c InsightsType) ToPtr() *InsightsType { + return &c +} + +// InterleaveOutput - Sets the interleave mode of the output to control how audio and video are stored in the container format. Example: set InterleavedOutput +// as NonInterleavedOutput to produce audio-only and video-only +// outputs in separate MP4 files. +type InterleaveOutput string + +const ( + // InterleaveOutputInterleavedOutput - The output includes both audio and video. + InterleaveOutputInterleavedOutput InterleaveOutput = "InterleavedOutput" + // InterleaveOutputNonInterleavedOutput - The output is video-only or audio-only. + InterleaveOutputNonInterleavedOutput InterleaveOutput = "NonInterleavedOutput" +) + +// PossibleInterleaveOutputValues returns the possible values for the InterleaveOutput const type. +func PossibleInterleaveOutputValues() []InterleaveOutput { + return []InterleaveOutput{ + InterleaveOutputInterleavedOutput, + InterleaveOutputNonInterleavedOutput, + } +} + +// ToPtr returns a *InterleaveOutput pointing to the current value. +func (c InterleaveOutput) ToPtr() *InterleaveOutput { + return &c +} + +// JobErrorCategory - Helps with categorization of errors. +type JobErrorCategory string + +const ( + // JobErrorCategoryConfiguration - The error is configuration related. + JobErrorCategoryConfiguration JobErrorCategory = "Configuration" + // JobErrorCategoryContent - The error is related to data in the input files. + JobErrorCategoryContent JobErrorCategory = "Content" + // JobErrorCategoryDownload - The error is download related. + JobErrorCategoryDownload JobErrorCategory = "Download" + // JobErrorCategoryService - The error is service related. + JobErrorCategoryService JobErrorCategory = "Service" + // JobErrorCategoryUpload - The error is upload related. + JobErrorCategoryUpload JobErrorCategory = "Upload" +) + +// PossibleJobErrorCategoryValues returns the possible values for the JobErrorCategory const type. +func PossibleJobErrorCategoryValues() []JobErrorCategory { + return []JobErrorCategory{ + JobErrorCategoryConfiguration, + JobErrorCategoryContent, + JobErrorCategoryDownload, + JobErrorCategoryService, + JobErrorCategoryUpload, + } +} + +// ToPtr returns a *JobErrorCategory pointing to the current value. +func (c JobErrorCategory) ToPtr() *JobErrorCategory { + return &c +} + +// JobErrorCode - Error code describing the error. +type JobErrorCode string + +const ( + // JobErrorCodeConfigurationUnsupported - There was a problem with the combination of input files and the configuration settings applied, fix the configuration + // settings and retry with the same input, or change input to match the configuration. + JobErrorCodeConfigurationUnsupported JobErrorCode = "ConfigurationUnsupported" + // JobErrorCodeContentMalformed - There was a problem with the input content (for example: zero byte files, or corrupt/non-decodable files), check the input + // files. + JobErrorCodeContentMalformed JobErrorCode = "ContentMalformed" + // JobErrorCodeContentUnsupported - There was a problem with the format of the input (not valid media file, or an unsupported file/codec), check the validity + // of the input files. + JobErrorCodeContentUnsupported JobErrorCode = "ContentUnsupported" + // JobErrorCodeDownloadNotAccessible - While trying to download the input files, the files were not accessible, please check the availability of the source. + JobErrorCodeDownloadNotAccessible JobErrorCode = "DownloadNotAccessible" + // JobErrorCodeDownloadTransientError - While trying to download the input files, there was an issue during transfer (storage service, network errors), + // see details and check your source. + JobErrorCodeDownloadTransientError JobErrorCode = "DownloadTransientError" + // JobErrorCodeServiceError - Fatal service error, please contact support. + JobErrorCodeServiceError JobErrorCode = "ServiceError" + // JobErrorCodeServiceTransientError - Transient error, please retry, if retry is unsuccessful, please contact support. + JobErrorCodeServiceTransientError JobErrorCode = "ServiceTransientError" + // JobErrorCodeUploadNotAccessible - While trying to upload the output files, the destination was not reachable, please check the availability of the destination. + JobErrorCodeUploadNotAccessible JobErrorCode = "UploadNotAccessible" + // JobErrorCodeUploadTransientError - While trying to upload the output files, there was an issue during transfer (storage service, network errors), see + // details and check your destination. + JobErrorCodeUploadTransientError JobErrorCode = "UploadTransientError" +) + +// PossibleJobErrorCodeValues returns the possible values for the JobErrorCode const type. +func PossibleJobErrorCodeValues() []JobErrorCode { + return []JobErrorCode{ + JobErrorCodeConfigurationUnsupported, + JobErrorCodeContentMalformed, + JobErrorCodeContentUnsupported, + JobErrorCodeDownloadNotAccessible, + JobErrorCodeDownloadTransientError, + JobErrorCodeServiceError, + JobErrorCodeServiceTransientError, + JobErrorCodeUploadNotAccessible, + JobErrorCodeUploadTransientError, + } +} + +// ToPtr returns a *JobErrorCode pointing to the current value. +func (c JobErrorCode) ToPtr() *JobErrorCode { + return &c +} + +// JobRetry - Indicates that it may be possible to retry the Job. If retry is unsuccessful, please contact Azure support via Azure Portal. +type JobRetry string + +const ( + // JobRetryDoNotRetry - Issue needs to be investigated and then the job resubmitted with corrections or retried once the underlying issue has been corrected. + JobRetryDoNotRetry JobRetry = "DoNotRetry" + // JobRetryMayRetry - Issue may be resolved after waiting for a period of time and resubmitting the same Job. + JobRetryMayRetry JobRetry = "MayRetry" +) + +// PossibleJobRetryValues returns the possible values for the JobRetry const type. +func PossibleJobRetryValues() []JobRetry { + return []JobRetry{ + JobRetryDoNotRetry, + JobRetryMayRetry, + } +} + +// ToPtr returns a *JobRetry pointing to the current value. +func (c JobRetry) ToPtr() *JobRetry { + return &c +} + +// JobState - Describes the state of the JobOutput. +type JobState string + +const ( + // JobStateCanceled - The job was canceled. This is a final state for the job. + JobStateCanceled JobState = "Canceled" + // JobStateCanceling - The job is in the process of being canceled. This is a transient state for the job. + JobStateCanceling JobState = "Canceling" + // JobStateError - The job has encountered an error. This is a final state for the job. + JobStateError JobState = "Error" + // JobStateFinished - The job is finished. This is a final state for the job. + JobStateFinished JobState = "Finished" + // JobStateProcessing - The job is processing. This is a transient state for the job. + JobStateProcessing JobState = "Processing" + // JobStateQueued - The job is in a queued state, waiting for resources to become available. This is a transient state. + JobStateQueued JobState = "Queued" + // JobStateScheduled - The job is being scheduled to run on an available resource. This is a transient state, between queued and processing states. + JobStateScheduled JobState = "Scheduled" +) + +// PossibleJobStateValues returns the possible values for the JobState const type. +func PossibleJobStateValues() []JobState { + return []JobState{ + JobStateCanceled, + JobStateCanceling, + JobStateError, + JobStateFinished, + JobStateProcessing, + JobStateQueued, + JobStateScheduled, + } +} + +// ToPtr returns a *JobState pointing to the current value. +func (c JobState) ToPtr() *JobState { + return &c +} + +// LiveEventEncodingType - Live event type. When encodingType is set to PassthroughBasic or PassthroughStandard, the service simply passes through the incoming +// video and audio layer(s) to the output. When encodingType is set to +// Standard or Premium1080p, a live encoder transcodes the incoming stream into multiple bitrates or layers. See https://go.microsoft.com/fwlink/?linkid=2095101 +// for more information. This property cannot +// be modified after the live event is created. +type LiveEventEncodingType string + +const ( + // LiveEventEncodingTypeNone - This is the same as PassthroughStandard, please see description below. This enumeration value is being deprecated. + LiveEventEncodingTypeNone LiveEventEncodingType = "None" + // LiveEventEncodingTypePassthroughBasic - The ingested stream passes through the live event from the contribution encoder without any further processing. + // In the PassthroughBasic mode, ingestion is limited to up to 5Mbps and only 1 concurrent live output is allowed. Live transcription is not available. + LiveEventEncodingTypePassthroughBasic LiveEventEncodingType = "PassthroughBasic" + // LiveEventEncodingTypePassthroughStandard - The ingested stream passes through the live event from the contribution encoder without any further processing. + // Live transcription is available. Ingestion bitrate limits are much higher and up to 3 concurrent live outputs are allowed. + LiveEventEncodingTypePassthroughStandard LiveEventEncodingType = "PassthroughStandard" + // LiveEventEncodingTypePremium1080P - A contribution live encoder sends a single bitrate stream to the live event and Media Services creates multiple bitrate + // streams. The output cannot exceed 1080p in resolution. + LiveEventEncodingTypePremium1080P LiveEventEncodingType = "Premium1080p" + // LiveEventEncodingTypeStandard - A contribution live encoder sends a single bitrate stream to the live event and Media Services creates multiple bitrate + // streams. The output cannot exceed 720p in resolution. + LiveEventEncodingTypeStandard LiveEventEncodingType = "Standard" +) + +// PossibleLiveEventEncodingTypeValues returns the possible values for the LiveEventEncodingType const type. +func PossibleLiveEventEncodingTypeValues() []LiveEventEncodingType { + return []LiveEventEncodingType{ + LiveEventEncodingTypeNone, + LiveEventEncodingTypePassthroughBasic, + LiveEventEncodingTypePassthroughStandard, + LiveEventEncodingTypePremium1080P, + LiveEventEncodingTypeStandard, + } +} + +// ToPtr returns a *LiveEventEncodingType pointing to the current value. +func (c LiveEventEncodingType) ToPtr() *LiveEventEncodingType { + return &c +} + +// LiveEventInputProtocol - The input protocol for the live event. This is specified at creation time and cannot be updated. +type LiveEventInputProtocol string + +const ( + // LiveEventInputProtocolFragmentedMP4 - Smooth Streaming input will be sent by the contribution encoder to the live event. + LiveEventInputProtocolFragmentedMP4 LiveEventInputProtocol = "FragmentedMP4" + // LiveEventInputProtocolRTMP - RTMP input will be sent by the contribution encoder to the live event. + LiveEventInputProtocolRTMP LiveEventInputProtocol = "RTMP" +) + +// PossibleLiveEventInputProtocolValues returns the possible values for the LiveEventInputProtocol const type. +func PossibleLiveEventInputProtocolValues() []LiveEventInputProtocol { + return []LiveEventInputProtocol{ + LiveEventInputProtocolFragmentedMP4, + LiveEventInputProtocolRTMP, + } +} + +// ToPtr returns a *LiveEventInputProtocol pointing to the current value. +func (c LiveEventInputProtocol) ToPtr() *LiveEventInputProtocol { + return &c +} + +// LiveEventResourceState - The resource state of the live event. See https://go.microsoft.com/fwlink/?linkid=2139012 for more information. +type LiveEventResourceState string + +const ( + // LiveEventResourceStateAllocating - Allocate action was called on the live event and resources are being provisioned for this live event. Once allocation + // completes successfully, the live event will transition to StandBy state. + LiveEventResourceStateAllocating LiveEventResourceState = "Allocating" + // LiveEventResourceStateDeleting - The live event is being deleted. No billing occurs in this transient state. Updates or streaming are not allowed during + // this state. + LiveEventResourceStateDeleting LiveEventResourceState = "Deleting" + // LiveEventResourceStateRunning - The live event resources have been allocated, ingest and preview URLs have been generated, and it is capable of receiving + // live streams. At this point, billing is active. You must explicitly call Stop on the live event resource to halt further billing. + LiveEventResourceStateRunning LiveEventResourceState = "Running" + // LiveEventResourceStateStandBy - Live event resources have been provisioned and is ready to start. Billing occurs in this state. Most properties can still + // be updated, however ingest or streaming is not allowed during this state. + LiveEventResourceStateStandBy LiveEventResourceState = "StandBy" + // LiveEventResourceStateStarting - The live event is being started and resources are being allocated. No billing occurs in this state. Updates or streaming + // are not allowed during this state. If an error occurs, the live event returns to the Stopped state. + LiveEventResourceStateStarting LiveEventResourceState = "Starting" + // LiveEventResourceStateStopped - This is the initial state of the live event after creation (unless autostart was set to true.) No billing occurs in this + // state. In this state, the live event properties can be updated but streaming is not allowed. + LiveEventResourceStateStopped LiveEventResourceState = "Stopped" + // LiveEventResourceStateStopping - The live event is being stopped and resources are being de-provisioned. No billing occurs in this transient state. Updates + // or streaming are not allowed during this state. + LiveEventResourceStateStopping LiveEventResourceState = "Stopping" +) + +// PossibleLiveEventResourceStateValues returns the possible values for the LiveEventResourceState const type. +func PossibleLiveEventResourceStateValues() []LiveEventResourceState { + return []LiveEventResourceState{ + LiveEventResourceStateAllocating, + LiveEventResourceStateDeleting, + LiveEventResourceStateRunning, + LiveEventResourceStateStandBy, + LiveEventResourceStateStarting, + LiveEventResourceStateStopped, + LiveEventResourceStateStopping, + } +} + +// ToPtr returns a *LiveEventResourceState pointing to the current value. +func (c LiveEventResourceState) ToPtr() *LiveEventResourceState { + return &c +} + +// LiveOutputResourceState - The resource state of the live output. +type LiveOutputResourceState string + +const ( + // LiveOutputResourceStateCreating - Live output is being created. No content is archived in the asset until the live output is in running state. + LiveOutputResourceStateCreating LiveOutputResourceState = "Creating" + // LiveOutputResourceStateDeleting - Live output is being deleted. The live asset is being converted from live to on-demand asset. Any streaming URLs created + // on the live output asset continue to work. + LiveOutputResourceStateDeleting LiveOutputResourceState = "Deleting" + // LiveOutputResourceStateRunning - Live output is running and archiving live streaming content to the asset if there is valid input from a contribution + // encoder. + LiveOutputResourceStateRunning LiveOutputResourceState = "Running" +) + +// PossibleLiveOutputResourceStateValues returns the possible values for the LiveOutputResourceState const type. +func PossibleLiveOutputResourceStateValues() []LiveOutputResourceState { + return []LiveOutputResourceState{ + LiveOutputResourceStateCreating, + LiveOutputResourceStateDeleting, + LiveOutputResourceStateRunning, + } +} + +// ToPtr returns a *LiveOutputResourceState pointing to the current value. +func (c LiveOutputResourceState) ToPtr() *LiveOutputResourceState { + return &c +} + +// MetricAggregationType - The metric aggregation type +type MetricAggregationType string + +const ( + // MetricAggregationTypeAverage - The average. + MetricAggregationTypeAverage MetricAggregationType = "Average" + // MetricAggregationTypeCount - The count of a number of items, usually requests. + MetricAggregationTypeCount MetricAggregationType = "Count" + // MetricAggregationTypeTotal - The sum. + MetricAggregationTypeTotal MetricAggregationType = "Total" +) + +// PossibleMetricAggregationTypeValues returns the possible values for the MetricAggregationType const type. +func PossibleMetricAggregationTypeValues() []MetricAggregationType { + return []MetricAggregationType{ + MetricAggregationTypeAverage, + MetricAggregationTypeCount, + MetricAggregationTypeTotal, + } +} + +// ToPtr returns a *MetricAggregationType pointing to the current value. +func (c MetricAggregationType) ToPtr() *MetricAggregationType { + return &c +} + +// MetricUnit - The metric unit +type MetricUnit string + +const ( + // MetricUnitBytes - The number of bytes. + MetricUnitBytes MetricUnit = "Bytes" + // MetricUnitCount - The count. + MetricUnitCount MetricUnit = "Count" + // MetricUnitMilliseconds - The number of milliseconds. + MetricUnitMilliseconds MetricUnit = "Milliseconds" +) + +// PossibleMetricUnitValues returns the possible values for the MetricUnit const type. +func PossibleMetricUnitValues() []MetricUnit { + return []MetricUnit{ + MetricUnitBytes, + MetricUnitCount, + MetricUnitMilliseconds, + } +} + +// ToPtr returns a *MetricUnit pointing to the current value. +func (c MetricUnit) ToPtr() *MetricUnit { + return &c +} + +// OnErrorType - A Transform can define more than one outputs. This property defines what the service should do when one output fails - either continue +// to produce other outputs, or, stop the other outputs. The overall +// Job state will not reflect failures of outputs that are specified with 'ContinueJob'. The default is 'StopProcessingJob'. +type OnErrorType string + +const ( + // OnErrorTypeContinueJob - Tells the service that if this TransformOutput fails, then allow any other TransformOutput to continue. + OnErrorTypeContinueJob OnErrorType = "ContinueJob" + // OnErrorTypeStopProcessingJob - Tells the service that if this TransformOutput fails, then any other incomplete TransformOutputs can be stopped. + OnErrorTypeStopProcessingJob OnErrorType = "StopProcessingJob" +) + +// PossibleOnErrorTypeValues returns the possible values for the OnErrorType const type. +func PossibleOnErrorTypeValues() []OnErrorType { + return []OnErrorType{ + OnErrorTypeContinueJob, + OnErrorTypeStopProcessingJob, + } +} + +// ToPtr returns a *OnErrorType pointing to the current value. +func (c OnErrorType) ToPtr() *OnErrorType { + return &c +} + +// Priority - Sets the relative priority of the TransformOutputs within a Transform. This sets the priority that the service uses for processing TransformOutputs. +// The default priority is Normal. +type Priority string + +const ( + // PriorityHigh - Used for TransformOutputs that should take precedence over others. + PriorityHigh Priority = "High" + // PriorityLow - Used for TransformOutputs that can be generated after Normal and High priority TransformOutputs. + PriorityLow Priority = "Low" + // PriorityNormal - Used for TransformOutputs that can be generated at Normal priority. + PriorityNormal Priority = "Normal" +) + +// PossiblePriorityValues returns the possible values for the Priority const type. +func PossiblePriorityValues() []Priority { + return []Priority{ + PriorityHigh, + PriorityLow, + PriorityNormal, + } +} + +// ToPtr returns a *Priority pointing to the current value. +func (c Priority) ToPtr() *Priority { + return &c +} + +// PrivateEndpointConnectionProvisioningState - The current provisioning state. +type PrivateEndpointConnectionProvisioningState string + +const ( + PrivateEndpointConnectionProvisioningStateCreating PrivateEndpointConnectionProvisioningState = "Creating" + PrivateEndpointConnectionProvisioningStateDeleting PrivateEndpointConnectionProvisioningState = "Deleting" + PrivateEndpointConnectionProvisioningStateFailed PrivateEndpointConnectionProvisioningState = "Failed" + PrivateEndpointConnectionProvisioningStateSucceeded PrivateEndpointConnectionProvisioningState = "Succeeded" +) + +// PossiblePrivateEndpointConnectionProvisioningStateValues returns the possible values for the PrivateEndpointConnectionProvisioningState const type. +func PossiblePrivateEndpointConnectionProvisioningStateValues() []PrivateEndpointConnectionProvisioningState { + return []PrivateEndpointConnectionProvisioningState{ + PrivateEndpointConnectionProvisioningStateCreating, + PrivateEndpointConnectionProvisioningStateDeleting, + PrivateEndpointConnectionProvisioningStateFailed, + PrivateEndpointConnectionProvisioningStateSucceeded, + } +} + +// ToPtr returns a *PrivateEndpointConnectionProvisioningState pointing to the current value. +func (c PrivateEndpointConnectionProvisioningState) ToPtr() *PrivateEndpointConnectionProvisioningState { + return &c +} + +// PrivateEndpointServiceConnectionStatus - The private endpoint connection status. +type PrivateEndpointServiceConnectionStatus string + +const ( + PrivateEndpointServiceConnectionStatusApproved PrivateEndpointServiceConnectionStatus = "Approved" + PrivateEndpointServiceConnectionStatusPending PrivateEndpointServiceConnectionStatus = "Pending" + PrivateEndpointServiceConnectionStatusRejected PrivateEndpointServiceConnectionStatus = "Rejected" +) + +// PossiblePrivateEndpointServiceConnectionStatusValues returns the possible values for the PrivateEndpointServiceConnectionStatus const type. +func PossiblePrivateEndpointServiceConnectionStatusValues() []PrivateEndpointServiceConnectionStatus { + return []PrivateEndpointServiceConnectionStatus{ + PrivateEndpointServiceConnectionStatusApproved, + PrivateEndpointServiceConnectionStatusPending, + PrivateEndpointServiceConnectionStatusRejected, + } +} + +// ToPtr returns a *PrivateEndpointServiceConnectionStatus pointing to the current value. +func (c PrivateEndpointServiceConnectionStatus) ToPtr() *PrivateEndpointServiceConnectionStatus { + return &c +} + +// PublicNetworkAccess - Whether or not public network access is allowed for resources under the Media Services account. +type PublicNetworkAccess string + +const ( + // PublicNetworkAccessDisabled - Public network access is disabled. + PublicNetworkAccessDisabled PublicNetworkAccess = "Disabled" + // PublicNetworkAccessEnabled - Public network access is enabled. + PublicNetworkAccessEnabled PublicNetworkAccess = "Enabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessDisabled, + PublicNetworkAccessEnabled, + } +} + +// ToPtr returns a *PublicNetworkAccess pointing to the current value. +func (c PublicNetworkAccess) ToPtr() *PublicNetworkAccess { + return &c +} + +// Rotation - The rotation, if any, to be applied to the input video, before it is encoded. Default is Auto +type Rotation string + +const ( + // RotationAuto - Automatically detect and rotate as needed. + RotationAuto Rotation = "Auto" + // RotationNone - Do not rotate the video. If the output format supports it, any metadata about rotation is kept intact. + RotationNone Rotation = "None" + // RotationRotate0 - Do not rotate the video but remove any metadata about the rotation. + RotationRotate0 Rotation = "Rotate0" + // RotationRotate180 - Rotate 180 degrees clockwise. + RotationRotate180 Rotation = "Rotate180" + // RotationRotate270 - Rotate 270 degrees clockwise. + RotationRotate270 Rotation = "Rotate270" + // RotationRotate90 - Rotate 90 degrees clockwise. + RotationRotate90 Rotation = "Rotate90" +) + +// PossibleRotationValues returns the possible values for the Rotation const type. +func PossibleRotationValues() []Rotation { + return []Rotation{ + RotationAuto, + RotationNone, + RotationRotate0, + RotationRotate180, + RotationRotate270, + RotationRotate90, + } +} + +// ToPtr returns a *Rotation pointing to the current value. +func (c Rotation) ToPtr() *Rotation { + return &c +} + +// StorageAccountType - The type of the storage account. +type StorageAccountType string + +const ( + // StorageAccountTypePrimary - The primary storage account for the Media Services account. + StorageAccountTypePrimary StorageAccountType = "Primary" + // StorageAccountTypeSecondary - A secondary storage account for the Media Services account. + StorageAccountTypeSecondary StorageAccountType = "Secondary" +) + +// PossibleStorageAccountTypeValues returns the possible values for the StorageAccountType const type. +func PossibleStorageAccountTypeValues() []StorageAccountType { + return []StorageAccountType{ + StorageAccountTypePrimary, + StorageAccountTypeSecondary, + } +} + +// ToPtr returns a *StorageAccountType pointing to the current value. +func (c StorageAccountType) ToPtr() *StorageAccountType { + return &c +} + +type StorageAuthentication string + +const ( + // StorageAuthenticationManagedIdentity - Managed Identity authentication. + StorageAuthenticationManagedIdentity StorageAuthentication = "ManagedIdentity" + // StorageAuthenticationSystem - System authentication. + StorageAuthenticationSystem StorageAuthentication = "System" +) + +// PossibleStorageAuthenticationValues returns the possible values for the StorageAuthentication const type. +func PossibleStorageAuthenticationValues() []StorageAuthentication { + return []StorageAuthentication{ + StorageAuthenticationManagedIdentity, + StorageAuthenticationSystem, + } +} + +// ToPtr returns a *StorageAuthentication pointing to the current value. +func (c StorageAuthentication) ToPtr() *StorageAuthentication { + return &c +} + +type StreamOptionsFlag string + +const ( + // StreamOptionsFlagDefault - Live streaming with no special latency optimizations. + StreamOptionsFlagDefault StreamOptionsFlag = "Default" + // StreamOptionsFlagLowLatency - The live event provides lower end to end latency by reducing its internal buffers. This could result in more client buffering + // during playback if network bandwidth is low. + StreamOptionsFlagLowLatency StreamOptionsFlag = "LowLatency" +) + +// PossibleStreamOptionsFlagValues returns the possible values for the StreamOptionsFlag const type. +func PossibleStreamOptionsFlagValues() []StreamOptionsFlag { + return []StreamOptionsFlag{ + StreamOptionsFlagDefault, + StreamOptionsFlagLowLatency, + } +} + +// ToPtr returns a *StreamOptionsFlag pointing to the current value. +func (c StreamOptionsFlag) ToPtr() *StreamOptionsFlag { + return &c +} + +// StreamingEndpointResourceState - The resource state of the streaming endpoint. +type StreamingEndpointResourceState string + +const ( + // StreamingEndpointResourceStateDeleting - The streaming endpoint is being deleted. + StreamingEndpointResourceStateDeleting StreamingEndpointResourceState = "Deleting" + // StreamingEndpointResourceStateRunning - The streaming endpoint is running. It is able to stream content to clients + StreamingEndpointResourceStateRunning StreamingEndpointResourceState = "Running" + // StreamingEndpointResourceStateScaling - The streaming endpoint is increasing or decreasing scale units. + StreamingEndpointResourceStateScaling StreamingEndpointResourceState = "Scaling" + // StreamingEndpointResourceStateStarting - The streaming endpoint is transitioning to the running state. + StreamingEndpointResourceStateStarting StreamingEndpointResourceState = "Starting" + // StreamingEndpointResourceStateStopped - The initial state of a streaming endpoint after creation. Content is not ready to be streamed from this endpoint. + StreamingEndpointResourceStateStopped StreamingEndpointResourceState = "Stopped" + // StreamingEndpointResourceStateStopping - The streaming endpoint is transitioning to the stopped state. + StreamingEndpointResourceStateStopping StreamingEndpointResourceState = "Stopping" +) + +// PossibleStreamingEndpointResourceStateValues returns the possible values for the StreamingEndpointResourceState const type. +func PossibleStreamingEndpointResourceStateValues() []StreamingEndpointResourceState { + return []StreamingEndpointResourceState{ + StreamingEndpointResourceStateDeleting, + StreamingEndpointResourceStateRunning, + StreamingEndpointResourceStateScaling, + StreamingEndpointResourceStateStarting, + StreamingEndpointResourceStateStopped, + StreamingEndpointResourceStateStopping, + } +} + +// ToPtr returns a *StreamingEndpointResourceState pointing to the current value. +func (c StreamingEndpointResourceState) ToPtr() *StreamingEndpointResourceState { + return &c +} + +// StreamingLocatorContentKeyType - Encryption type of Content Key +type StreamingLocatorContentKeyType string + +const ( + // StreamingLocatorContentKeyTypeCommonEncryptionCbcs - Common Encryption using CBCS + StreamingLocatorContentKeyTypeCommonEncryptionCbcs StreamingLocatorContentKeyType = "CommonEncryptionCbcs" + // StreamingLocatorContentKeyTypeCommonEncryptionCenc - Common Encryption using CENC + StreamingLocatorContentKeyTypeCommonEncryptionCenc StreamingLocatorContentKeyType = "CommonEncryptionCenc" + // StreamingLocatorContentKeyTypeEnvelopeEncryption - Envelope Encryption + StreamingLocatorContentKeyTypeEnvelopeEncryption StreamingLocatorContentKeyType = "EnvelopeEncryption" +) + +// PossibleStreamingLocatorContentKeyTypeValues returns the possible values for the StreamingLocatorContentKeyType const type. +func PossibleStreamingLocatorContentKeyTypeValues() []StreamingLocatorContentKeyType { + return []StreamingLocatorContentKeyType{ + StreamingLocatorContentKeyTypeCommonEncryptionCbcs, + StreamingLocatorContentKeyTypeCommonEncryptionCenc, + StreamingLocatorContentKeyTypeEnvelopeEncryption, + } +} + +// ToPtr returns a *StreamingLocatorContentKeyType pointing to the current value. +func (c StreamingLocatorContentKeyType) ToPtr() *StreamingLocatorContentKeyType { + return &c +} + +// StreamingPolicyStreamingProtocol - Streaming protocol +type StreamingPolicyStreamingProtocol string + +const ( + // StreamingPolicyStreamingProtocolDash - DASH protocol + StreamingPolicyStreamingProtocolDash StreamingPolicyStreamingProtocol = "Dash" + // StreamingPolicyStreamingProtocolDownload - Download protocol + StreamingPolicyStreamingProtocolDownload StreamingPolicyStreamingProtocol = "Download" + // StreamingPolicyStreamingProtocolHls - HLS protocol + StreamingPolicyStreamingProtocolHls StreamingPolicyStreamingProtocol = "Hls" + // StreamingPolicyStreamingProtocolSmoothStreaming - SmoothStreaming protocol + StreamingPolicyStreamingProtocolSmoothStreaming StreamingPolicyStreamingProtocol = "SmoothStreaming" +) + +// PossibleStreamingPolicyStreamingProtocolValues returns the possible values for the StreamingPolicyStreamingProtocol const type. +func PossibleStreamingPolicyStreamingProtocolValues() []StreamingPolicyStreamingProtocol { + return []StreamingPolicyStreamingProtocol{ + StreamingPolicyStreamingProtocolDash, + StreamingPolicyStreamingProtocolDownload, + StreamingPolicyStreamingProtocolHls, + StreamingPolicyStreamingProtocolSmoothStreaming, + } +} + +// ToPtr returns a *StreamingPolicyStreamingProtocol pointing to the current value. +func (c StreamingPolicyStreamingProtocol) ToPtr() *StreamingPolicyStreamingProtocol { + return &c +} + +// StretchMode - The resizing mode - how the input video will be resized to fit the desired output resolution(s). Default is AutoSize +type StretchMode string + +const ( + // StretchModeAutoFit - Pad the output (with either letterbox or pillar box) to honor the output resolution, while ensuring that the active video region + // in the output has the same aspect ratio as the input. For example, if the input is 1920x1080 and the encoding preset asks for 1280x1280, then the output + // will be at 1280x1280, which contains an inner rectangle of 1280x720 at aspect ratio of 16:9, and pillar box regions 280 pixels wide at the left and right. + StretchModeAutoFit StretchMode = "AutoFit" + // StretchModeAutoSize - Override the output resolution, and change it to match the display aspect ratio of the input, without padding. For example, if + // the input is 1920x1080 and the encoding preset asks for 1280x1280, then the value in the preset is overridden, and the output will be at 1280x720, which + // maintains the input aspect ratio of 16:9. + StretchModeAutoSize StretchMode = "AutoSize" + // StretchModeNone - Strictly respect the output resolution without considering the pixel aspect ratio or display aspect ratio of the input video. + StretchModeNone StretchMode = "None" +) + +// PossibleStretchModeValues returns the possible values for the StretchMode const type. +func PossibleStretchModeValues() []StretchMode { + return []StretchMode{ + StretchModeAutoFit, + StretchModeAutoSize, + StretchModeNone, + } +} + +// ToPtr returns a *StretchMode pointing to the current value. +func (c StretchMode) ToPtr() *StretchMode { + return &c +} + +// TrackAttribute - The TrackAttribute to filter the tracks by. +type TrackAttribute string + +const ( + // TrackAttributeBitrate - The bitrate of the track. + TrackAttributeBitrate TrackAttribute = "Bitrate" + // TrackAttributeLanguage - The language of the track. + TrackAttributeLanguage TrackAttribute = "Language" +) + +// PossibleTrackAttributeValues returns the possible values for the TrackAttribute const type. +func PossibleTrackAttributeValues() []TrackAttribute { + return []TrackAttribute{ + TrackAttributeBitrate, + TrackAttributeLanguage, + } +} + +// ToPtr returns a *TrackAttribute pointing to the current value. +func (c TrackAttribute) ToPtr() *TrackAttribute { + return &c +} + +// TrackPropertyCompareOperation - Track property condition operation +type TrackPropertyCompareOperation string + +const ( + // TrackPropertyCompareOperationEqual - Equal operation + TrackPropertyCompareOperationEqual TrackPropertyCompareOperation = "Equal" + // TrackPropertyCompareOperationUnknown - Unknown track property compare operation + TrackPropertyCompareOperationUnknown TrackPropertyCompareOperation = "Unknown" +) + +// PossibleTrackPropertyCompareOperationValues returns the possible values for the TrackPropertyCompareOperation const type. +func PossibleTrackPropertyCompareOperationValues() []TrackPropertyCompareOperation { + return []TrackPropertyCompareOperation{ + TrackPropertyCompareOperationEqual, + TrackPropertyCompareOperationUnknown, + } +} + +// ToPtr returns a *TrackPropertyCompareOperation pointing to the current value. +func (c TrackPropertyCompareOperation) ToPtr() *TrackPropertyCompareOperation { + return &c +} + +// TrackPropertyType - Track property type +type TrackPropertyType string + +const ( + // TrackPropertyTypeFourCC - Track FourCC + TrackPropertyTypeFourCC TrackPropertyType = "FourCC" + // TrackPropertyTypeUnknown - Unknown track property + TrackPropertyTypeUnknown TrackPropertyType = "Unknown" +) + +// PossibleTrackPropertyTypeValues returns the possible values for the TrackPropertyType const type. +func PossibleTrackPropertyTypeValues() []TrackPropertyType { + return []TrackPropertyType{ + TrackPropertyTypeFourCC, + TrackPropertyTypeUnknown, + } +} + +// ToPtr returns a *TrackPropertyType pointing to the current value. +func (c TrackPropertyType) ToPtr() *TrackPropertyType { + return &c +} + +// VideoSyncMode - The Video Sync Mode +type VideoSyncMode string + +const ( + // VideoSyncModeAuto - This is the default method. Chooses between Cfr and Vfr depending on muxer capabilities. For output format MP4, the default mode + // is Cfr. + VideoSyncModeAuto VideoSyncMode = "Auto" + // VideoSyncModeCfr - Input frames will be repeated and/or dropped as needed to achieve exactly the requested constant frame rate. Recommended when the + // output frame rate is explicitly set at a specified value + VideoSyncModeCfr VideoSyncMode = "Cfr" + // VideoSyncModePassthrough - The presentation timestamps on frames are passed through from the input file to the output file writer. Recommended when the + // input source has variable frame rate, and are attempting to produce multiple layers for adaptive streaming in the output which have aligned GOP boundaries. + // Note: if two or more frames in the input have duplicate timestamps, then the output will also have the same behavior + VideoSyncModePassthrough VideoSyncMode = "Passthrough" + // VideoSyncModeVfr - Similar to the Passthrough mode, but if the input has frames that have duplicate timestamps, then only one frame is passed through + // to the output, and others are dropped. Recommended when the number of output frames is expected to be equal to the number of input frames. For example, + // the output is used to calculate a quality metric like PSNR against the input + VideoSyncModeVfr VideoSyncMode = "Vfr" +) + +// PossibleVideoSyncModeValues returns the possible values for the VideoSyncMode const type. +func PossibleVideoSyncModeValues() []VideoSyncMode { + return []VideoSyncMode{ + VideoSyncModeAuto, + VideoSyncModeCfr, + VideoSyncModePassthrough, + VideoSyncModeVfr, + } +} + +// ToPtr returns a *VideoSyncMode pointing to the current value. +func (c VideoSyncMode) ToPtr() *VideoSyncMode { + return &c +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_contentkeypolicies_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_contentkeypolicies_client.go new file mode 100644 index 000000000000..7f5f56cf06fc --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_contentkeypolicies_client.go @@ -0,0 +1,443 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ContentKeyPoliciesClient contains the methods for the ContentKeyPolicies group. +// Don't use this type directly, use NewContentKeyPoliciesClient() instead. +type ContentKeyPoliciesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewContentKeyPoliciesClient creates a new instance of ContentKeyPoliciesClient with the specified values. +func NewContentKeyPoliciesClient(con *arm.Connection, subscriptionID string) *ContentKeyPoliciesClient { + return &ContentKeyPoliciesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Create or update a Content Key Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, parameters ContentKeyPolicy, options *ContentKeyPoliciesCreateOrUpdateOptions) (ContentKeyPoliciesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, contentKeyPolicyName, parameters, options) + if err != nil { + return ContentKeyPoliciesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ContentKeyPoliciesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return ContentKeyPoliciesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ContentKeyPoliciesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, parameters ContentKeyPolicy, options *ContentKeyPoliciesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if contentKeyPolicyName == "" { + return nil, errors.New("parameter contentKeyPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contentKeyPolicyName}", url.PathEscape(contentKeyPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *ContentKeyPoliciesClient) createOrUpdateHandleResponse(resp *http.Response) (ContentKeyPoliciesCreateOrUpdateResponse, error) { + result := ContentKeyPoliciesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ContentKeyPolicy); err != nil { + return ContentKeyPoliciesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *ContentKeyPoliciesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Content Key Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesDeleteOptions) (ContentKeyPoliciesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, contentKeyPolicyName, options) + if err != nil { + return ContentKeyPoliciesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ContentKeyPoliciesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return ContentKeyPoliciesDeleteResponse{}, client.deleteHandleError(resp) + } + return ContentKeyPoliciesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ContentKeyPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if contentKeyPolicyName == "" { + return nil, errors.New("parameter contentKeyPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contentKeyPolicyName}", url.PathEscape(contentKeyPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ContentKeyPoliciesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of a Content Key Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesGetOptions) (ContentKeyPoliciesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, contentKeyPolicyName, options) + if err != nil { + return ContentKeyPoliciesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ContentKeyPoliciesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ContentKeyPoliciesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *ContentKeyPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if contentKeyPolicyName == "" { + return nil, errors.New("parameter contentKeyPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contentKeyPolicyName}", url.PathEscape(contentKeyPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ContentKeyPoliciesClient) getHandleResponse(resp *http.Response) (ContentKeyPoliciesGetResponse, error) { + result := ContentKeyPoliciesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ContentKeyPolicy); err != nil { + return ContentKeyPoliciesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *ContentKeyPoliciesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetPolicyPropertiesWithSecrets - Get a Content Key Policy including secret values +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) GetPolicyPropertiesWithSecrets(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptions) (ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse, error) { + req, err := client.getPolicyPropertiesWithSecretsCreateRequest(ctx, resourceGroupName, accountName, contentKeyPolicyName, options) + if err != nil { + return ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse{}, client.getPolicyPropertiesWithSecretsHandleError(resp) + } + return client.getPolicyPropertiesWithSecretsHandleResponse(resp) +} + +// getPolicyPropertiesWithSecretsCreateRequest creates the GetPolicyPropertiesWithSecrets request. +func (client *ContentKeyPoliciesClient) getPolicyPropertiesWithSecretsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, options *ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}/getPolicyPropertiesWithSecrets" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if contentKeyPolicyName == "" { + return nil, errors.New("parameter contentKeyPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contentKeyPolicyName}", url.PathEscape(contentKeyPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getPolicyPropertiesWithSecretsHandleResponse handles the GetPolicyPropertiesWithSecrets response. +func (client *ContentKeyPoliciesClient) getPolicyPropertiesWithSecretsHandleResponse(resp *http.Response) (ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse, error) { + result := ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ContentKeyPolicyProperties); err != nil { + return ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse{}, err + } + return result, nil +} + +// getPolicyPropertiesWithSecretsHandleError handles the GetPolicyPropertiesWithSecrets error response. +func (client *ContentKeyPoliciesClient) getPolicyPropertiesWithSecretsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the Content Key Policies in the account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) List(resourceGroupName string, accountName string, options *ContentKeyPoliciesListOptions) *ContentKeyPoliciesListPager { + return &ContentKeyPoliciesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp ContentKeyPoliciesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ContentKeyPolicyCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *ContentKeyPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *ContentKeyPoliciesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ContentKeyPoliciesClient) listHandleResponse(resp *http.Response) (ContentKeyPoliciesListResponse, error) { + result := ContentKeyPoliciesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ContentKeyPolicyCollection); err != nil { + return ContentKeyPoliciesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *ContentKeyPoliciesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing Content Key Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *ContentKeyPoliciesClient) Update(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, parameters ContentKeyPolicy, options *ContentKeyPoliciesUpdateOptions) (ContentKeyPoliciesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, contentKeyPolicyName, parameters, options) + if err != nil { + return ContentKeyPoliciesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ContentKeyPoliciesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ContentKeyPoliciesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *ContentKeyPoliciesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, contentKeyPolicyName string, parameters ContentKeyPolicy, options *ContentKeyPoliciesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/contentKeyPolicies/{contentKeyPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if contentKeyPolicyName == "" { + return nil, errors.New("parameter contentKeyPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{contentKeyPolicyName}", url.PathEscape(contentKeyPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *ContentKeyPoliciesClient) updateHandleResponse(resp *http.Response) (ContentKeyPoliciesUpdateResponse, error) { + result := ContentKeyPoliciesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ContentKeyPolicy); err != nil { + return ContentKeyPoliciesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *ContentKeyPoliciesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_jobs_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_jobs_client.go new file mode 100644 index 000000000000..5fece488786b --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_jobs_client.go @@ -0,0 +1,455 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// JobsClient contains the methods for the Jobs group. +// Don't use this type directly, use NewJobsClient() instead. +type JobsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewJobsClient creates a new instance of JobsClient with the specified values. +func NewJobsClient(con *arm.Connection, subscriptionID string) *JobsClient { + return &JobsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CancelJob - Cancel a Job. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) CancelJob(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsCancelJobOptions) (JobsCancelJobResponse, error) { + req, err := client.cancelJobCreateRequest(ctx, resourceGroupName, accountName, transformName, jobName, options) + if err != nil { + return JobsCancelJobResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsCancelJobResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsCancelJobResponse{}, client.cancelJobHandleError(resp) + } + return JobsCancelJobResponse{RawResponse: resp}, nil +} + +// cancelJobCreateRequest creates the CancelJob request. +func (client *JobsClient) cancelJobCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsCancelJobOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs/{jobName}/cancelJob" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// cancelJobHandleError handles the CancelJob error response. +func (client *JobsClient) cancelJobHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Create - Creates a Job. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) Create(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, parameters Job, options *JobsCreateOptions) (JobsCreateResponse, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, transformName, jobName, parameters, options) + if err != nil { + return JobsCreateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsCreateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusCreated) { + return JobsCreateResponse{}, client.createHandleError(resp) + } + return client.createHandleResponse(resp) +} + +// createCreateRequest creates the Create request. +func (client *JobsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, parameters Job, options *JobsCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleResponse handles the Create response. +func (client *JobsClient) createHandleResponse(resp *http.Response) (JobsCreateResponse, error) { + result := JobsCreateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Job); err != nil { + return JobsCreateResponse{}, err + } + return result, nil +} + +// createHandleError handles the Create error response. +func (client *JobsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Job. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsDeleteOptions) (JobsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, transformName, jobName, options) + if err != nil { + return JobsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return JobsDeleteResponse{}, client.deleteHandleError(resp) + } + return JobsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *JobsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *JobsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets a Job. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) Get(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsGetOptions) (JobsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, transformName, jobName, options) + if err != nil { + return JobsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *JobsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, options *JobsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *JobsClient) getHandleResponse(resp *http.Response) (JobsGetResponse, error) { + result := JobsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Job); err != nil { + return JobsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *JobsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists all of the Jobs for the Transform. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) List(resourceGroupName string, accountName string, transformName string, options *JobsListOptions) *JobsListPager { + return &JobsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, transformName, options) + }, + advancer: func(ctx context.Context, resp JobsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.JobCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *JobsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, options *JobsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *JobsClient) listHandleResponse(resp *http.Response) (JobsListResponse, error) { + result := JobsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollection); err != nil { + return JobsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *JobsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Update is only supported for description and priority. Updating Priority will take effect when the Job state is Queued or Scheduled and depending +// on the timing the priority update may be ignored. +// If the operation fails it returns the *ErrorResponse error type. +func (client *JobsClient) Update(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, parameters Job, options *JobsUpdateOptions) (JobsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, transformName, jobName, parameters, options) + if err != nil { + return JobsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *JobsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, jobName string, parameters Job, options *JobsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *JobsClient) updateHandleResponse(resp *http.Response) (JobsUpdateResponse, error) { + result := JobsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Job); err != nil { + return JobsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *JobsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveevents_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveevents_client.go new file mode 100644 index 000000000000..31a0ae015960 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveevents_client.go @@ -0,0 +1,735 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// LiveEventsClient contains the methods for the LiveEvents group. +// Don't use this type directly, use NewLiveEventsClient() instead. +type LiveEventsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewLiveEventsClient creates a new instance of LiveEventsClient with the specified values. +func NewLiveEventsClient(con *arm.Connection, subscriptionID string) *LiveEventsClient { + return &LiveEventsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginAllocate - A live event is in StandBy state after allocation completes, and is ready to start. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginAllocate(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginAllocateOptions) (LiveEventsAllocatePollerResponse, error) { + resp, err := client.allocate(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return LiveEventsAllocatePollerResponse{}, err + } + result := LiveEventsAllocatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Allocate", "", resp, client.pl, client.allocateHandleError) + if err != nil { + return LiveEventsAllocatePollerResponse{}, err + } + result.Poller = &LiveEventsAllocatePoller{ + pt: pt, + } + return result, nil +} + +// Allocate - A live event is in StandBy state after allocation completes, and is ready to start. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) allocate(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginAllocateOptions) (*http.Response, error) { + req, err := client.allocateCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.allocateHandleError(resp) + } + return resp, nil +} + +// allocateCreateRequest creates the Allocate request. +func (client *LiveEventsClient) allocateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginAllocateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/allocate" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// allocateHandleError handles the Allocate error response. +func (client *LiveEventsClient) allocateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginCreate - Creates a new live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginCreateOptions) (LiveEventsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return LiveEventsCreatePollerResponse{}, err + } + result := LiveEventsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return LiveEventsCreatePollerResponse{}, err + } + result.Poller = &LiveEventsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Creates a new live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) create(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *LiveEventsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.AutoStart != nil { + reqQP.Set("autoStart", strconv.FormatBool(*options.AutoStart)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleError handles the Create error response. +func (client *LiveEventsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes a live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginDeleteOptions) (LiveEventsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return LiveEventsDeletePollerResponse{}, err + } + result := LiveEventsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return LiveEventsDeletePollerResponse{}, err + } + result.Poller = &LiveEventsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LiveEventsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *LiveEventsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets properties of a live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) Get(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsGetOptions) (LiveEventsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return LiveEventsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return LiveEventsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return LiveEventsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *LiveEventsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LiveEventsClient) getHandleResponse(resp *http.Response) (LiveEventsGetResponse, error) { + result := LiveEventsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.LiveEvent); err != nil { + return LiveEventsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *LiveEventsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists all the live events in the account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) List(resourceGroupName string, accountName string, options *LiveEventsListOptions) *LiveEventsListPager { + return &LiveEventsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp LiveEventsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.LiveEventListResult.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *LiveEventsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *LiveEventsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LiveEventsClient) listHandleResponse(resp *http.Response) (LiveEventsListResponse, error) { + result := LiveEventsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.LiveEventListResult); err != nil { + return LiveEventsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *LiveEventsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginReset - Resets an existing live event. All live outputs for the live event are deleted and the live event is stopped and will be started again. +// All assets used by the live outputs and streaming locators +// created on these assets are unaffected. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginReset(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginResetOptions) (LiveEventsResetPollerResponse, error) { + resp, err := client.reset(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return LiveEventsResetPollerResponse{}, err + } + result := LiveEventsResetPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Reset", "", resp, client.pl, client.resetHandleError) + if err != nil { + return LiveEventsResetPollerResponse{}, err + } + result.Poller = &LiveEventsResetPoller{ + pt: pt, + } + return result, nil +} + +// Reset - Resets an existing live event. All live outputs for the live event are deleted and the live event is stopped and will be started again. All assets +// used by the live outputs and streaming locators +// created on these assets are unaffected. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) reset(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginResetOptions) (*http.Response, error) { + req, err := client.resetCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.resetHandleError(resp) + } + return resp, nil +} + +// resetCreateRequest creates the Reset request. +func (client *LiveEventsClient) resetCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginResetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/reset" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// resetHandleError handles the Reset error response. +func (client *LiveEventsClient) resetHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStart - A live event in Stopped or StandBy state will be in Running state after the start operation completes. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginStart(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginStartOptions) (LiveEventsStartPollerResponse, error) { + resp, err := client.start(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return LiveEventsStartPollerResponse{}, err + } + result := LiveEventsStartPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Start", "", resp, client.pl, client.startHandleError) + if err != nil { + return LiveEventsStartPollerResponse{}, err + } + result.Poller = &LiveEventsStartPoller{ + pt: pt, + } + return result, nil +} + +// Start - A live event in Stopped or StandBy state will be in Running state after the start operation completes. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) start(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginStartOptions) (*http.Response, error) { + req, err := client.startCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.startHandleError(resp) + } + return resp, nil +} + +// startCreateRequest creates the Start request. +func (client *LiveEventsClient) startCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveEventsBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// startHandleError handles the Start error response. +func (client *LiveEventsClient) startHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStop - Stops a running live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginStop(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEventActionInput, options *LiveEventsBeginStopOptions) (LiveEventsStopPollerResponse, error) { + resp, err := client.stop(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return LiveEventsStopPollerResponse{}, err + } + result := LiveEventsStopPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Stop", "", resp, client.pl, client.stopHandleError) + if err != nil { + return LiveEventsStopPollerResponse{}, err + } + result.Poller = &LiveEventsStopPoller{ + pt: pt, + } + return result, nil +} + +// Stop - Stops a running live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) stop(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEventActionInput, options *LiveEventsBeginStopOptions) (*http.Response, error) { + req, err := client.stopCreateRequest(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.stopHandleError(resp) + } + return resp, nil +} + +// stopCreateRequest creates the Stop request. +func (client *LiveEventsClient) stopCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEventActionInput, options *LiveEventsBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/stop" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// stopHandleError handles the Stop error response. +func (client *LiveEventsClient) stopHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates settings on an existing live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginUpdateOptions) (LiveEventsUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return LiveEventsUpdatePollerResponse{}, err + } + result := LiveEventsUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveEventsClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return LiveEventsUpdatePollerResponse{}, err + } + result.Poller = &LiveEventsUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates settings on an existing live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveEventsClient) update(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, liveEventName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *LiveEventsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, parameters LiveEvent, options *LiveEventsBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleError handles the Update error response. +func (client *LiveEventsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveoutputs_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveoutputs_client.go new file mode 100644 index 000000000000..cc45d148de56 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_liveoutputs_client.go @@ -0,0 +1,343 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// LiveOutputsClient contains the methods for the LiveOutputs group. +// Don't use this type directly, use NewLiveOutputsClient() instead. +type LiveOutputsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewLiveOutputsClient creates a new instance of LiveOutputsClient with the specified values. +func NewLiveOutputsClient(con *arm.Connection, subscriptionID string) *LiveOutputsClient { + return &LiveOutputsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreate - Creates a new live output. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, parameters LiveOutput, options *LiveOutputsBeginCreateOptions) (LiveOutputsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, accountName, liveEventName, liveOutputName, parameters, options) + if err != nil { + return LiveOutputsCreatePollerResponse{}, err + } + result := LiveOutputsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveOutputsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return LiveOutputsCreatePollerResponse{}, err + } + result.Poller = &LiveOutputsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Creates a new live output. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) create(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, parameters LiveOutput, options *LiveOutputsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, liveEventName, liveOutputName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *LiveOutputsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, parameters LiveOutput, options *LiveOutputsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + if liveOutputName == "" { + return nil, errors.New("parameter liveOutputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveOutputName}", url.PathEscape(liveOutputName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleError handles the Create error response. +func (client *LiveOutputsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes a live output. Deleting a live output does not delete the asset the live output is writing to. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, options *LiveOutputsBeginDeleteOptions) (LiveOutputsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, liveEventName, liveOutputName, options) + if err != nil { + return LiveOutputsDeletePollerResponse{}, err + } + result := LiveOutputsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("LiveOutputsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return LiveOutputsDeletePollerResponse{}, err + } + result.Poller = &LiveOutputsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a live output. Deleting a live output does not delete the asset the live output is writing to. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, options *LiveOutputsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, liveEventName, liveOutputName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *LiveOutputsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, options *LiveOutputsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + if liveOutputName == "" { + return nil, errors.New("parameter liveOutputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveOutputName}", url.PathEscape(liveOutputName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *LiveOutputsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets a live output. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) Get(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, options *LiveOutputsGetOptions) (LiveOutputsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, liveEventName, liveOutputName, options) + if err != nil { + return LiveOutputsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return LiveOutputsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return LiveOutputsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *LiveOutputsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, liveOutputName string, options *LiveOutputsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs/{liveOutputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + if liveOutputName == "" { + return nil, errors.New("parameter liveOutputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveOutputName}", url.PathEscape(liveOutputName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *LiveOutputsClient) getHandleResponse(resp *http.Response) (LiveOutputsGetResponse, error) { + result := LiveOutputsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.LiveOutput); err != nil { + return LiveOutputsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *LiveOutputsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the live outputs of a live event. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LiveOutputsClient) List(resourceGroupName string, accountName string, liveEventName string, options *LiveOutputsListOptions) *LiveOutputsListPager { + return &LiveOutputsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, liveEventName, options) + }, + advancer: func(ctx context.Context, resp LiveOutputsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.LiveOutputListResult.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *LiveOutputsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, liveEventName string, options *LiveOutputsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/liveEvents/{liveEventName}/liveOutputs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if liveEventName == "" { + return nil, errors.New("parameter liveEventName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{liveEventName}", url.PathEscape(liveEventName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *LiveOutputsClient) listHandleResponse(resp *http.Response) (LiveOutputsListResponse, error) { + result := LiveOutputsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.LiveOutputListResult); err != nil { + return LiveOutputsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *LiveOutputsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_locations_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_locations_client.go new file mode 100644 index 000000000000..fa702a4739f2 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_locations_client.go @@ -0,0 +1,96 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// LocationsClient contains the methods for the Locations group. +// Don't use this type directly, use NewLocationsClient() instead. +type LocationsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewLocationsClient creates a new instance of LocationsClient with the specified values. +func NewLocationsClient(con *arm.Connection, subscriptionID string) *LocationsClient { + return &LocationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckNameAvailability - Checks whether the Media Service resource name is available. +// If the operation fails it returns the *ErrorResponse error type. +func (client *LocationsClient) CheckNameAvailability(ctx context.Context, locationName string, parameters CheckNameAvailabilityInput, options *LocationsCheckNameAvailabilityOptions) (LocationsCheckNameAvailabilityResponse, error) { + req, err := client.checkNameAvailabilityCreateRequest(ctx, locationName, parameters, options) + if err != nil { + return LocationsCheckNameAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return LocationsCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return LocationsCheckNameAvailabilityResponse{}, client.checkNameAvailabilityHandleError(resp) + } + return client.checkNameAvailabilityHandleResponse(resp) +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *LocationsClient) checkNameAvailabilityCreateRequest(ctx context.Context, locationName string, parameters CheckNameAvailabilityInput, options *LocationsCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Media/locations/{locationName}/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if locationName == "" { + return nil, errors.New("parameter locationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{locationName}", url.PathEscape(locationName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *LocationsClient) checkNameAvailabilityHandleResponse(resp *http.Response) (LocationsCheckNameAvailabilityResponse, error) { + result := LocationsCheckNameAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.EntityNameAvailabilityCheckOutput); err != nil { + return LocationsCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// checkNameAvailabilityHandleError handles the CheckNameAvailability error response. +func (client *LocationsClient) checkNameAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_mediaservices_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_mediaservices_client.go new file mode 100644 index 000000000000..f0eb62f58d18 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_mediaservices_client.go @@ -0,0 +1,519 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// MediaservicesClient contains the methods for the Mediaservices group. +// Don't use this type directly, use NewMediaservicesClient() instead. +type MediaservicesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewMediaservicesClient creates a new instance of MediaservicesClient with the specified values. +func NewMediaservicesClient(con *arm.Connection, subscriptionID string) *MediaservicesClient { + return &MediaservicesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates a Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, parameters MediaService, options *MediaservicesCreateOrUpdateOptions) (MediaservicesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return MediaservicesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return MediaservicesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *MediaservicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters MediaService, options *MediaservicesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *MediaservicesClient) createOrUpdateHandleResponse(resp *http.Response) (MediaservicesCreateOrUpdateResponse, error) { + result := MediaservicesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.MediaService); err != nil { + return MediaservicesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *MediaservicesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, options *MediaservicesDeleteOptions) (MediaservicesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return MediaservicesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return MediaservicesDeleteResponse{}, client.deleteHandleError(resp) + } + return MediaservicesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *MediaservicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *MediaservicesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *MediaservicesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of a Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) Get(ctx context.Context, resourceGroupName string, accountName string, options *MediaservicesGetOptions) (MediaservicesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return MediaservicesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MediaservicesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *MediaservicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *MediaservicesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *MediaservicesClient) getHandleResponse(resp *http.Response) (MediaservicesGetResponse, error) { + result := MediaservicesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.MediaService); err != nil { + return MediaservicesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *MediaservicesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - List Media Services accounts in the resource group +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) List(resourceGroupName string, options *MediaservicesListOptions) *MediaservicesListPager { + return &MediaservicesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp MediaservicesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.MediaServiceCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *MediaservicesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *MediaservicesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *MediaservicesClient) listHandleResponse(resp *http.Response) (MediaservicesListResponse, error) { + result := MediaservicesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.MediaServiceCollection); err != nil { + return MediaservicesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *MediaservicesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscription - List Media Services accounts in the subscription. +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) ListBySubscription(options *MediaservicesListBySubscriptionOptions) *MediaservicesListBySubscriptionPager { + return &MediaservicesListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp MediaservicesListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.MediaServiceCollection.ODataNextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *MediaservicesClient) listBySubscriptionCreateRequest(ctx context.Context, options *MediaservicesListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Media/mediaservices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *MediaservicesClient) listBySubscriptionHandleResponse(resp *http.Response) (MediaservicesListBySubscriptionResponse, error) { + result := MediaservicesListBySubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.MediaServiceCollection); err != nil { + return MediaservicesListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *MediaservicesClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListEdgePolicies - List the media edge policies associated with the Media Services account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) ListEdgePolicies(ctx context.Context, resourceGroupName string, accountName string, parameters ListEdgePoliciesInput, options *MediaservicesListEdgePoliciesOptions) (MediaservicesListEdgePoliciesResponse, error) { + req, err := client.listEdgePoliciesCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return MediaservicesListEdgePoliciesResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesListEdgePoliciesResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MediaservicesListEdgePoliciesResponse{}, client.listEdgePoliciesHandleError(resp) + } + return client.listEdgePoliciesHandleResponse(resp) +} + +// listEdgePoliciesCreateRequest creates the ListEdgePolicies request. +func (client *MediaservicesClient) listEdgePoliciesCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters ListEdgePoliciesInput, options *MediaservicesListEdgePoliciesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/listEdgePolicies" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// listEdgePoliciesHandleResponse handles the ListEdgePolicies response. +func (client *MediaservicesClient) listEdgePoliciesHandleResponse(resp *http.Response) (MediaservicesListEdgePoliciesResponse, error) { + result := MediaservicesListEdgePoliciesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.EdgePolicies); err != nil { + return MediaservicesListEdgePoliciesResponse{}, err + } + return result, nil +} + +// listEdgePoliciesHandleError handles the ListEdgePolicies error response. +func (client *MediaservicesClient) listEdgePoliciesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// SyncStorageKeys - Synchronizes storage account keys for a storage account associated with the Media Service account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) SyncStorageKeys(ctx context.Context, resourceGroupName string, accountName string, parameters SyncStorageKeysInput, options *MediaservicesSyncStorageKeysOptions) (MediaservicesSyncStorageKeysResponse, error) { + req, err := client.syncStorageKeysCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return MediaservicesSyncStorageKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesSyncStorageKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MediaservicesSyncStorageKeysResponse{}, client.syncStorageKeysHandleError(resp) + } + return MediaservicesSyncStorageKeysResponse{RawResponse: resp}, nil +} + +// syncStorageKeysCreateRequest creates the SyncStorageKeys request. +func (client *MediaservicesClient) syncStorageKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters SyncStorageKeysInput, options *MediaservicesSyncStorageKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/syncStorageKeys" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// syncStorageKeysHandleError handles the SyncStorageKeys error response. +func (client *MediaservicesClient) syncStorageKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *MediaservicesClient) Update(ctx context.Context, resourceGroupName string, accountName string, parameters MediaServiceUpdate, options *MediaservicesUpdateOptions) (MediaservicesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, parameters, options) + if err != nil { + return MediaservicesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return MediaservicesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return MediaservicesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *MediaservicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, parameters MediaServiceUpdate, options *MediaservicesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *MediaservicesClient) updateHandleResponse(resp *http.Response) (MediaservicesUpdateResponse, error) { + result := MediaservicesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.MediaService); err != nil { + return MediaservicesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *MediaservicesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_models.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_models.go new file mode 100644 index 000000000000..ac8501a2c873 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_models.go @@ -0,0 +1,7147 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AacAudio - Describes Advanced Audio Codec (AAC) audio encoding settings. +type AacAudio struct { + Audio + // The encoding profile to be used when encoding audio with AAC. + Profile *AacAudioProfile `json:"profile,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AacAudio. +func (a AacAudio) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Audio.marshalInternal(objectMap, "#Microsoft.Media.AacAudio") + populate(objectMap, "profile", a.Profile) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AacAudio. +func (a *AacAudio) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "profile": + err = unpopulate(val, &a.Profile) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Audio.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AbsoluteClipTime - Specifies the clip time as an absolute time position in the media file. The absolute time can point to a different position depending +// on whether the media file starts from a timestamp of zero or not. +type AbsoluteClipTime struct { + ClipTime + // REQUIRED; The time position on the timeline of the input media. It is usually specified as an ISO8601 period. e.g PT30S for 30 seconds. + Time *string `json:"time,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AbsoluteClipTime. +func (a AbsoluteClipTime) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ClipTime.marshalInternal(objectMap, "#Microsoft.Media.AbsoluteClipTime") + populate(objectMap, "time", a.Time) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AbsoluteClipTime. +func (a *AbsoluteClipTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "time": + err = unpopulate(val, &a.Time) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.ClipTime.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type AccessControl struct { + // The behavior for IP access control in Key Delivery. + DefaultAction *DefaultAction `json:"defaultAction,omitempty"` + + // The IP allow list for access control in Key Delivery. If the default action is set to 'Allow', the IP allow list must be empty. + IPAllowList []*string `json:"ipAllowList,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccessControl. +func (a AccessControl) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "defaultAction", a.DefaultAction) + populate(objectMap, "ipAllowList", a.IPAllowList) + return json.Marshal(objectMap) +} + +type AccountEncryption struct { + // REQUIRED; The type of key used to encrypt the Account Key. + Type *AccountEncryptionKeyType `json:"type,omitempty"` + + // The Key Vault identity. + Identity *ResourceIdentity `json:"identity,omitempty"` + + // The properties of the key used to encrypt the account. + KeyVaultProperties *KeyVaultProperties `json:"keyVaultProperties,omitempty"` + + // READ-ONLY; The current status of the Key Vault mapping. + Status *string `json:"status,omitempty" azure:"ro"` +} + +// AccountFilter - An Account Filter. +type AccountFilter struct { + ProxyResource + // The Media Filter properties. + Properties *MediaFilterProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccountFilter. +func (a AccountFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + return json.Marshal(objectMap) +} + +// AccountFilterCollection - A collection of AccountFilter items. +type AccountFilterCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of AccountFilter items. + Value []*AccountFilter `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AccountFilterCollection. +func (a AccountFilterCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", a.ODataNextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AccountFiltersCreateOrUpdateOptions contains the optional parameters for the AccountFilters.CreateOrUpdate method. +type AccountFiltersCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AccountFiltersDeleteOptions contains the optional parameters for the AccountFilters.Delete method. +type AccountFiltersDeleteOptions struct { + // placeholder for future optional parameters +} + +// AccountFiltersGetOptions contains the optional parameters for the AccountFilters.Get method. +type AccountFiltersGetOptions struct { + // placeholder for future optional parameters +} + +// AccountFiltersListOptions contains the optional parameters for the AccountFilters.List method. +type AccountFiltersListOptions struct { + // placeholder for future optional parameters +} + +// AccountFiltersUpdateOptions contains the optional parameters for the AccountFilters.Update method. +type AccountFiltersUpdateOptions struct { + // placeholder for future optional parameters +} + +// AkamaiAccessControl - Akamai access control +type AkamaiAccessControl struct { + // authentication key list + AkamaiSignatureHeaderAuthenticationKeyList []*AkamaiSignatureHeaderAuthenticationKey `json:"akamaiSignatureHeaderAuthenticationKeyList,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AkamaiAccessControl. +func (a AkamaiAccessControl) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "akamaiSignatureHeaderAuthenticationKeyList", a.AkamaiSignatureHeaderAuthenticationKeyList) + return json.Marshal(objectMap) +} + +// AkamaiSignatureHeaderAuthenticationKey - Akamai Signature Header authentication key. +type AkamaiSignatureHeaderAuthenticationKey struct { + // authentication key + Base64Key *string `json:"base64Key,omitempty"` + + // The expiration time of the authentication key. + Expiration *time.Time `json:"expiration,omitempty"` + + // identifier of the key + Identifier *string `json:"identifier,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AkamaiSignatureHeaderAuthenticationKey. +func (a AkamaiSignatureHeaderAuthenticationKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "base64Key", a.Base64Key) + populate(objectMap, "expiration", (*timeRFC3339)(a.Expiration)) + populate(objectMap, "identifier", a.Identifier) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AkamaiSignatureHeaderAuthenticationKey. +func (a *AkamaiSignatureHeaderAuthenticationKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "base64Key": + err = unpopulate(val, &a.Base64Key) + delete(rawMsg, key) + case "expiration": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.Expiration = (*time.Time)(&aux) + delete(rawMsg, key) + case "identifier": + err = unpopulate(val, &a.Identifier) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// Asset - An Asset. +type Asset struct { + ProxyResource + // The resource properties. + Properties *AssetProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Asset. +func (a Asset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + return json.Marshal(objectMap) +} + +// AssetCollection - A collection of Asset items. +type AssetCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of Asset items. + Value []*Asset `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetCollection. +func (a AssetCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", a.ODataNextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AssetContainerSas - The Asset Storage container SAS URLs. +type AssetContainerSas struct { + // The list of Asset container SAS URLs. + AssetContainerSasUrls []*string `json:"assetContainerSasUrls,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetContainerSas. +func (a AssetContainerSas) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "assetContainerSasUrls", a.AssetContainerSasUrls) + return json.Marshal(objectMap) +} + +// AssetFileEncryptionMetadata - The Asset File Storage encryption metadata. +type AssetFileEncryptionMetadata struct { + // REQUIRED; The Asset File Id. + AssetFileID *string `json:"assetFileId,omitempty"` + + // The Asset File name. + AssetFileName *string `json:"assetFileName,omitempty"` + + // The Asset File initialization vector. + InitializationVector *string `json:"initializationVector,omitempty"` +} + +// AssetFilter - An Asset Filter. +type AssetFilter struct { + ProxyResource + // The Media Filter properties. + Properties *MediaFilterProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetFilter. +func (a AssetFilter) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + populate(objectMap, "systemData", a.SystemData) + return json.Marshal(objectMap) +} + +// AssetFilterCollection - A collection of AssetFilter items. +type AssetFilterCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of AssetFilter items. + Value []*AssetFilter `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetFilterCollection. +func (a AssetFilterCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", a.ODataNextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AssetFiltersCreateOrUpdateOptions contains the optional parameters for the AssetFilters.CreateOrUpdate method. +type AssetFiltersCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AssetFiltersDeleteOptions contains the optional parameters for the AssetFilters.Delete method. +type AssetFiltersDeleteOptions struct { + // placeholder for future optional parameters +} + +// AssetFiltersGetOptions contains the optional parameters for the AssetFilters.Get method. +type AssetFiltersGetOptions struct { + // placeholder for future optional parameters +} + +// AssetFiltersListOptions contains the optional parameters for the AssetFilters.List method. +type AssetFiltersListOptions struct { + // placeholder for future optional parameters +} + +// AssetFiltersUpdateOptions contains the optional parameters for the AssetFilters.Update method. +type AssetFiltersUpdateOptions struct { + // placeholder for future optional parameters +} + +// AssetProperties - The Asset properties. +type AssetProperties struct { + // The alternate ID of the Asset. + AlternateID *string `json:"alternateId,omitempty"` + + // The name of the asset blob container. + Container *string `json:"container,omitempty"` + + // The Asset description. + Description *string `json:"description,omitempty"` + + // The name of the storage account. + StorageAccountName *string `json:"storageAccountName,omitempty"` + + // READ-ONLY; The Asset ID. + AssetID *string `json:"assetId,omitempty" azure:"ro"` + + // READ-ONLY; The creation date of the Asset. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The last modified date of the Asset. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The Asset encryption format. One of None or MediaStorageEncryption. + StorageEncryptionFormat *AssetStorageEncryptionFormat `json:"storageEncryptionFormat,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetProperties. +func (a AssetProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "alternateId", a.AlternateID) + populate(objectMap, "assetId", a.AssetID) + populate(objectMap, "container", a.Container) + populate(objectMap, "created", (*timeRFC3339)(a.Created)) + populate(objectMap, "description", a.Description) + populate(objectMap, "lastModified", (*timeRFC3339)(a.LastModified)) + populate(objectMap, "storageAccountName", a.StorageAccountName) + populate(objectMap, "storageEncryptionFormat", a.StorageEncryptionFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AssetProperties. +func (a *AssetProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "alternateId": + err = unpopulate(val, &a.AlternateID) + delete(rawMsg, key) + case "assetId": + err = unpopulate(val, &a.AssetID) + delete(rawMsg, key) + case "container": + err = unpopulate(val, &a.Container) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &a.Description) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "storageAccountName": + err = unpopulate(val, &a.StorageAccountName) + delete(rawMsg, key) + case "storageEncryptionFormat": + err = unpopulate(val, &a.StorageEncryptionFormat) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AssetStreamingLocator - Properties of the Streaming Locator. +type AssetStreamingLocator struct { + // READ-ONLY; Asset Name. + AssetName *string `json:"assetName,omitempty" azure:"ro"` + + // READ-ONLY; The creation time of the Streaming Locator. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; Name of the default ContentKeyPolicy used by this Streaming Locator. + DefaultContentKeyPolicyName *string `json:"defaultContentKeyPolicyName,omitempty" azure:"ro"` + + // READ-ONLY; The end time of the Streaming Locator. + EndTime *time.Time `json:"endTime,omitempty" azure:"ro"` + + // READ-ONLY; Streaming Locator name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The start time of the Streaming Locator. + StartTime *time.Time `json:"startTime,omitempty" azure:"ro"` + + // READ-ONLY; StreamingLocatorId of the Streaming Locator. + StreamingLocatorID *string `json:"streamingLocatorId,omitempty" azure:"ro"` + + // READ-ONLY; Name of the Streaming Policy used by this Streaming Locator. + StreamingPolicyName *string `json:"streamingPolicyName,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type AssetStreamingLocator. +func (a AssetStreamingLocator) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "assetName", a.AssetName) + populate(objectMap, "created", (*timeRFC3339)(a.Created)) + populate(objectMap, "defaultContentKeyPolicyName", a.DefaultContentKeyPolicyName) + populate(objectMap, "endTime", (*timeRFC3339)(a.EndTime)) + populate(objectMap, "name", a.Name) + populate(objectMap, "startTime", (*timeRFC3339)(a.StartTime)) + populate(objectMap, "streamingLocatorId", a.StreamingLocatorID) + populate(objectMap, "streamingPolicyName", a.StreamingPolicyName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AssetStreamingLocator. +func (a *AssetStreamingLocator) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "assetName": + err = unpopulate(val, &a.AssetName) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "defaultContentKeyPolicyName": + err = unpopulate(val, &a.DefaultContentKeyPolicyName) + delete(rawMsg, key) + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "name": + err = unpopulate(val, &a.Name) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "streamingLocatorId": + err = unpopulate(val, &a.StreamingLocatorID) + delete(rawMsg, key) + case "streamingPolicyName": + err = unpopulate(val, &a.StreamingPolicyName) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AssetsCreateOrUpdateOptions contains the optional parameters for the Assets.CreateOrUpdate method. +type AssetsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// AssetsDeleteOptions contains the optional parameters for the Assets.Delete method. +type AssetsDeleteOptions struct { + // placeholder for future optional parameters +} + +// AssetsGetEncryptionKeyOptions contains the optional parameters for the Assets.GetEncryptionKey method. +type AssetsGetEncryptionKeyOptions struct { + // placeholder for future optional parameters +} + +// AssetsGetOptions contains the optional parameters for the Assets.Get method. +type AssetsGetOptions struct { + // placeholder for future optional parameters +} + +// AssetsListContainerSasOptions contains the optional parameters for the Assets.ListContainerSas method. +type AssetsListContainerSasOptions struct { + // placeholder for future optional parameters +} + +// AssetsListOptions contains the optional parameters for the Assets.List method. +type AssetsListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string + // Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to + // but not greater than the specified value n. + Top *int32 +} + +// AssetsListStreamingLocatorsOptions contains the optional parameters for the Assets.ListStreamingLocators method. +type AssetsListStreamingLocatorsOptions struct { + // placeholder for future optional parameters +} + +// AssetsUpdateOptions contains the optional parameters for the Assets.Update method. +type AssetsUpdateOptions struct { + // placeholder for future optional parameters +} + +// AudioClassification provides polymorphic access to related types. +// Call the interface's GetAudio() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AacAudio, *Audio +type AudioClassification interface { + CodecClassification + // GetAudio returns the Audio content of the underlying type. + GetAudio() *Audio +} + +// Audio - Defines the common properties for all audio codecs. +type Audio struct { + Codec + // The bitrate, in bits per second, of the output encoded audio. + Bitrate *int32 `json:"bitrate,omitempty"` + + // The number of channels in the audio. + Channels *int32 `json:"channels,omitempty"` + + // The sampling rate to use for encoding in hertz. + SamplingRate *int32 `json:"samplingRate,omitempty"` +} + +// GetAudio implements the AudioClassification interface for type Audio. +func (a *Audio) GetAudio() *Audio { return a } + +// MarshalJSON implements the json.Marshaller interface for type Audio. +func (a Audio) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.marshalInternal(objectMap, "#Microsoft.Media.Audio") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Audio. +func (a *Audio) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return a.unmarshalInternal(rawMsg) +} + +func (a Audio) marshalInternal(objectMap map[string]interface{}, discValue string) { + a.Codec.marshalInternal(objectMap, discValue) + populate(objectMap, "bitrate", a.Bitrate) + populate(objectMap, "channels", a.Channels) + populate(objectMap, "samplingRate", a.SamplingRate) +} + +func (a *Audio) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "bitrate": + err = unpopulate(val, &a.Bitrate) + delete(rawMsg, key) + case "channels": + err = unpopulate(val, &a.Channels) + delete(rawMsg, key) + case "samplingRate": + err = unpopulate(val, &a.SamplingRate) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Codec.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AudioAnalyzerPresetClassification provides polymorphic access to related types. +// Call the interface's GetAudioAnalyzerPreset() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AudioAnalyzerPreset, *VideoAnalyzerPreset +type AudioAnalyzerPresetClassification interface { + PresetClassification + // GetAudioAnalyzerPreset returns the AudioAnalyzerPreset content of the underlying type. + GetAudioAnalyzerPreset() *AudioAnalyzerPreset +} + +// AudioAnalyzerPreset - The Audio Analyzer preset applies a pre-defined set of AI-based analysis operations, including speech transcription. Currently, +// the preset supports processing of content with a single audio track. +type AudioAnalyzerPreset struct { + Preset + // 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. The + // language must be specified explicitly for AudioAnalysisMode::Basic, since automatic language detection is not included in basic mode. 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 + AudioLanguage *string `json:"audioLanguage,omitempty"` + + // Dictionary containing key value pairs for parameters not exposed in the preset itself + ExperimentalOptions map[string]*string `json:"experimentalOptions,omitempty"` + + // Determines the set of audio analysis operations to be performed. If unspecified, the Standard AudioAnalysisMode would be chosen. + Mode *AudioAnalysisMode `json:"mode,omitempty"` +} + +// GetAudioAnalyzerPreset implements the AudioAnalyzerPresetClassification interface for type AudioAnalyzerPreset. +func (a *AudioAnalyzerPreset) GetAudioAnalyzerPreset() *AudioAnalyzerPreset { return a } + +// MarshalJSON implements the json.Marshaller interface for type AudioAnalyzerPreset. +func (a AudioAnalyzerPreset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.marshalInternal(objectMap, "#Microsoft.Media.AudioAnalyzerPreset") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AudioAnalyzerPreset. +func (a *AudioAnalyzerPreset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return a.unmarshalInternal(rawMsg) +} + +func (a AudioAnalyzerPreset) marshalInternal(objectMap map[string]interface{}, discValue string) { + a.Preset.marshalInternal(objectMap, discValue) + populate(objectMap, "audioLanguage", a.AudioLanguage) + populate(objectMap, "experimentalOptions", a.ExperimentalOptions) + populate(objectMap, "mode", a.Mode) +} + +func (a *AudioAnalyzerPreset) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "audioLanguage": + err = unpopulate(val, &a.AudioLanguage) + delete(rawMsg, key) + case "experimentalOptions": + err = unpopulate(val, &a.ExperimentalOptions) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, &a.Mode) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Preset.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AudioOverlay - Describes the properties of an audio overlay. +type AudioOverlay struct { + Overlay +} + +// MarshalJSON implements the json.Marshaller interface for type AudioOverlay. +func (a AudioOverlay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Overlay.marshalInternal(objectMap, "#Microsoft.Media.AudioOverlay") + return json.Marshal(objectMap) +} + +// AudioTrackDescriptorClassification provides polymorphic access to related types. +// Call the interface's GetAudioTrackDescriptor() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AudioTrackDescriptor, *SelectAudioTrackByAttribute, *SelectAudioTrackById +type AudioTrackDescriptorClassification interface { + TrackDescriptorClassification + // GetAudioTrackDescriptor returns the AudioTrackDescriptor content of the underlying type. + GetAudioTrackDescriptor() *AudioTrackDescriptor +} + +// AudioTrackDescriptor - A TrackSelection to select audio tracks. +type AudioTrackDescriptor struct { + TrackDescriptor + // Optional designation for single channel audio tracks. Can be used to combine the tracks into stereo or multi-channel audio tracks. + ChannelMapping *ChannelMapping `json:"channelMapping,omitempty"` +} + +// GetAudioTrackDescriptor implements the AudioTrackDescriptorClassification interface for type AudioTrackDescriptor. +func (a *AudioTrackDescriptor) GetAudioTrackDescriptor() *AudioTrackDescriptor { return a } + +// MarshalJSON implements the json.Marshaller interface for type AudioTrackDescriptor. +func (a AudioTrackDescriptor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.marshalInternal(objectMap, "#Microsoft.Media.AudioTrackDescriptor") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AudioTrackDescriptor. +func (a *AudioTrackDescriptor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return a.unmarshalInternal(rawMsg) +} + +func (a AudioTrackDescriptor) marshalInternal(objectMap map[string]interface{}, discValue string) { + a.TrackDescriptor.marshalInternal(objectMap, discValue) + populate(objectMap, "channelMapping", a.ChannelMapping) +} + +func (a *AudioTrackDescriptor) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "channelMapping": + err = unpopulate(val, &a.ChannelMapping) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.TrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// BuiltInStandardEncoderPreset - Describes a built-in preset for encoding the input video with the Standard Encoder. +type BuiltInStandardEncoderPreset struct { + Preset + // REQUIRED; The built-in preset to be used for encoding videos. + PresetName *EncoderNamedPreset `json:"presetName,omitempty"` + + // PresetConfigurations are only supported for the ContentAwareEncoding and H265ContentAwareEncoding built-in presets. These settings will not affect other + // built-in or custom defined presets. + Configurations *PresetConfigurations `json:"configurations,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BuiltInStandardEncoderPreset. +func (b BuiltInStandardEncoderPreset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.Preset.marshalInternal(objectMap, "#Microsoft.Media.BuiltInStandardEncoderPreset") + populate(objectMap, "configurations", b.Configurations) + populate(objectMap, "presetName", b.PresetName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BuiltInStandardEncoderPreset. +func (b *BuiltInStandardEncoderPreset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "configurations": + err = unpopulate(val, &b.Configurations) + delete(rawMsg, key) + case "presetName": + err = unpopulate(val, &b.PresetName) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := b.Preset.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// CbcsDrmConfiguration - Class to specify DRM configurations of CommonEncryptionCbcs scheme in Streaming Policy +type CbcsDrmConfiguration struct { + // FairPlay configurations + FairPlay *StreamingPolicyFairPlayConfiguration `json:"fairPlay,omitempty"` + + // PlayReady configurations + PlayReady *StreamingPolicyPlayReadyConfiguration `json:"playReady,omitempty"` + + // Widevine configurations + Widevine *StreamingPolicyWidevineConfiguration `json:"widevine,omitempty"` +} + +// CencDrmConfiguration - Class to specify DRM configurations of CommonEncryptionCenc scheme in Streaming Policy +type CencDrmConfiguration struct { + // PlayReady configurations + PlayReady *StreamingPolicyPlayReadyConfiguration `json:"playReady,omitempty"` + + // Widevine configurations + Widevine *StreamingPolicyWidevineConfiguration `json:"widevine,omitempty"` +} + +// CheckNameAvailabilityInput - The input to the check name availability request. +type CheckNameAvailabilityInput struct { + // The account name. + Name *string `json:"name,omitempty"` + + // The account type. For a Media Services account, this should be 'MediaServices'. + Type *string `json:"type,omitempty"` +} + +// ClipTimeClassification provides polymorphic access to related types. +// Call the interface's GetClipTime() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AbsoluteClipTime, *ClipTime, *UtcClipTime +type ClipTimeClassification interface { + // GetClipTime returns the ClipTime content of the underlying type. + GetClipTime() *ClipTime +} + +// ClipTime - Base class for specifying a clip time. Use sub classes of this class to specify the time position in the media. +type ClipTime struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetClipTime implements the ClipTimeClassification interface for type ClipTime. +func (c *ClipTime) GetClipTime() *ClipTime { return c } + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClipTime. +func (c *ClipTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c ClipTime) marshalInternal(objectMap map[string]interface{}, discValue string) { + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *ClipTime) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// CodecClassification provides polymorphic access to related types. +// Call the interface's GetCodec() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AacAudio, *Audio, *Codec, *CopyAudio, *CopyVideo, *H264Video, *H265Video, *Image, *JpgImage, *PngImage, *Video +type CodecClassification interface { + // GetCodec returns the Codec content of the underlying type. + GetCodec() *Codec +} + +// Codec - Describes the basic properties of all codecs. +type Codec struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` + + // An optional label for the codec. The label can be used to control muxing behavior. + Label *string `json:"label,omitempty"` +} + +// GetCodec implements the CodecClassification interface for type Codec. +func (c *Codec) GetCodec() *Codec { return c } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Codec. +func (c *Codec) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c Codec) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "label", c.Label) + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *Codec) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "label": + err = unpopulate(val, &c.Label) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// CommonEncryptionCbcs - Class for CommonEncryptionCbcs encryption scheme +type CommonEncryptionCbcs struct { + // Representing which tracks should not be encrypted + ClearTracks []*TrackSelection `json:"clearTracks,omitempty"` + + // Representing default content key for each encryption scheme and separate content keys for specific tracks + ContentKeys *StreamingPolicyContentKeys `json:"contentKeys,omitempty"` + + // Configuration of DRMs for current encryption scheme + Drm *CbcsDrmConfiguration `json:"drm,omitempty"` + + // Representing supported protocols + EnabledProtocols *EnabledProtocols `json:"enabledProtocols,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CommonEncryptionCbcs. +func (c CommonEncryptionCbcs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "clearTracks", c.ClearTracks) + populate(objectMap, "contentKeys", c.ContentKeys) + populate(objectMap, "drm", c.Drm) + populate(objectMap, "enabledProtocols", c.EnabledProtocols) + return json.Marshal(objectMap) +} + +// CommonEncryptionCenc - Class for envelope encryption scheme +type CommonEncryptionCenc struct { + // Representing which tracks should not be encrypted + ClearTracks []*TrackSelection `json:"clearTracks,omitempty"` + + // Representing default content key for each encryption scheme and separate content keys for specific tracks + ContentKeys *StreamingPolicyContentKeys `json:"contentKeys,omitempty"` + + // Configuration of DRMs for CommonEncryptionCenc encryption scheme + Drm *CencDrmConfiguration `json:"drm,omitempty"` + + // Representing supported protocols + EnabledProtocols *EnabledProtocols `json:"enabledProtocols,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CommonEncryptionCenc. +func (c CommonEncryptionCenc) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "clearTracks", c.ClearTracks) + populate(objectMap, "contentKeys", c.ContentKeys) + populate(objectMap, "drm", c.Drm) + populate(objectMap, "enabledProtocols", c.EnabledProtocols) + return json.Marshal(objectMap) +} + +// ContentKeyPoliciesCreateOrUpdateOptions contains the optional parameters for the ContentKeyPolicies.CreateOrUpdate method. +type ContentKeyPoliciesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ContentKeyPoliciesDeleteOptions contains the optional parameters for the ContentKeyPolicies.Delete method. +type ContentKeyPoliciesDeleteOptions struct { + // placeholder for future optional parameters +} + +// ContentKeyPoliciesGetOptions contains the optional parameters for the ContentKeyPolicies.Get method. +type ContentKeyPoliciesGetOptions struct { + // placeholder for future optional parameters +} + +// ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptions contains the optional parameters for the ContentKeyPolicies.GetPolicyPropertiesWithSecrets method. +type ContentKeyPoliciesGetPolicyPropertiesWithSecretsOptions struct { + // placeholder for future optional parameters +} + +// ContentKeyPoliciesListOptions contains the optional parameters for the ContentKeyPolicies.List method. +type ContentKeyPoliciesListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string + // Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to + // but not greater than the specified value n. + Top *int32 +} + +// ContentKeyPoliciesUpdateOptions contains the optional parameters for the ContentKeyPolicies.Update method. +type ContentKeyPoliciesUpdateOptions struct { + // placeholder for future optional parameters +} + +// ContentKeyPolicy - A Content Key Policy resource. +type ContentKeyPolicy struct { + ProxyResource + // The properties of the Content Key Policy. + Properties *ContentKeyPolicyProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicy. +func (c ContentKeyPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "systemData", c.SystemData) + return json.Marshal(objectMap) +} + +// ContentKeyPolicyClearKeyConfiguration - Represents a configuration for non-DRM keys. +type ContentKeyPolicyClearKeyConfiguration struct { + ContentKeyPolicyConfiguration +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyClearKeyConfiguration. +func (c ContentKeyPolicyClearKeyConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyConfiguration.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyClearKeyConfiguration") + return json.Marshal(objectMap) +} + +// ContentKeyPolicyCollection - A collection of ContentKeyPolicy items. +type ContentKeyPolicyCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of ContentKeyPolicy items. + Value []*ContentKeyPolicy `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyCollection. +func (c ContentKeyPolicyCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", c.ODataNextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// ContentKeyPolicyConfigurationClassification provides polymorphic access to related types. +// Call the interface's GetContentKeyPolicyConfiguration() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ContentKeyPolicyClearKeyConfiguration, *ContentKeyPolicyConfiguration, *ContentKeyPolicyFairPlayConfiguration, *ContentKeyPolicyPlayReadyConfiguration, +// - *ContentKeyPolicyUnknownConfiguration, *ContentKeyPolicyWidevineConfiguration +type ContentKeyPolicyConfigurationClassification interface { + // GetContentKeyPolicyConfiguration returns the ContentKeyPolicyConfiguration content of the underlying type. + GetContentKeyPolicyConfiguration() *ContentKeyPolicyConfiguration +} + +// ContentKeyPolicyConfiguration - Base class for Content Key Policy configuration. A derived class must be used to create a configuration. +type ContentKeyPolicyConfiguration struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetContentKeyPolicyConfiguration implements the ContentKeyPolicyConfigurationClassification interface for type ContentKeyPolicyConfiguration. +func (c *ContentKeyPolicyConfiguration) GetContentKeyPolicyConfiguration() *ContentKeyPolicyConfiguration { + return c +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyConfiguration. +func (c *ContentKeyPolicyConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c ContentKeyPolicyConfiguration) marshalInternal(objectMap map[string]interface{}, discValue string) { + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *ContentKeyPolicyConfiguration) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyFairPlayConfiguration - Specifies a configuration for FairPlay licenses. +type ContentKeyPolicyFairPlayConfiguration struct { + ContentKeyPolicyConfiguration + // REQUIRED; The key that must be used as FairPlay Application Secret key. + Ask []byte `json:"ask,omitempty"` + + // REQUIRED; The Base64 representation of FairPlay certificate in PKCS 12 (pfx) format (including private key). + FairPlayPfx *string `json:"fairPlayPfx,omitempty"` + + // REQUIRED; The password encrypting FairPlay certificate in PKCS 12 (pfx) format. + FairPlayPfxPassword *string `json:"fairPlayPfxPassword,omitempty"` + + // REQUIRED; The rental and lease key type. + RentalAndLeaseKeyType *ContentKeyPolicyFairPlayRentalAndLeaseKeyType `json:"rentalAndLeaseKeyType,omitempty"` + + // REQUIRED; The rental duration. Must be greater than or equal to 0. + RentalDuration *int64 `json:"rentalDuration,omitempty"` + + // Offline rental policy + OfflineRentalConfiguration *ContentKeyPolicyFairPlayOfflineRentalConfiguration `json:"offlineRentalConfiguration,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyFairPlayConfiguration. +func (c ContentKeyPolicyFairPlayConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyConfiguration.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyFairPlayConfiguration") + populateByteArray(objectMap, "ask", c.Ask, runtime.Base64StdFormat) + populate(objectMap, "fairPlayPfx", c.FairPlayPfx) + populate(objectMap, "fairPlayPfxPassword", c.FairPlayPfxPassword) + populate(objectMap, "offlineRentalConfiguration", c.OfflineRentalConfiguration) + populate(objectMap, "rentalAndLeaseKeyType", c.RentalAndLeaseKeyType) + populate(objectMap, "rentalDuration", c.RentalDuration) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyFairPlayConfiguration. +func (c *ContentKeyPolicyFairPlayConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "ask": + err = runtime.DecodeByteArray(string(val), &c.Ask, runtime.Base64StdFormat) + delete(rawMsg, key) + case "fairPlayPfx": + err = unpopulate(val, &c.FairPlayPfx) + delete(rawMsg, key) + case "fairPlayPfxPassword": + err = unpopulate(val, &c.FairPlayPfxPassword) + delete(rawMsg, key) + case "offlineRentalConfiguration": + err = unpopulate(val, &c.OfflineRentalConfiguration) + delete(rawMsg, key) + case "rentalAndLeaseKeyType": + err = unpopulate(val, &c.RentalAndLeaseKeyType) + delete(rawMsg, key) + case "rentalDuration": + err = unpopulate(val, &c.RentalDuration) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyConfiguration.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type ContentKeyPolicyFairPlayOfflineRentalConfiguration struct { + // REQUIRED; Playback duration + PlaybackDurationSeconds *int64 `json:"playbackDurationSeconds,omitempty"` + + // REQUIRED; Storage duration + StorageDurationSeconds *int64 `json:"storageDurationSeconds,omitempty"` +} + +// ContentKeyPolicyOpenRestriction - Represents an open restriction. License or key will be delivered on every request. +type ContentKeyPolicyOpenRestriction struct { + ContentKeyPolicyRestriction +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyOpenRestriction. +func (c ContentKeyPolicyOpenRestriction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestriction.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyOpenRestriction") + return json.Marshal(objectMap) +} + +// ContentKeyPolicyOption - Represents a policy option. +type ContentKeyPolicyOption struct { + // REQUIRED; The key delivery configuration. + Configuration ContentKeyPolicyConfigurationClassification `json:"configuration,omitempty"` + + // REQUIRED; The requirements that must be met to deliver keys with this configuration + Restriction ContentKeyPolicyRestrictionClassification `json:"restriction,omitempty"` + + // The Policy Option description. + Name *string `json:"name,omitempty"` + + // READ-ONLY; The legacy Policy Option ID. + PolicyOptionID *string `json:"policyOptionId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyOption. +func (c ContentKeyPolicyOption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "configuration", c.Configuration) + populate(objectMap, "name", c.Name) + populate(objectMap, "policyOptionId", c.PolicyOptionID) + populate(objectMap, "restriction", c.Restriction) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyOption. +func (c *ContentKeyPolicyOption) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "configuration": + c.Configuration, err = unmarshalContentKeyPolicyConfigurationClassification(val) + delete(rawMsg, key) + case "name": + err = unpopulate(val, &c.Name) + delete(rawMsg, key) + case "policyOptionId": + err = unpopulate(val, &c.PolicyOptionID) + delete(rawMsg, key) + case "restriction": + c.Restriction, err = unmarshalContentKeyPolicyRestrictionClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyPlayReadyConfiguration - Specifies a configuration for PlayReady licenses. +type ContentKeyPolicyPlayReadyConfiguration struct { + ContentKeyPolicyConfiguration + // REQUIRED; The PlayReady licenses. + Licenses []*ContentKeyPolicyPlayReadyLicense `json:"licenses,omitempty"` + + // The custom response data. + ResponseCustomData *string `json:"responseCustomData,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyPlayReadyConfiguration. +func (c ContentKeyPolicyPlayReadyConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyConfiguration.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyPlayReadyConfiguration") + populate(objectMap, "licenses", c.Licenses) + populate(objectMap, "responseCustomData", c.ResponseCustomData) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyPlayReadyConfiguration. +func (c *ContentKeyPolicyPlayReadyConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "licenses": + err = unpopulate(val, &c.Licenses) + delete(rawMsg, key) + case "responseCustomData": + err = unpopulate(val, &c.ResponseCustomData) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyConfiguration.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader - Specifies that the content key ID is in the PlayReady header. +type ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader struct { + ContentKeyPolicyPlayReadyContentKeyLocation +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader. +func (c ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyPlayReadyContentKeyLocation.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader") + return json.Marshal(objectMap) +} + +// ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier - Specifies that the content key ID is specified in the PlayReady configuration. +type ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier struct { + ContentKeyPolicyPlayReadyContentKeyLocation + // REQUIRED; The content key ID. + KeyID *string `json:"keyId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier. +func (c ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyPlayReadyContentKeyLocation.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier") + populate(objectMap, "keyId", c.KeyID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier. +func (c *ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "keyId": + err = unpopulate(val, &c.KeyID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyPlayReadyContentKeyLocation.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicyPlayReadyContentKeyLocationClassification provides polymorphic access to related types. +// Call the interface's GetContentKeyPolicyPlayReadyContentKeyLocation() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader, *ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier, +// - *ContentKeyPolicyPlayReadyContentKeyLocation +type ContentKeyPolicyPlayReadyContentKeyLocationClassification interface { + // GetContentKeyPolicyPlayReadyContentKeyLocation returns the ContentKeyPolicyPlayReadyContentKeyLocation content of the underlying type. + GetContentKeyPolicyPlayReadyContentKeyLocation() *ContentKeyPolicyPlayReadyContentKeyLocation +} + +// ContentKeyPolicyPlayReadyContentKeyLocation - Base class for content key ID location. A derived class must be used to represent the location. +type ContentKeyPolicyPlayReadyContentKeyLocation struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetContentKeyPolicyPlayReadyContentKeyLocation implements the ContentKeyPolicyPlayReadyContentKeyLocationClassification interface for type ContentKeyPolicyPlayReadyContentKeyLocation. +func (c *ContentKeyPolicyPlayReadyContentKeyLocation) GetContentKeyPolicyPlayReadyContentKeyLocation() *ContentKeyPolicyPlayReadyContentKeyLocation { + return c +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyPlayReadyContentKeyLocation. +func (c *ContentKeyPolicyPlayReadyContentKeyLocation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c ContentKeyPolicyPlayReadyContentKeyLocation) marshalInternal(objectMap map[string]interface{}, discValue string) { + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *ContentKeyPolicyPlayReadyContentKeyLocation) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction - Configures the Explicit Analog Television Output Restriction control bits. For further +// details see the PlayReady Compliance Rules. +type ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction struct { + // REQUIRED; Indicates whether this restriction is enforced on a Best Effort basis. + BestEffort *bool `json:"bestEffort,omitempty"` + + // REQUIRED; Configures the restriction control bits. Must be between 0 and 3 inclusive. + ConfigurationData *int32 `json:"configurationData,omitempty"` +} + +// ContentKeyPolicyPlayReadyLicense - The PlayReady license +type ContentKeyPolicyPlayReadyLicense struct { + // REQUIRED; A flag indicating whether test devices can use the license. + AllowTestDevices *bool `json:"allowTestDevices,omitempty"` + + // REQUIRED; The content key location. + ContentKeyLocation ContentKeyPolicyPlayReadyContentKeyLocationClassification `json:"contentKeyLocation,omitempty"` + + // REQUIRED; The PlayReady content type. + ContentType *ContentKeyPolicyPlayReadyContentType `json:"contentType,omitempty"` + + // REQUIRED; The license type. + LicenseType *ContentKeyPolicyPlayReadyLicenseType `json:"licenseType,omitempty"` + + // The begin date of license + BeginDate *time.Time `json:"beginDate,omitempty"` + + // The expiration date of license. + ExpirationDate *time.Time `json:"expirationDate,omitempty"` + + // The grace period of license. + GracePeriod *string `json:"gracePeriod,omitempty"` + + // The license PlayRight + PlayRight *ContentKeyPolicyPlayReadyPlayRight `json:"playRight,omitempty"` + + // The relative begin date of license. + RelativeBeginDate *string `json:"relativeBeginDate,omitempty"` + + // The relative expiration date of license. + RelativeExpirationDate *string `json:"relativeExpirationDate,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyPlayReadyLicense. +func (c ContentKeyPolicyPlayReadyLicense) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "allowTestDevices", c.AllowTestDevices) + populate(objectMap, "beginDate", (*timeRFC3339)(c.BeginDate)) + populate(objectMap, "contentKeyLocation", c.ContentKeyLocation) + populate(objectMap, "contentType", c.ContentType) + populate(objectMap, "expirationDate", (*timeRFC3339)(c.ExpirationDate)) + populate(objectMap, "gracePeriod", c.GracePeriod) + populate(objectMap, "licenseType", c.LicenseType) + populate(objectMap, "playRight", c.PlayRight) + populate(objectMap, "relativeBeginDate", c.RelativeBeginDate) + populate(objectMap, "relativeExpirationDate", c.RelativeExpirationDate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyPlayReadyLicense. +func (c *ContentKeyPolicyPlayReadyLicense) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "allowTestDevices": + err = unpopulate(val, &c.AllowTestDevices) + delete(rawMsg, key) + case "beginDate": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.BeginDate = (*time.Time)(&aux) + delete(rawMsg, key) + case "contentKeyLocation": + c.ContentKeyLocation, err = unmarshalContentKeyPolicyPlayReadyContentKeyLocationClassification(val) + delete(rawMsg, key) + case "contentType": + err = unpopulate(val, &c.ContentType) + delete(rawMsg, key) + case "expirationDate": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.ExpirationDate = (*time.Time)(&aux) + delete(rawMsg, key) + case "gracePeriod": + err = unpopulate(val, &c.GracePeriod) + delete(rawMsg, key) + case "licenseType": + err = unpopulate(val, &c.LicenseType) + delete(rawMsg, key) + case "playRight": + err = unpopulate(val, &c.PlayRight) + delete(rawMsg, key) + case "relativeBeginDate": + err = unpopulate(val, &c.RelativeBeginDate) + delete(rawMsg, key) + case "relativeExpirationDate": + err = unpopulate(val, &c.RelativeExpirationDate) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyPlayReadyPlayRight - Configures the Play Right in the PlayReady license. +type ContentKeyPolicyPlayReadyPlayRight struct { + // REQUIRED; Configures Unknown output handling settings of the license. + AllowPassingVideoContentToUnknownOutput *ContentKeyPolicyPlayReadyUnknownOutputPassingOption `json:"allowPassingVideoContentToUnknownOutput,omitempty"` + + // REQUIRED; Enables the Image Constraint For Analog Component Video Restriction in the license. + DigitalVideoOnlyContentRestriction *bool `json:"digitalVideoOnlyContentRestriction,omitempty"` + + // REQUIRED; Enables the Image Constraint For Analog Component Video Restriction in the license. + ImageConstraintForAnalogComponentVideoRestriction *bool `json:"imageConstraintForAnalogComponentVideoRestriction,omitempty"` + + // REQUIRED; Enables the Image Constraint For Analog Component Video Restriction in the license. + ImageConstraintForAnalogComputerMonitorRestriction *bool `json:"imageConstraintForAnalogComputerMonitorRestriction,omitempty"` + + // Configures Automatic Gain Control (AGC) and Color Stripe in the license. Must be between 0 and 3 inclusive. + AgcAndColorStripeRestriction *int32 `json:"agcAndColorStripeRestriction,omitempty"` + + // Specifies the output protection level for compressed digital audio. + AnalogVideoOpl *int32 `json:"analogVideoOpl,omitempty"` + + // Specifies the output protection level for compressed digital audio. + CompressedDigitalAudioOpl *int32 `json:"compressedDigitalAudioOpl,omitempty"` + + // Specifies the output protection level for compressed digital video. + CompressedDigitalVideoOpl *int32 `json:"compressedDigitalVideoOpl,omitempty"` + + // Configures the Explicit Analog Television Output Restriction in the license. Configuration data must be between 0 and 3 inclusive. + ExplicitAnalogTelevisionOutputRestriction *ContentKeyPolicyPlayReadyExplicitAnalogTelevisionRestriction `json:"explicitAnalogTelevisionOutputRestriction,omitempty"` + + // The amount of time that the license is valid after the license is first used to play content. + FirstPlayExpiration *string `json:"firstPlayExpiration,omitempty"` + + // Configures the Serial Copy Management System (SCMS) in the license. Must be between 0 and 3 inclusive. + ScmsRestriction *int32 `json:"scmsRestriction,omitempty"` + + // Specifies the output protection level for uncompressed digital audio. + UncompressedDigitalAudioOpl *int32 `json:"uncompressedDigitalAudioOpl,omitempty"` + + // Specifies the output protection level for uncompressed digital video. + UncompressedDigitalVideoOpl *int32 `json:"uncompressedDigitalVideoOpl,omitempty"` +} + +// ContentKeyPolicyProperties - The properties of the Content Key Policy. +type ContentKeyPolicyProperties struct { + // REQUIRED; The Key Policy options. + Options []*ContentKeyPolicyOption `json:"options,omitempty"` + + // A description for the Policy. + Description *string `json:"description,omitempty"` + + // READ-ONLY; The creation date of the Policy + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The last modified date of the Policy + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The legacy Policy ID. + PolicyID *string `json:"policyId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyProperties. +func (c ContentKeyPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "created", (*timeRFC3339)(c.Created)) + populate(objectMap, "description", c.Description) + populate(objectMap, "lastModified", (*timeRFC3339)(c.LastModified)) + populate(objectMap, "options", c.Options) + populate(objectMap, "policyId", c.PolicyID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyProperties. +func (c *ContentKeyPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &c.Description) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "options": + err = unpopulate(val, &c.Options) + delete(rawMsg, key) + case "policyId": + err = unpopulate(val, &c.PolicyID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyRestrictionClassification provides polymorphic access to related types. +// Call the interface's GetContentKeyPolicyRestriction() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ContentKeyPolicyOpenRestriction, *ContentKeyPolicyRestriction, *ContentKeyPolicyTokenRestriction, *ContentKeyPolicyUnknownRestriction +type ContentKeyPolicyRestrictionClassification interface { + // GetContentKeyPolicyRestriction returns the ContentKeyPolicyRestriction content of the underlying type. + GetContentKeyPolicyRestriction() *ContentKeyPolicyRestriction +} + +// ContentKeyPolicyRestriction - Base class for Content Key Policy restrictions. A derived class must be used to create a restriction. +type ContentKeyPolicyRestriction struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetContentKeyPolicyRestriction implements the ContentKeyPolicyRestrictionClassification interface for type ContentKeyPolicyRestriction. +func (c *ContentKeyPolicyRestriction) GetContentKeyPolicyRestriction() *ContentKeyPolicyRestriction { + return c +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyRestriction. +func (c *ContentKeyPolicyRestriction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c ContentKeyPolicyRestriction) marshalInternal(objectMap map[string]interface{}, discValue string) { + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *ContentKeyPolicyRestriction) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyRestrictionTokenKeyClassification provides polymorphic access to related types. +// Call the interface's GetContentKeyPolicyRestrictionTokenKey() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ContentKeyPolicyRestrictionTokenKey, *ContentKeyPolicyRsaTokenKey, *ContentKeyPolicySymmetricTokenKey, *ContentKeyPolicyX509CertificateTokenKey +type ContentKeyPolicyRestrictionTokenKeyClassification interface { + // GetContentKeyPolicyRestrictionTokenKey returns the ContentKeyPolicyRestrictionTokenKey content of the underlying type. + GetContentKeyPolicyRestrictionTokenKey() *ContentKeyPolicyRestrictionTokenKey +} + +// ContentKeyPolicyRestrictionTokenKey - Base class for Content Key Policy key for token validation. A derived class must be used to create a token key. +type ContentKeyPolicyRestrictionTokenKey struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetContentKeyPolicyRestrictionTokenKey implements the ContentKeyPolicyRestrictionTokenKeyClassification interface for type ContentKeyPolicyRestrictionTokenKey. +func (c *ContentKeyPolicyRestrictionTokenKey) GetContentKeyPolicyRestrictionTokenKey() *ContentKeyPolicyRestrictionTokenKey { + return c +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyRestrictionTokenKey. +func (c *ContentKeyPolicyRestrictionTokenKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return c.unmarshalInternal(rawMsg) +} + +func (c ContentKeyPolicyRestrictionTokenKey) marshalInternal(objectMap map[string]interface{}, discValue string) { + c.ODataType = &discValue + objectMap["@odata.type"] = c.ODataType +} + +func (c *ContentKeyPolicyRestrictionTokenKey) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &c.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ContentKeyPolicyRsaTokenKey - Specifies a RSA key for token validation +type ContentKeyPolicyRsaTokenKey struct { + ContentKeyPolicyRestrictionTokenKey + // REQUIRED; The RSA Parameter exponent + Exponent []byte `json:"exponent,omitempty"` + + // REQUIRED; The RSA Parameter modulus + Modulus []byte `json:"modulus,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyRsaTokenKey. +func (c ContentKeyPolicyRsaTokenKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestrictionTokenKey.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyRsaTokenKey") + populateByteArray(objectMap, "exponent", c.Exponent, runtime.Base64StdFormat) + populateByteArray(objectMap, "modulus", c.Modulus, runtime.Base64StdFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyRsaTokenKey. +func (c *ContentKeyPolicyRsaTokenKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "exponent": + err = runtime.DecodeByteArray(string(val), &c.Exponent, runtime.Base64StdFormat) + delete(rawMsg, key) + case "modulus": + err = runtime.DecodeByteArray(string(val), &c.Modulus, runtime.Base64StdFormat) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyRestrictionTokenKey.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicySymmetricTokenKey - Specifies a symmetric key for token validation. +type ContentKeyPolicySymmetricTokenKey struct { + ContentKeyPolicyRestrictionTokenKey + // REQUIRED; The key value of the key + KeyValue []byte `json:"keyValue,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicySymmetricTokenKey. +func (c ContentKeyPolicySymmetricTokenKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestrictionTokenKey.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicySymmetricTokenKey") + populateByteArray(objectMap, "keyValue", c.KeyValue, runtime.Base64StdFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicySymmetricTokenKey. +func (c *ContentKeyPolicySymmetricTokenKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "keyValue": + err = runtime.DecodeByteArray(string(val), &c.KeyValue, runtime.Base64StdFormat) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyRestrictionTokenKey.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicyTokenClaim - Represents a token claim. +type ContentKeyPolicyTokenClaim struct { + // Token claim type. + ClaimType *string `json:"claimType,omitempty"` + + // Token claim value. + ClaimValue *string `json:"claimValue,omitempty"` +} + +// ContentKeyPolicyTokenRestriction - Represents a token restriction. Provided token must match these requirements for successful license or key delivery. +type ContentKeyPolicyTokenRestriction struct { + ContentKeyPolicyRestriction + // REQUIRED; The audience for the token. + Audience *string `json:"audience,omitempty"` + + // REQUIRED; The token issuer. + Issuer *string `json:"issuer,omitempty"` + + // REQUIRED; The primary verification key. + PrimaryVerificationKey ContentKeyPolicyRestrictionTokenKeyClassification `json:"primaryVerificationKey,omitempty"` + + // REQUIRED; The type of token. + RestrictionTokenType *ContentKeyPolicyRestrictionTokenType `json:"restrictionTokenType,omitempty"` + + // A list of alternative verification keys. + AlternateVerificationKeys []ContentKeyPolicyRestrictionTokenKeyClassification `json:"alternateVerificationKeys,omitempty"` + + // The OpenID connect discovery document. + OpenIDConnectDiscoveryDocument *string `json:"openIdConnectDiscoveryDocument,omitempty"` + + // A list of required token claims. + RequiredClaims []*ContentKeyPolicyTokenClaim `json:"requiredClaims,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyTokenRestriction. +func (c ContentKeyPolicyTokenRestriction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestriction.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyTokenRestriction") + populate(objectMap, "alternateVerificationKeys", c.AlternateVerificationKeys) + populate(objectMap, "audience", c.Audience) + populate(objectMap, "issuer", c.Issuer) + populate(objectMap, "openIdConnectDiscoveryDocument", c.OpenIDConnectDiscoveryDocument) + populate(objectMap, "primaryVerificationKey", c.PrimaryVerificationKey) + populate(objectMap, "requiredClaims", c.RequiredClaims) + populate(objectMap, "restrictionTokenType", c.RestrictionTokenType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyTokenRestriction. +func (c *ContentKeyPolicyTokenRestriction) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "alternateVerificationKeys": + c.AlternateVerificationKeys, err = unmarshalContentKeyPolicyRestrictionTokenKeyClassificationArray(val) + delete(rawMsg, key) + case "audience": + err = unpopulate(val, &c.Audience) + delete(rawMsg, key) + case "issuer": + err = unpopulate(val, &c.Issuer) + delete(rawMsg, key) + case "openIdConnectDiscoveryDocument": + err = unpopulate(val, &c.OpenIDConnectDiscoveryDocument) + delete(rawMsg, key) + case "primaryVerificationKey": + c.PrimaryVerificationKey, err = unmarshalContentKeyPolicyRestrictionTokenKeyClassification(val) + delete(rawMsg, key) + case "requiredClaims": + err = unpopulate(val, &c.RequiredClaims) + delete(rawMsg, key) + case "restrictionTokenType": + err = unpopulate(val, &c.RestrictionTokenType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyRestriction.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicyUnknownConfiguration - Represents a ContentKeyPolicyConfiguration that is unavailable in the current API version. +type ContentKeyPolicyUnknownConfiguration struct { + ContentKeyPolicyConfiguration +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyUnknownConfiguration. +func (c ContentKeyPolicyUnknownConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyConfiguration.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyUnknownConfiguration") + return json.Marshal(objectMap) +} + +// ContentKeyPolicyUnknownRestriction - Represents a ContentKeyPolicyRestriction that is unavailable in the current API version. +type ContentKeyPolicyUnknownRestriction struct { + ContentKeyPolicyRestriction +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyUnknownRestriction. +func (c ContentKeyPolicyUnknownRestriction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestriction.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyUnknownRestriction") + return json.Marshal(objectMap) +} + +// ContentKeyPolicyWidevineConfiguration - Specifies a configuration for Widevine licenses. +type ContentKeyPolicyWidevineConfiguration struct { + ContentKeyPolicyConfiguration + // REQUIRED; The Widevine template. + WidevineTemplate *string `json:"widevineTemplate,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyWidevineConfiguration. +func (c ContentKeyPolicyWidevineConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyConfiguration.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyWidevineConfiguration") + populate(objectMap, "widevineTemplate", c.WidevineTemplate) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyWidevineConfiguration. +func (c *ContentKeyPolicyWidevineConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "widevineTemplate": + err = unpopulate(val, &c.WidevineTemplate) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyConfiguration.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ContentKeyPolicyX509CertificateTokenKey - Specifies a certificate for token validation. +type ContentKeyPolicyX509CertificateTokenKey struct { + ContentKeyPolicyRestrictionTokenKey + // REQUIRED; The raw data field of a certificate in PKCS 12 format (X509Certificate2 in .NET) + RawBody []byte `json:"rawBody,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ContentKeyPolicyX509CertificateTokenKey. +func (c ContentKeyPolicyX509CertificateTokenKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.ContentKeyPolicyRestrictionTokenKey.marshalInternal(objectMap, "#Microsoft.Media.ContentKeyPolicyX509CertificateTokenKey") + populateByteArray(objectMap, "rawBody", c.RawBody, runtime.Base64StdFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ContentKeyPolicyX509CertificateTokenKey. +func (c *ContentKeyPolicyX509CertificateTokenKey) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "rawBody": + err = runtime.DecodeByteArray(string(val), &c.RawBody, runtime.Base64StdFormat) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.ContentKeyPolicyRestrictionTokenKey.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// CopyAudio - A codec flag, which tells the encoder to copy the input audio bitstream. +type CopyAudio struct { + Codec +} + +// MarshalJSON implements the json.Marshaller interface for type CopyAudio. +func (c CopyAudio) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.Codec.marshalInternal(objectMap, "#Microsoft.Media.CopyAudio") + return json.Marshal(objectMap) +} + +// CopyVideo - A codec flag, which tells the encoder to copy the input video bitstream without re-encoding. +type CopyVideo struct { + Codec +} + +// MarshalJSON implements the json.Marshaller interface for type CopyVideo. +func (c CopyVideo) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.Codec.marshalInternal(objectMap, "#Microsoft.Media.CopyVideo") + return json.Marshal(objectMap) +} + +// CrossSiteAccessPolicies - The client access policy. +type CrossSiteAccessPolicies struct { + // The content of clientaccesspolicy.xml used by Silverlight. + ClientAccessPolicy *string `json:"clientAccessPolicy,omitempty"` + + // The content of crossdomain.xml used by Silverlight. + CrossDomainPolicy *string `json:"crossDomainPolicy,omitempty"` +} + +// DefaultKey - Class to specify properties of default content key for each encryption scheme +type DefaultKey struct { + // Label can be used to specify Content Key when creating a Streaming Locator + Label *string `json:"label,omitempty"` + + // Policy used by Default Key + PolicyName *string `json:"policyName,omitempty"` +} + +// Deinterlace - Describes the de-interlacing settings. +type Deinterlace struct { + // The deinterlacing mode. Defaults to AutoPixelAdaptive. + Mode *DeinterlaceMode `json:"mode,omitempty"` + + // The field parity for de-interlacing, defaults to Auto. + Parity *DeinterlaceParity `json:"parity,omitempty"` +} + +type EdgePolicies struct { + UsageDataCollectionPolicy *EdgeUsageDataCollectionPolicy `json:"usageDataCollectionPolicy,omitempty"` +} + +type EdgeUsageDataCollectionPolicy struct { + // Usage data collection frequency in ISO 8601 duration format e.g. PT10M , PT5H. + DataCollectionFrequency *string `json:"dataCollectionFrequency,omitempty"` + + // Usage data reporting frequency in ISO 8601 duration format e.g. PT10M , PT5H. + DataReportingFrequency *string `json:"dataReportingFrequency,omitempty"` + + // Details of Event Hub where the usage will be reported. + EventHubDetails *EdgeUsageDataEventHub `json:"eventHubDetails,omitempty"` + + // Maximum time for which the functionality of the device will not be hampered for not reporting the usage data. + MaxAllowedUnreportedUsageDuration *string `json:"maxAllowedUnreportedUsageDuration,omitempty"` +} + +type EdgeUsageDataEventHub struct { + // Name of the Event Hub where usage will be reported. + Name *string `json:"name,omitempty"` + + // Namespace of the Event Hub where usage will be reported. + Namespace *string `json:"namespace,omitempty"` + + // SAS token needed to interact with Event Hub. + Token *string `json:"token,omitempty"` +} + +// EnabledProtocols - Class to specify which protocols are enabled +type EnabledProtocols struct { + // REQUIRED; Enable DASH protocol or not + Dash *bool `json:"dash,omitempty"` + + // REQUIRED; Enable Download protocol or not + Download *bool `json:"download,omitempty"` + + // REQUIRED; Enable HLS protocol or not + Hls *bool `json:"hls,omitempty"` + + // REQUIRED; Enable SmoothStreaming protocol or not + SmoothStreaming *bool `json:"smoothStreaming,omitempty"` +} + +// EntityNameAvailabilityCheckOutput - The response from the check name availability request. +type EntityNameAvailabilityCheckOutput struct { + // REQUIRED; Specifies if the name is available. + NameAvailable *bool `json:"nameAvailable,omitempty"` + + // Specifies the detailed reason if the name is not available. + Message *string `json:"message,omitempty"` + + // Specifies the reason if the name is not available. + Reason *string `json:"reason,omitempty"` +} + +// EnvelopeEncryption - Class for EnvelopeEncryption encryption scheme +type EnvelopeEncryption struct { + // Representing which tracks should not be encrypted + ClearTracks []*TrackSelection `json:"clearTracks,omitempty"` + + // Representing default content key for each encryption scheme and separate content keys for specific tracks + ContentKeys *StreamingPolicyContentKeys `json:"contentKeys,omitempty"` + + // Template for the URL of the custom service delivering keys to end user players. Not required when using Azure Media Services for issuing keys. The template + // supports replaceable tokens that the service + // will update at runtime with the value specific to the request. The currently supported token values are {AlternativeMediaId}, which is replaced with + // the value of StreamingLocatorId.AlternativeMediaId, + // and {ContentKeyId}, which is replaced with the value of identifier of the key being requested. + CustomKeyAcquisitionURLTemplate *string `json:"customKeyAcquisitionUrlTemplate,omitempty"` + + // Representing supported protocols + EnabledProtocols *EnabledProtocols `json:"enabledProtocols,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EnvelopeEncryption. +func (e EnvelopeEncryption) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "clearTracks", e.ClearTracks) + populate(objectMap, "contentKeys", e.ContentKeys) + populate(objectMap, "customKeyAcquisitionUrlTemplate", e.CustomKeyAcquisitionURLTemplate) + populate(objectMap, "enabledProtocols", e.EnabledProtocols) + return json.Marshal(objectMap) +} + +// ErrorAdditionalInfo - The resource management error additional info. +type ErrorAdditionalInfo struct { + // READ-ONLY; The additional info. + Info map[string]interface{} `json:"info,omitempty" azure:"ro"` + + // READ-ONLY; The additional info type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ErrorDetail - The error detail. +type ErrorDetail struct { + // READ-ONLY; The error additional info. + AdditionalInfo []*ErrorAdditionalInfo `json:"additionalInfo,omitempty" azure:"ro"` + + // READ-ONLY; The error code. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; The error details. + Details []*ErrorDetail `json:"details,omitempty" azure:"ro"` + + // READ-ONLY; The error message. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The error target. + Target *string `json:"target,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorDetail. +func (e ErrorDetail) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "additionalInfo", e.AdditionalInfo) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponse - Common error response for all Azure Resource Manager APIs to return error details for failed operations. (This also follows the OData +// error response format.). +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // The error object. + InnerError *ErrorDetail `json:"error,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// FaceDetectorPreset - Describes all the settings to be used when analyzing a video in order to detect (and optionally redact) all the faces present. +type FaceDetectorPreset struct { + Preset + // Blur type + BlurType *BlurType `json:"blurType,omitempty"` + + // Dictionary containing key value pairs for parameters not exposed in the preset itself + ExperimentalOptions map[string]*string `json:"experimentalOptions,omitempty"` + + // This mode provides the ability to choose between the following settings: 1) Analyze - For detection only.This mode generates a metadata JSON file marking + // appearances of faces throughout the + // video.Where possible, appearances of the same person are assigned the same ID. 2) Combined - Additionally redacts(blurs) detected faces. 3) Redact - + // This enables a 2-pass process, allowing for + // selective redaction of a subset of detected faces.It takes in the metadata file from a prior analyze pass, along with the source video, and a user-selected + // subset of IDs that require redaction. + Mode *FaceRedactorMode `json:"mode,omitempty"` + + // 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. + Resolution *AnalysisResolution `json:"resolution,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type FaceDetectorPreset. +func (f FaceDetectorPreset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + f.Preset.marshalInternal(objectMap, "#Microsoft.Media.FaceDetectorPreset") + populate(objectMap, "blurType", f.BlurType) + populate(objectMap, "experimentalOptions", f.ExperimentalOptions) + populate(objectMap, "mode", f.Mode) + populate(objectMap, "resolution", f.Resolution) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FaceDetectorPreset. +func (f *FaceDetectorPreset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "blurType": + err = unpopulate(val, &f.BlurType) + delete(rawMsg, key) + case "experimentalOptions": + err = unpopulate(val, &f.ExperimentalOptions) + delete(rawMsg, key) + case "mode": + err = unpopulate(val, &f.Mode) + delete(rawMsg, key) + case "resolution": + err = unpopulate(val, &f.Resolution) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := f.Preset.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// FilterTrackPropertyCondition - The class to specify one track property condition. +type FilterTrackPropertyCondition struct { + // REQUIRED; The track property condition operation. + Operation *FilterTrackPropertyCompareOperation `json:"operation,omitempty"` + + // REQUIRED; The track property type. + Property *FilterTrackPropertyType `json:"property,omitempty"` + + // REQUIRED; The track property value. + Value *string `json:"value,omitempty"` +} + +// FilterTrackSelection - Representing a list of FilterTrackPropertyConditions to select a track. The filters are combined using a logical AND operation. +type FilterTrackSelection struct { + // REQUIRED; The track selections. + TrackSelections []*FilterTrackPropertyCondition `json:"trackSelections,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type FilterTrackSelection. +func (f FilterTrackSelection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "trackSelections", f.TrackSelections) + return json.Marshal(objectMap) +} + +// Filters - Describes all the filtering operations, such as de-interlacing, rotation etc. that are to be applied to the input media before encoding. +type Filters struct { + // The parameters for the rectangular window with which to crop the input video. + Crop *Rectangle `json:"crop,omitempty"` + + // The de-interlacing settings. + Deinterlace *Deinterlace `json:"deinterlace,omitempty"` + + // The properties of overlays to be applied to the input video. These could be audio, image or video overlays. + Overlays []OverlayClassification `json:"overlays,omitempty"` + + // The rotation, if any, to be applied to the input video, before it is encoded. Default is Auto + Rotation *Rotation `json:"rotation,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Filters. +func (f Filters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "crop", f.Crop) + populate(objectMap, "deinterlace", f.Deinterlace) + populate(objectMap, "overlays", f.Overlays) + populate(objectMap, "rotation", f.Rotation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Filters. +func (f *Filters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "crop": + err = unpopulate(val, &f.Crop) + delete(rawMsg, key) + case "deinterlace": + err = unpopulate(val, &f.Deinterlace) + delete(rawMsg, key) + case "overlays": + f.Overlays, err = unmarshalOverlayClassificationArray(val) + delete(rawMsg, key) + case "rotation": + err = unpopulate(val, &f.Rotation) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// FirstQuality - Filter First Quality +type FirstQuality struct { + // REQUIRED; The first quality bitrate. + Bitrate *int32 `json:"bitrate,omitempty"` +} + +// FormatClassification provides polymorphic access to related types. +// Call the interface's GetFormat() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Format, *ImageFormat, *JpgFormat, *Mp4Format, *MultiBitrateFormat, *PngFormat, *TransportStreamFormat +type FormatClassification interface { + // GetFormat returns the Format content of the underlying type. + GetFormat() *Format +} + +// Format - Base class for output. +type Format struct { + // REQUIRED; The pattern of the file names for the generated output files. The following macros are supported in the file name: {Basename} - An expansion + // macro that will use the name of the input video file. If + // the base name(the file suffix is not included) of the input video file is less than 32 characters long, the base name of input video files will be used. + // If the length of base name of the input video + // file exceeds 32 characters, the base name is truncated to the first 32 characters in total length. {Extension} - The appropriate extension for this format. + // {Label} - The label assigned to the + // codec/layer. {Index} - A unique index for thumbnails. Only applicable to thumbnails. {Bitrate} - The audio/video bitrate. Not applicable to thumbnails. + // {Codec} - The type of the audio/video codec. + // {Resolution} - The video resolution. Any unsubstituted macros will be collapsed and removed from the filename. + FilenamePattern *string `json:"filenamePattern,omitempty"` + + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetFormat implements the FormatClassification interface for type Format. +func (f *Format) GetFormat() *Format { return f } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Format. +func (f *Format) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return f.unmarshalInternal(rawMsg) +} + +func (f Format) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "filenamePattern", f.FilenamePattern) + f.ODataType = &discValue + objectMap["@odata.type"] = f.ODataType +} + +func (f *Format) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "filenamePattern": + err = unpopulate(val, &f.FilenamePattern) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &f.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// FromAllInputFile - An InputDefinition that looks across all of the files provided to select tracks specified by the IncludedTracks property. Generally +// used with the AudioTrackByAttribute and VideoTrackByAttribute to +// allow selection of a single track across a set of input files. +type FromAllInputFile struct { + InputDefinition +} + +// MarshalJSON implements the json.Marshaller interface for type FromAllInputFile. +func (f FromAllInputFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + f.InputDefinition.marshalInternal(objectMap, "#Microsoft.Media.FromAllInputFile") + return json.Marshal(objectMap) +} + +// FromEachInputFile - An InputDefinition that looks at each input file provided to select tracks specified by the IncludedTracks property. Generally used +// with the AudioTrackByAttribute and VideoTrackByAttribute to select +// tracks from each file given. +type FromEachInputFile struct { + InputDefinition +} + +// MarshalJSON implements the json.Marshaller interface for type FromEachInputFile. +func (f FromEachInputFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + f.InputDefinition.marshalInternal(objectMap, "#Microsoft.Media.FromEachInputFile") + return json.Marshal(objectMap) +} + +// H264Layer - Describes the settings to be used when encoding the input video into a desired output bitrate layer with the H.264 video codec. +type H264Layer struct { + VideoLayer + // The VBV buffer window length. The value should be in ISO 8601 format. The value should be in the range [0.1-100] seconds. The default is 5 seconds (for + // example, PT5S). + BufferWindow *string `json:"bufferWindow,omitempty"` + + // The entropy mode to be used for this layer. If not specified, the encoder chooses the mode that is appropriate for the profile and level. + EntropyMode *EntropyMode `json:"entropyMode,omitempty"` + + // We currently support Level up to 6.2. The value can be Auto, or a number that matches the H.264 profile. If not specified, the default is Auto, which + // lets the encoder choose the Level that is + // appropriate for this layer. + Level *string `json:"level,omitempty"` + + // We currently support Baseline, Main, High, High422, High444. Default is Auto. + Profile *H264VideoProfile `json:"profile,omitempty"` + + // The number of reference frames to be used when encoding this layer. If not specified, the encoder determines an appropriate number based on the encoder + // complexity setting. + ReferenceFrames *int32 `json:"referenceFrames,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type H264Layer. +func (h H264Layer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.VideoLayer.marshalInternal(objectMap, "#Microsoft.Media.H264Layer") + populate(objectMap, "bufferWindow", h.BufferWindow) + populate(objectMap, "entropyMode", h.EntropyMode) + populate(objectMap, "level", h.Level) + populate(objectMap, "profile", h.Profile) + populate(objectMap, "referenceFrames", h.ReferenceFrames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type H264Layer. +func (h *H264Layer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bufferWindow": + err = unpopulate(val, &h.BufferWindow) + delete(rawMsg, key) + case "entropyMode": + err = unpopulate(val, &h.EntropyMode) + delete(rawMsg, key) + case "level": + err = unpopulate(val, &h.Level) + delete(rawMsg, key) + case "profile": + err = unpopulate(val, &h.Profile) + delete(rawMsg, key) + case "referenceFrames": + err = unpopulate(val, &h.ReferenceFrames) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := h.VideoLayer.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// H264Video - Describes all the properties for encoding a video with the H.264 codec. +type H264Video struct { + Video + // Tells the encoder how to choose its encoding settings. The default value is Balanced. + Complexity *H264Complexity `json:"complexity,omitempty"` + + // The collection of output H.264 layers to be produced by the encoder. + Layers []*H264Layer `json:"layers,omitempty"` + + // Whether or not the encoder should insert key frames at scene changes. If not specified, the default is false. This flag should be set to true only when + // the encoder is being configured to produce a + // single output video. + SceneChangeDetection *bool `json:"sceneChangeDetection,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type H264Video. +func (h H264Video) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.Video.marshalInternal(objectMap, "#Microsoft.Media.H264Video") + populate(objectMap, "complexity", h.Complexity) + populate(objectMap, "layers", h.Layers) + populate(objectMap, "sceneChangeDetection", h.SceneChangeDetection) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type H264Video. +func (h *H264Video) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "complexity": + err = unpopulate(val, &h.Complexity) + delete(rawMsg, key) + case "layers": + err = unpopulate(val, &h.Layers) + delete(rawMsg, key) + case "sceneChangeDetection": + err = unpopulate(val, &h.SceneChangeDetection) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := h.Video.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// H265Layer - Describes the settings to be used when encoding the input video into a desired output bitrate layer with the H.265 video codec. +type H265Layer struct { + H265VideoLayer + // The VBV buffer window length. The value should be in ISO 8601 format. The value should be in the range [0.1-100] seconds. The default is 5 seconds (for + // example, PT5S). + BufferWindow *string `json:"bufferWindow,omitempty"` + + // We currently support Level up to 6.2. The value can be Auto, or a number that matches the H.265 profile. If not specified, the default is Auto, which + // lets the encoder choose the Level that is + // appropriate for this layer. + Level *string `json:"level,omitempty"` + + // We currently support Main. Default is Auto. + Profile *H265VideoProfile `json:"profile,omitempty"` + + // The number of reference frames to be used when encoding this layer. If not specified, the encoder determines an appropriate number based on the encoder + // complexity setting. + ReferenceFrames *int32 `json:"referenceFrames,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type H265Layer. +func (h H265Layer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.H265VideoLayer.marshalInternal(objectMap, "#Microsoft.Media.H265Layer") + populate(objectMap, "bufferWindow", h.BufferWindow) + populate(objectMap, "level", h.Level) + populate(objectMap, "profile", h.Profile) + populate(objectMap, "referenceFrames", h.ReferenceFrames) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type H265Layer. +func (h *H265Layer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bufferWindow": + err = unpopulate(val, &h.BufferWindow) + delete(rawMsg, key) + case "level": + err = unpopulate(val, &h.Level) + delete(rawMsg, key) + case "profile": + err = unpopulate(val, &h.Profile) + delete(rawMsg, key) + case "referenceFrames": + err = unpopulate(val, &h.ReferenceFrames) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := h.H265VideoLayer.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// H265Video - Describes all the properties for encoding a video with the H.265 codec. +type H265Video struct { + Video + // Tells the encoder how to choose its encoding settings. Quality will provide for a higher compression ratio but at a higher cost and longer compute time. + // Speed will produce a relatively larger file but + // is faster and more economical. The default value is Balanced. + Complexity *H265Complexity `json:"complexity,omitempty"` + + // The collection of output H.265 layers to be produced by the encoder. + Layers []*H265Layer `json:"layers,omitempty"` + + // Specifies whether or not the encoder should insert key frames at scene changes. If not specified, the default is false. This flag should be set to true + // only when the encoder is being configured to + // produce a single output video. + SceneChangeDetection *bool `json:"sceneChangeDetection,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type H265Video. +func (h H265Video) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.Video.marshalInternal(objectMap, "#Microsoft.Media.H265Video") + populate(objectMap, "complexity", h.Complexity) + populate(objectMap, "layers", h.Layers) + populate(objectMap, "sceneChangeDetection", h.SceneChangeDetection) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type H265Video. +func (h *H265Video) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "complexity": + err = unpopulate(val, &h.Complexity) + delete(rawMsg, key) + case "layers": + err = unpopulate(val, &h.Layers) + delete(rawMsg, key) + case "sceneChangeDetection": + err = unpopulate(val, &h.SceneChangeDetection) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := h.Video.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// H265VideoLayerClassification provides polymorphic access to related types. +// Call the interface's GetH265VideoLayer() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *H265Layer, *H265VideoLayer +type H265VideoLayerClassification interface { + LayerClassification + // GetH265VideoLayer returns the H265VideoLayer content of the underlying type. + GetH265VideoLayer() *H265VideoLayer +} + +// H265VideoLayer - Describes the settings to be used when encoding the input video into a desired output bitrate layer. +type H265VideoLayer struct { + Layer + // REQUIRED; The average bitrate in bits per second at which to encode the input video when generating this layer. For example: a target bitrate of 3000Kbps + // or 3Mbps means this value should be 3000000 This is a + // required field. + Bitrate *int32 `json:"bitrate,omitempty"` + + // Specifies whether or not adaptive B-frames are to be used when encoding this layer. If not specified, the encoder will turn it on whenever the video + // profile permits its use. + AdaptiveBFrame *bool `json:"adaptiveBFrame,omitempty"` + + // The number of B-frames to be used when encoding this layer. If not specified, the encoder chooses an appropriate number based on the video profile and + // level. + BFrames *int32 `json:"bFrames,omitempty"` + + // The frame rate (in frames per second) at which to encode this layer. The value can be in the form of M/N where M and N are integers (For example, 30000/1001), + // or in the form of a number (For example, + // 30, or 29.97). The encoder enforces constraints on allowed frame rates based on the profile and level. If it is not specified, the encoder will use the + // same frame rate as the input video. + FrameRate *string `json:"frameRate,omitempty"` + + // The maximum bitrate (in bits per second), at which the VBV buffer should be assumed to refill. If not specified, defaults to the same value as bitrate. + MaxBitrate *int32 `json:"maxBitrate,omitempty"` + + // The number of slices to be used when encoding this layer. If not specified, default is zero, which means that encoder will use a single slice for each + // frame. + Slices *int32 `json:"slices,omitempty"` +} + +// GetH265VideoLayer implements the H265VideoLayerClassification interface for type H265VideoLayer. +func (h *H265VideoLayer) GetH265VideoLayer() *H265VideoLayer { return h } + +// MarshalJSON implements the json.Marshaller interface for type H265VideoLayer. +func (h H265VideoLayer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.marshalInternal(objectMap, "#Microsoft.Media.H265VideoLayer") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type H265VideoLayer. +func (h *H265VideoLayer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return h.unmarshalInternal(rawMsg) +} + +func (h H265VideoLayer) marshalInternal(objectMap map[string]interface{}, discValue string) { + h.Layer.marshalInternal(objectMap, discValue) + populate(objectMap, "adaptiveBFrame", h.AdaptiveBFrame) + populate(objectMap, "bFrames", h.BFrames) + populate(objectMap, "bitrate", h.Bitrate) + populate(objectMap, "frameRate", h.FrameRate) + populate(objectMap, "maxBitrate", h.MaxBitrate) + populate(objectMap, "slices", h.Slices) +} + +func (h *H265VideoLayer) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "adaptiveBFrame": + err = unpopulate(val, &h.AdaptiveBFrame) + delete(rawMsg, key) + case "bFrames": + err = unpopulate(val, &h.BFrames) + delete(rawMsg, key) + case "bitrate": + err = unpopulate(val, &h.Bitrate) + delete(rawMsg, key) + case "frameRate": + err = unpopulate(val, &h.FrameRate) + delete(rawMsg, key) + case "maxBitrate": + err = unpopulate(val, &h.MaxBitrate) + delete(rawMsg, key) + case "slices": + err = unpopulate(val, &h.Slices) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := h.Layer.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// Hls - HTTP Live Streaming (HLS) packing setting for the live output. +type Hls struct { + // The number of fragments in an HTTP Live Streaming (HLS) TS segment in the output of the live event. This value does not affect the packing ratio for + // HLS CMAF output. + FragmentsPerTsSegment *int32 `json:"fragmentsPerTsSegment,omitempty"` +} + +// IPAccessControl - The IP access control. +type IPAccessControl struct { + // The IP allow list. + Allow []*IPRange `json:"allow,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type IPAccessControl. +func (i IPAccessControl) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "allow", i.Allow) + return json.Marshal(objectMap) +} + +// IPRange - The IP address range in the CIDR scheme. +type IPRange struct { + // The IP address. + Address *string `json:"address,omitempty"` + + // The friendly name for the IP address range. + Name *string `json:"name,omitempty"` + + // The subnet mask prefix length (see CIDR notation). + SubnetPrefixLength *int32 `json:"subnetPrefixLength,omitempty"` +} + +// ImageClassification provides polymorphic access to related types. +// Call the interface's GetImage() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Image, *JpgImage, *PngImage +type ImageClassification interface { + VideoClassification + // GetImage returns the Image content of the underlying type. + GetImage() *Image +} + +// Image - Describes the basic properties for generating thumbnails from the input video +type Image struct { + Video + // REQUIRED; The position in the input video from where to start generating thumbnails. The value can be in ISO 8601 format (For example, PT05S to start + // at 5 seconds), or a frame count (For example, 10 to start at + // the 10th frame), or a relative value to stream duration (For example, 10% to start at 10% of stream duration). Also supports a macro {Best}, which tells + // the encoder to select the best thumbnail from + // the first few seconds of the video and will only produce one thumbnail, no matter what other settings are for Step and Range. The default value is macro + // {Best}. + Start *string `json:"start,omitempty"` + + // The position relative to transform preset start time in the input video at which to stop generating thumbnails. The value can be in ISO 8601 format (For + // example, PT5M30S to stop at 5 minutes and 30 + // seconds from start time), or a frame count (For example, 300 to stop at the 300th frame from the frame at start time. If this value is 1, it means only + // producing one thumbnail at start time), or a + // relative value to the stream duration (For example, 50% to stop at half of stream duration from start time). The default value is 100%, which means to + // stop at the end of the stream. + Range *string `json:"range,omitempty"` + + // The intervals at which thumbnails are generated. The value can be in ISO 8601 format (For example, PT05S for one image every 5 seconds), or a frame count + // (For example, 30 for one image every 30 + // frames), or a relative value to stream duration (For example, 10% for one image every 10% of stream duration). Note: Step value will affect the first + // generated thumbnail, which may not be exactly the + // one specified at transform preset start time. This is due to the encoder, which tries to select the best thumbnail between start time and Step position + // from start time as the first output. As the + // default value is 10%, it means if stream has long duration, the first generated thumbnail might be far away from the one specified at start time. Try + // to select reasonable value for Step if the first + // thumbnail is expected close to start time, or set Range value at 1 if only one thumbnail is needed at start time. + Step *string `json:"step,omitempty"` +} + +// GetImage implements the ImageClassification interface for type Image. +func (i *Image) GetImage() *Image { return i } + +// MarshalJSON implements the json.Marshaller interface for type Image. +func (i Image) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + i.marshalInternal(objectMap, "#Microsoft.Media.Image") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Image. +func (i *Image) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return i.unmarshalInternal(rawMsg) +} + +func (i Image) marshalInternal(objectMap map[string]interface{}, discValue string) { + i.Video.marshalInternal(objectMap, discValue) + populate(objectMap, "range", i.Range) + populate(objectMap, "start", i.Start) + populate(objectMap, "step", i.Step) +} + +func (i *Image) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "range": + err = unpopulate(val, &i.Range) + delete(rawMsg, key) + case "start": + err = unpopulate(val, &i.Start) + delete(rawMsg, key) + case "step": + err = unpopulate(val, &i.Step) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := i.Video.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ImageFormatClassification provides polymorphic access to related types. +// Call the interface's GetImageFormat() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *ImageFormat, *JpgFormat, *PngFormat +type ImageFormatClassification interface { + FormatClassification + // GetImageFormat returns the ImageFormat content of the underlying type. + GetImageFormat() *ImageFormat +} + +// ImageFormat - Describes the properties for an output image file. +type ImageFormat struct { + Format +} + +// GetImageFormat implements the ImageFormatClassification interface for type ImageFormat. +func (i *ImageFormat) GetImageFormat() *ImageFormat { return i } + +// MarshalJSON implements the json.Marshaller interface for type ImageFormat. +func (i ImageFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + i.marshalInternal(objectMap, "#Microsoft.Media.ImageFormat") + return json.Marshal(objectMap) +} + +func (i ImageFormat) marshalInternal(objectMap map[string]interface{}, discValue string) { + i.Format.marshalInternal(objectMap, discValue) +} + +func (i *ImageFormat) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + if err := i.Format.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// InputDefinitionClassification provides polymorphic access to related types. +// Call the interface's GetInputDefinition() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *FromAllInputFile, *FromEachInputFile, *InputDefinition, *InputFile +type InputDefinitionClassification interface { + // GetInputDefinition returns the InputDefinition content of the underlying type. + GetInputDefinition() *InputDefinition +} + +// InputDefinition - Base class for defining an input. Use sub classes of this class to specify tracks selections and related metadata. +type InputDefinition struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` + + // The list of TrackDescriptors which define the metadata and selection of tracks in the input. + IncludedTracks []TrackDescriptorClassification `json:"includedTracks,omitempty"` +} + +// GetInputDefinition implements the InputDefinitionClassification interface for type InputDefinition. +func (i *InputDefinition) GetInputDefinition() *InputDefinition { return i } + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputDefinition. +func (i *InputDefinition) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return i.unmarshalInternal(rawMsg) +} + +func (i InputDefinition) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "includedTracks", i.IncludedTracks) + i.ODataType = &discValue + objectMap["@odata.type"] = i.ODataType +} + +func (i *InputDefinition) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "includedTracks": + i.IncludedTracks, err = unmarshalTrackDescriptorClassificationArray(val) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &i.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// InputFile - An InputDefinition for a single file. TrackSelections are scoped to the file specified. +type InputFile struct { + InputDefinition + // Name of the file that this input definition applies to. + Filename *string `json:"filename,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type InputFile. +func (i InputFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + i.InputDefinition.marshalInternal(objectMap, "#Microsoft.Media.InputFile") + populate(objectMap, "filename", i.Filename) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputFile. +func (i *InputFile) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "filename": + err = unpopulate(val, &i.Filename) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := i.InputDefinition.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// Job - A Job resource type. The progress and state can be obtained by polling a Job or subscribing to events using EventGrid. +type Job struct { + ProxyResource + // The resource properties. + Properties *JobProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Job. +func (j Job) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", j.Properties) + populate(objectMap, "systemData", j.SystemData) + return json.Marshal(objectMap) +} + +// JobCollection - A collection of Job items. +type JobCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of Job items. + Value []*Job `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobCollection. +func (j JobCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", j.ODataNextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +// JobError - Details of JobOutput errors. +type JobError struct { + // READ-ONLY; Helps with categorization of errors. + Category *JobErrorCategory `json:"category,omitempty" azure:"ro"` + + // READ-ONLY; Error code describing the error. + Code *JobErrorCode `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; An array of details about specific errors that led to this reported error. + Details []*JobErrorDetail `json:"details,omitempty" azure:"ro"` + + // READ-ONLY; A human-readable language-dependent representation of the error. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; Indicates that it may be possible to retry the Job. If retry is unsuccessful, please contact Azure support via Azure Portal. + Retry *JobRetry `json:"retry,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobError. +func (j JobError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "category", j.Category) + populate(objectMap, "code", j.Code) + populate(objectMap, "details", j.Details) + populate(objectMap, "message", j.Message) + populate(objectMap, "retry", j.Retry) + return json.Marshal(objectMap) +} + +// JobErrorDetail - Details of JobOutput errors. +type JobErrorDetail struct { + // READ-ONLY; Code describing the error detail. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; A human-readable representation of the error. + Message *string `json:"message,omitempty" azure:"ro"` +} + +// JobInputClassification provides polymorphic access to related types. +// Call the interface's GetJobInput() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *JobInput, *JobInputAsset, *JobInputClip, *JobInputHttp, *JobInputSequence, *JobInputs +type JobInputClassification interface { + // GetJobInput returns the JobInput content of the underlying type. + GetJobInput() *JobInput +} + +// JobInput - Base class for inputs to a Job. +type JobInput struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetJobInput implements the JobInputClassification interface for type JobInput. +func (j *JobInput) GetJobInput() *JobInput { return j } + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInput. +func (j *JobInput) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return j.unmarshalInternal(rawMsg) +} + +func (j JobInput) marshalInternal(objectMap map[string]interface{}, discValue string) { + j.ODataType = &discValue + objectMap["@odata.type"] = j.ODataType +} + +func (j *JobInput) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &j.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// JobInputAsset - Represents an Asset for input into a Job. +type JobInputAsset struct { + JobInputClip + // REQUIRED; The name of the input Asset. + AssetName *string `json:"assetName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobInputAsset. +func (j JobInputAsset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.JobInputClip.marshalInternal(objectMap, "#Microsoft.Media.JobInputAsset") + populate(objectMap, "assetName", j.AssetName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInputAsset. +func (j *JobInputAsset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "assetName": + err = unpopulate(val, &j.AssetName) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobInputClip.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobInputClipClassification provides polymorphic access to related types. +// Call the interface's GetJobInputClip() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *JobInputAsset, *JobInputClip, *JobInputHttp +type JobInputClipClassification interface { + JobInputClassification + // GetJobInputClip returns the JobInputClip content of the underlying type. + GetJobInputClip() *JobInputClip +} + +// JobInputClip - Represents input files for a Job. +type JobInputClip struct { + JobInput + // Defines a point on the timeline of the input media at which processing will end. Defaults to the end of the input media. + End ClipTimeClassification `json:"end,omitempty"` + + // List of files. Required for JobInputHttp. Maximum of 4000 characters each. Query strings will not be returned in service responses to prevent sensitive + // data exposure. + Files []*string `json:"files,omitempty"` + + // Defines a list of InputDefinitions. For each InputDefinition, it defines a list of track selections and related metadata. + InputDefinitions []InputDefinitionClassification `json:"inputDefinitions,omitempty"` + + // A label that is assigned to a JobInputClip, that is used to satisfy a reference used in the Transform. For example, a Transform can be authored so as + // to take an image file with the label 'xyz' and + // apply it as an overlay onto the input video before it is encoded. When submitting a Job, exactly one of the JobInputs should be the image file, and it + // should have the label 'xyz'. + Label *string `json:"label,omitempty"` + + // Defines a point on the timeline of the input media at which processing will start. Defaults to the beginning of the input media. + Start ClipTimeClassification `json:"start,omitempty"` +} + +// GetJobInputClip implements the JobInputClipClassification interface for type JobInputClip. +func (j *JobInputClip) GetJobInputClip() *JobInputClip { return j } + +// MarshalJSON implements the json.Marshaller interface for type JobInputClip. +func (j JobInputClip) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.marshalInternal(objectMap, "#Microsoft.Media.JobInputClip") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInputClip. +func (j *JobInputClip) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return j.unmarshalInternal(rawMsg) +} + +func (j JobInputClip) marshalInternal(objectMap map[string]interface{}, discValue string) { + j.JobInput.marshalInternal(objectMap, discValue) + populate(objectMap, "end", j.End) + populate(objectMap, "files", j.Files) + populate(objectMap, "inputDefinitions", j.InputDefinitions) + populate(objectMap, "label", j.Label) + populate(objectMap, "start", j.Start) +} + +func (j *JobInputClip) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "end": + j.End, err = unmarshalClipTimeClassification(val) + delete(rawMsg, key) + case "files": + err = unpopulate(val, &j.Files) + delete(rawMsg, key) + case "inputDefinitions": + j.InputDefinitions, err = unmarshalInputDefinitionClassificationArray(val) + delete(rawMsg, key) + case "label": + err = unpopulate(val, &j.Label) + delete(rawMsg, key) + case "start": + j.Start, err = unmarshalClipTimeClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobInput.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobInputHTTP - Represents HTTPS job input. +type JobInputHTTP struct { + JobInputClip + // Base URI for HTTPS job input. It will be concatenated with provided file names. If no base uri is given, then the provided file list is assumed to be + // fully qualified uris. Maximum length of 4000 + // characters. The query strings will not be returned in service responses to prevent sensitive data exposure. + BaseURI *string `json:"baseUri,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobInputHTTP. +func (j JobInputHTTP) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.JobInputClip.marshalInternal(objectMap, "#Microsoft.Media.JobInputHttp") + populate(objectMap, "baseUri", j.BaseURI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInputHTTP. +func (j *JobInputHTTP) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "baseUri": + err = unpopulate(val, &j.BaseURI) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobInputClip.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobInputSequence - A Sequence contains an ordered list of Clips where each clip is a JobInput. The Sequence will be treated as a single input. +type JobInputSequence struct { + JobInput + // JobInputs that make up the timeline. + Inputs []JobInputClipClassification `json:"inputs,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobInputSequence. +func (j JobInputSequence) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.JobInput.marshalInternal(objectMap, "#Microsoft.Media.JobInputSequence") + populate(objectMap, "inputs", j.Inputs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInputSequence. +func (j *JobInputSequence) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "inputs": + j.Inputs, err = unmarshalJobInputClipClassificationArray(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobInput.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobInputs - Describes a list of inputs to a Job. +type JobInputs struct { + JobInput + // List of inputs to a Job. + Inputs []JobInputClassification `json:"inputs,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobInputs. +func (j JobInputs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.JobInput.marshalInternal(objectMap, "#Microsoft.Media.JobInputs") + populate(objectMap, "inputs", j.Inputs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobInputs. +func (j *JobInputs) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "inputs": + j.Inputs, err = unmarshalJobInputClassificationArray(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobInput.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobOutputClassification provides polymorphic access to related types. +// Call the interface's GetJobOutput() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *JobOutput, *JobOutputAsset +type JobOutputClassification interface { + // GetJobOutput returns the JobOutput content of the underlying type. + GetJobOutput() *JobOutput +} + +// JobOutput - Describes all the properties of a JobOutput. +type JobOutput struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` + + // A label that is assigned to a JobOutput in order to help uniquely identify it. This is useful when your Transform has more than one TransformOutput, + // whereby your Job has more than one JobOutput. In + // such cases, when you submit the Job, you will add two or more JobOutputs, in the same order as TransformOutputs in the Transform. Subsequently, when + // you retrieve the Job, either through events or on a + // GET request, you can use the label to easily identify the JobOutput. If a label is not provided, a default value of '{presetName}_{outputIndex}' will + // be used, where the preset name is the name of the + // preset in the corresponding TransformOutput and the output index is the relative index of the this JobOutput within the Job. Note that this index is + // the same as the relative index of the corresponding + // TransformOutput within its Transform. + Label *string `json:"label,omitempty"` + + // A preset used to override the preset in the corresponding transform output. + PresetOverride PresetClassification `json:"presetOverride,omitempty"` + + // READ-ONLY; The UTC date and time at which this Job Output finished processing. + EndTime *time.Time `json:"endTime,omitempty" azure:"ro"` + + // READ-ONLY; If the JobOutput is in the Error state, it contains the details of the error. + Error *JobError `json:"error,omitempty" azure:"ro"` + + // READ-ONLY; If the JobOutput is in a Processing state, this contains the Job completion percentage. The value is an estimate and not intended to be used + // to predict Job completion times. To determine if the + // JobOutput is complete, use the State property. + Progress *int32 `json:"progress,omitempty" azure:"ro"` + + // READ-ONLY; The UTC date and time at which this Job Output began processing. + StartTime *time.Time `json:"startTime,omitempty" azure:"ro"` + + // READ-ONLY; Describes the state of the JobOutput. + State *JobState `json:"state,omitempty" azure:"ro"` +} + +// GetJobOutput implements the JobOutputClassification interface for type JobOutput. +func (j *JobOutput) GetJobOutput() *JobOutput { return j } + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobOutput. +func (j *JobOutput) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return j.unmarshalInternal(rawMsg) +} + +func (j JobOutput) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "endTime", (*timeRFC3339)(j.EndTime)) + populate(objectMap, "error", j.Error) + populate(objectMap, "label", j.Label) + j.ODataType = &discValue + objectMap["@odata.type"] = j.ODataType + populate(objectMap, "presetOverride", j.PresetOverride) + populate(objectMap, "progress", j.Progress) + populate(objectMap, "startTime", (*timeRFC3339)(j.StartTime)) + populate(objectMap, "state", j.State) +} + +func (j *JobOutput) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "error": + err = unpopulate(val, &j.Error) + delete(rawMsg, key) + case "label": + err = unpopulate(val, &j.Label) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &j.ODataType) + delete(rawMsg, key) + case "presetOverride": + j.PresetOverride, err = unmarshalPresetClassification(val) + delete(rawMsg, key) + case "progress": + err = unpopulate(val, &j.Progress) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "state": + err = unpopulate(val, &j.State) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// JobOutputAsset - Represents an Asset used as a JobOutput. +type JobOutputAsset struct { + JobOutput + // REQUIRED; The name of the output Asset. + AssetName *string `json:"assetName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobOutputAsset. +func (j JobOutputAsset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.JobOutput.marshalInternal(objectMap, "#Microsoft.Media.JobOutputAsset") + populate(objectMap, "assetName", j.AssetName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobOutputAsset. +func (j *JobOutputAsset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "assetName": + err = unpopulate(val, &j.AssetName) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.JobOutput.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobProperties - Properties of the Job. +type JobProperties struct { + // REQUIRED; The inputs for the Job. + Input JobInputClassification `json:"input,omitempty"` + + // REQUIRED; The outputs for the Job. + Outputs []JobOutputClassification `json:"outputs,omitempty"` + + // Customer provided key, value pairs that will be returned in Job and JobOutput state events. + CorrelationData map[string]*string `json:"correlationData,omitempty"` + + // Optional customer supplied description of the Job. + Description *string `json:"description,omitempty"` + + // Priority with which the job should be processed. Higher priority jobs are processed before lower priority jobs. If not set, the default is normal. + Priority *Priority `json:"priority,omitempty"` + + // READ-ONLY; The UTC date and time when the customer has created the Job, in 'YYYY-MM-DDThh:mm:ssZ' format. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The UTC date and time at which this Job finished processing. + EndTime *time.Time `json:"endTime,omitempty" azure:"ro"` + + // READ-ONLY; The UTC date and time when the customer has last updated the Job, in 'YYYY-MM-DDThh:mm:ssZ' format. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The UTC date and time at which this Job began processing. + StartTime *time.Time `json:"startTime,omitempty" azure:"ro"` + + // READ-ONLY; The current state of the job. + State *JobState `json:"state,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobProperties. +func (j JobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "correlationData", j.CorrelationData) + populate(objectMap, "created", (*timeRFC3339)(j.Created)) + populate(objectMap, "description", j.Description) + populate(objectMap, "endTime", (*timeRFC3339)(j.EndTime)) + populate(objectMap, "input", j.Input) + populate(objectMap, "lastModified", (*timeRFC3339)(j.LastModified)) + populate(objectMap, "outputs", j.Outputs) + populate(objectMap, "priority", j.Priority) + populate(objectMap, "startTime", (*timeRFC3339)(j.StartTime)) + populate(objectMap, "state", j.State) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobProperties. +func (j *JobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationData": + err = unpopulate(val, &j.CorrelationData) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &j.Description) + delete(rawMsg, key) + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "input": + j.Input, err = unmarshalJobInputClassification(val) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "outputs": + j.Outputs, err = unmarshalJobOutputClassificationArray(val) + delete(rawMsg, key) + case "priority": + err = unpopulate(val, &j.Priority) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "state": + err = unpopulate(val, &j.State) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// JobsCancelJobOptions contains the optional parameters for the Jobs.CancelJob method. +type JobsCancelJobOptions struct { + // placeholder for future optional parameters +} + +// JobsCreateOptions contains the optional parameters for the Jobs.Create method. +type JobsCreateOptions struct { + // placeholder for future optional parameters +} + +// JobsDeleteOptions contains the optional parameters for the Jobs.Delete method. +type JobsDeleteOptions struct { + // placeholder for future optional parameters +} + +// JobsGetOptions contains the optional parameters for the Jobs.Get method. +type JobsGetOptions struct { + // placeholder for future optional parameters +} + +// JobsListOptions contains the optional parameters for the Jobs.List method. +type JobsListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string +} + +// JobsUpdateOptions contains the optional parameters for the Jobs.Update method. +type JobsUpdateOptions struct { + // placeholder for future optional parameters +} + +// JpgFormat - Describes the settings for producing JPEG thumbnails. +type JpgFormat struct { + ImageFormat +} + +// MarshalJSON implements the json.Marshaller interface for type JpgFormat. +func (j JpgFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.ImageFormat.marshalInternal(objectMap, "#Microsoft.Media.JpgFormat") + return json.Marshal(objectMap) +} + +// JpgImage - Describes the properties for producing a series of JPEG images from the input video. +type JpgImage struct { + Image + // A collection of output JPEG image layers to be produced by the encoder. + Layers []*JpgLayer `json:"layers,omitempty"` + + // Sets the number of columns used in thumbnail sprite image. The number of rows are automatically calculated and a VTT file is generated with the coordinate + // mappings for each thumbnail in the sprite. + // Note: this value should be a positive integer and a proper value is recommended so that the output image resolution will not go beyond JPEG maximum pixel + // resolution limit 65535x65535. + SpriteColumn *int32 `json:"spriteColumn,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JpgImage. +func (j JpgImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.Image.marshalInternal(objectMap, "#Microsoft.Media.JpgImage") + populate(objectMap, "layers", j.Layers) + populate(objectMap, "spriteColumn", j.SpriteColumn) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JpgImage. +func (j *JpgImage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "layers": + err = unpopulate(val, &j.Layers) + delete(rawMsg, key) + case "spriteColumn": + err = unpopulate(val, &j.SpriteColumn) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.Image.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JpgLayer - Describes the settings to produce a JPEG image from the input video. +type JpgLayer struct { + Layer + // The compression quality of the JPEG output. Range is from 0-100 and the default is 70. + Quality *int32 `json:"quality,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JpgLayer. +func (j JpgLayer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.Layer.marshalInternal(objectMap, "#Microsoft.Media.JpgLayer") + populate(objectMap, "quality", j.Quality) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JpgLayer. +func (j *JpgLayer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "quality": + err = unpopulate(val, &j.Quality) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.Layer.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type KeyDelivery struct { + // The access control properties for Key Delivery. + AccessControl *AccessControl `json:"accessControl,omitempty"` +} + +type KeyVaultProperties struct { + // The URL of the Key Vault key used to encrypt the account. The key may either be versioned (for example https://vault/keys/mykey/version1) or reference + // a key without a version (for example + // https://vault/keys/mykey). + KeyIdentifier *string `json:"keyIdentifier,omitempty"` + + // READ-ONLY; The current key used to encrypt the Media Services account, including the key version. + CurrentKeyIdentifier *string `json:"currentKeyIdentifier,omitempty" azure:"ro"` +} + +// LayerClassification provides polymorphic access to related types. +// Call the interface's GetLayer() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *H264Layer, *H265Layer, *H265VideoLayer, *JpgLayer, *Layer, *PngLayer, *VideoLayer +type LayerClassification interface { + // GetLayer returns the Layer content of the underlying type. + GetLayer() *Layer +} + +// Layer - The encoder can be configured to produce video and/or images (thumbnails) at different resolutions, by specifying a layer for each desired resolution. +// A layer represents the properties for the video +// or image at a resolution. +type Layer struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` + + // The height of the output video for this layer. The value can be absolute (in pixels) or relative (in percentage). For example 50% means the output video + // has half as many pixels in height as the input. + Height *string `json:"height,omitempty"` + + // The alphanumeric label for this layer, which can be used in multiplexing different video and audio layers, or in naming the output file. + Label *string `json:"label,omitempty"` + + // The width of the output video for this layer. The value can be absolute (in pixels) or relative (in percentage). For example 50% means the output video + // has half as many pixels in width as the input. + Width *string `json:"width,omitempty"` +} + +// GetLayer implements the LayerClassification interface for type Layer. +func (l *Layer) GetLayer() *Layer { return l } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Layer. +func (l *Layer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return l.unmarshalInternal(rawMsg) +} + +func (l Layer) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "height", l.Height) + populate(objectMap, "label", l.Label) + l.ODataType = &discValue + objectMap["@odata.type"] = l.ODataType + populate(objectMap, "width", l.Width) +} + +func (l *Layer) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "height": + err = unpopulate(val, &l.Height) + delete(rawMsg, key) + case "label": + err = unpopulate(val, &l.Label) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &l.ODataType) + delete(rawMsg, key) + case "width": + err = unpopulate(val, &l.Width) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ListContainerSasInput - The parameters to the list SAS request. +type ListContainerSasInput struct { + // The SAS URL expiration time. This must be less than 24 hours from the current time. + ExpiryTime *time.Time `json:"expiryTime,omitempty"` + + // The permissions to set on the SAS URL. + Permissions *AssetContainerPermission `json:"permissions,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListContainerSasInput. +func (l ListContainerSasInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "expiryTime", (*timeRFC3339)(l.ExpiryTime)) + populate(objectMap, "permissions", l.Permissions) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ListContainerSasInput. +func (l *ListContainerSasInput) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "expiryTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + l.ExpiryTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "permissions": + err = unpopulate(val, &l.Permissions) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ListContentKeysResponse - Class of response for listContentKeys action +type ListContentKeysResponse struct { + // ContentKeys used by current Streaming Locator + ContentKeys []*StreamingLocatorContentKey `json:"contentKeys,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListContentKeysResponse. +func (l ListContentKeysResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "contentKeys", l.ContentKeys) + return json.Marshal(objectMap) +} + +type ListEdgePoliciesInput struct { + // Unique identifier of the edge device. + DeviceID *string `json:"deviceId,omitempty"` +} + +// ListPathsResponse - Class of response for listPaths action +type ListPathsResponse struct { + // Download Paths supported by current Streaming Locator + DownloadPaths []*string `json:"downloadPaths,omitempty"` + + // Streaming Paths supported by current Streaming Locator + StreamingPaths []*StreamingPath `json:"streamingPaths,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListPathsResponse. +func (l ListPathsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "downloadPaths", l.DownloadPaths) + populate(objectMap, "streamingPaths", l.StreamingPaths) + return json.Marshal(objectMap) +} + +// ListStreamingLocatorsResponse - The Streaming Locators associated with this Asset. +type ListStreamingLocatorsResponse struct { + // READ-ONLY; The list of Streaming Locators. + StreamingLocators []*AssetStreamingLocator `json:"streamingLocators,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListStreamingLocatorsResponse. +func (l ListStreamingLocatorsResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "streamingLocators", l.StreamingLocators) + return json.Marshal(objectMap) +} + +// LiveEvent - The live event. +type LiveEvent struct { + TrackedResource + // The live event properties. + Properties *LiveEventProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEvent. +func (l LiveEvent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + l.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + return json.Marshal(objectMap) +} + +// LiveEventActionInput - The LiveEvent action input parameter definition. +type LiveEventActionInput struct { + // The flag indicates whether live outputs are automatically deleted when live event is being stopped. Deleting live outputs do not delete the underlying + // assets. + RemoveOutputsOnStop *bool `json:"removeOutputsOnStop,omitempty"` +} + +// LiveEventEncoding - Specifies the live event type and optional encoding settings for encoding live events. +type LiveEventEncoding struct { + // Live event type. When encodingType is set to PassthroughBasic or PassthroughStandard, the service simply passes through the incoming video and audio + // layer(s) to the output. When encodingType is set to + // Standard or Premium1080p, a live encoder transcodes the incoming stream into multiple bitrates or layers. See https://go.microsoft.com/fwlink/?linkid=2095101 + // for more information. This property cannot + // be modified after the live event is created. + EncodingType *LiveEventEncodingType `json:"encodingType,omitempty"` + + // Use an ISO 8601 time value between 0.5 to 20 seconds to specify the output fragment length for the video and audio tracks of an encoding live event. + // For example, use PT2S to indicate 2 seconds. For + // the video track it also defines the key frame interval, or the length of a GoP (group of pictures). If this value is not set for an encoding live event, + // the fragment duration defaults to 2 seconds. + // The value cannot be set for pass-through live events. + KeyFrameInterval *string `json:"keyFrameInterval,omitempty"` + + // The optional encoding preset name, used when encodingType is not None. This value is specified at creation time and cannot be updated. If the encodingType + // is set to Standard, then the default preset + // name is ‘Default720p’. Else if the encodingType is set to Premium1080p, the default preset is ‘Default1080p’. + PresetName *string `json:"presetName,omitempty"` + + // Specifies how the input video will be resized to fit the desired output resolution(s). Default is None + StretchMode *StretchMode `json:"stretchMode,omitempty"` +} + +// LiveEventEndpoint - The live event endpoint. +type LiveEventEndpoint struct { + // The endpoint protocol. + Protocol *string `json:"protocol,omitempty"` + + // The endpoint URL. + URL *string `json:"url,omitempty"` +} + +// LiveEventInput - The live event input. +type LiveEventInput struct { + // REQUIRED; The input protocol for the live event. This is specified at creation time and cannot be updated. + StreamingProtocol *LiveEventInputProtocol `json:"streamingProtocol,omitempty"` + + // Access control for live event input. + AccessControl *LiveEventInputAccessControl `json:"accessControl,omitempty"` + + // A UUID in string form to uniquely identify the stream. This can be specified at creation time but cannot be updated. If omitted, the service will generate + // a unique value. + AccessToken *string `json:"accessToken,omitempty"` + + // The input endpoints for the live event. + Endpoints []*LiveEventEndpoint `json:"endpoints,omitempty"` + + // ISO 8601 time duration of the key frame interval duration of the input. This value sets the EXT-X-TARGETDURATION property in the HLS output. For example, + // use PT2S to indicate 2 seconds. Leave the + // value empty for encoding live events. + KeyFrameIntervalDuration *string `json:"keyFrameIntervalDuration,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEventInput. +func (l LiveEventInput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "accessControl", l.AccessControl) + populate(objectMap, "accessToken", l.AccessToken) + populate(objectMap, "endpoints", l.Endpoints) + populate(objectMap, "keyFrameIntervalDuration", l.KeyFrameIntervalDuration) + populate(objectMap, "streamingProtocol", l.StreamingProtocol) + return json.Marshal(objectMap) +} + +// LiveEventInputAccessControl - The IP access control for live event input. +type LiveEventInputAccessControl struct { + // The IP access control properties. + IP *IPAccessControl `json:"ip,omitempty"` +} + +// LiveEventInputTrackSelection - A track selection condition. This property is reserved for future use, any value set on this property will be ignored. +type LiveEventInputTrackSelection struct { + // Comparing operation. This property is reserved for future use, any value set on this property will be ignored. + Operation *string `json:"operation,omitempty"` + + // Property name to select. This property is reserved for future use, any value set on this property will be ignored. + Property *string `json:"property,omitempty"` + + // Property value to select. This property is reserved for future use, any value set on this property will be ignored. + Value *string `json:"value,omitempty"` +} + +// LiveEventListResult - The LiveEvent list result. +type LiveEventListResult struct { + // The number of result. + ODataCount *int32 `json:"@odata.count,omitempty"` + + // The link to the next set of results. Not empty if value contains incomplete list of live outputs. + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // The result of the List Live Event operation. + Value []*LiveEvent `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEventListResult. +func (l LiveEventListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.count", l.ODataCount) + populate(objectMap, "@odata.nextLink", l.ODataNextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// LiveEventOutputTranscriptionTrack - Describes a transcription track in the output of a live event, generated using speech-to-text transcription. This +// property is reserved for future use, any value set on this property will be ignored. +type LiveEventOutputTranscriptionTrack struct { + // REQUIRED; The output track name. This property is reserved for future use, any value set on this property will be ignored. + TrackName *string `json:"trackName,omitempty"` +} + +// LiveEventPreview - Live event preview settings. +type LiveEventPreview struct { + // The access control for live event preview. + AccessControl *LiveEventPreviewAccessControl `json:"accessControl,omitempty"` + + // An alternative media identifier associated with the streaming locator created for the preview. This value is specified at creation time and cannot be + // updated. The identifier can be used in the + // CustomLicenseAcquisitionUrlTemplate or the CustomKeyAcquisitionUrlTemplate of the StreamingPolicy specified in the StreamingPolicyName field. + AlternativeMediaID *string `json:"alternativeMediaId,omitempty"` + + // The endpoints for preview. Do not share the preview URL with the live event audience. + Endpoints []*LiveEventEndpoint `json:"endpoints,omitempty"` + + // The identifier of the preview locator in Guid format. Specifying this at creation time allows the caller to know the preview locator url before the event + // is created. If omitted, the service will + // generate a random identifier. This value cannot be updated once the live event is created. + PreviewLocator *string `json:"previewLocator,omitempty"` + + // The name of streaming policy used for the live event preview. This value is specified at creation time and cannot be updated. + StreamingPolicyName *string `json:"streamingPolicyName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEventPreview. +func (l LiveEventPreview) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "accessControl", l.AccessControl) + populate(objectMap, "alternativeMediaId", l.AlternativeMediaID) + populate(objectMap, "endpoints", l.Endpoints) + populate(objectMap, "previewLocator", l.PreviewLocator) + populate(objectMap, "streamingPolicyName", l.StreamingPolicyName) + return json.Marshal(objectMap) +} + +// LiveEventPreviewAccessControl - The IP access control for the live event preview endpoint. +type LiveEventPreviewAccessControl struct { + // The IP access control properties. + IP *IPAccessControl `json:"ip,omitempty"` +} + +// LiveEventProperties - The live event properties. +type LiveEventProperties struct { + // REQUIRED; Live event input settings. It defines how the live event receives input from a contribution encoder. + Input *LiveEventInput `json:"input,omitempty"` + + // Live event cross site access policies. + CrossSiteAccessPolicies *CrossSiteAccessPolicies `json:"crossSiteAccessPolicies,omitempty"` + + // A description for the live event. + Description *string `json:"description,omitempty"` + + // Encoding settings for the live event. It configures whether a live encoder is used for the live event and settings for the live encoder if it is used. + Encoding *LiveEventEncoding `json:"encoding,omitempty"` + + // When useStaticHostname is set to true, the hostnamePrefix specifies the first part of the hostname assigned to the live event preview and ingest endpoints. + // The final hostname would be a combination of + // this prefix, the media service account name and a short code for the Azure Media Services data center. + HostnamePrefix *string `json:"hostnamePrefix,omitempty"` + + // Live event preview settings. Preview allows live event producers to preview the live streaming content without creating any live output. + Preview *LiveEventPreview `json:"preview,omitempty"` + + // The options to use for the LiveEvent. This value is specified at creation time and cannot be updated. The valid values for the array entry values are + // 'Default' and 'LowLatency'. + StreamOptions []*StreamOptionsFlag `json:"streamOptions,omitempty"` + + // Live transcription settings for the live event. See https://go.microsoft.com/fwlink/?linkid=2133742 for more information about the live transcription + // feature. + Transcriptions []*LiveEventTranscription `json:"transcriptions,omitempty"` + + // Specifies whether a static hostname would be assigned to the live event preview and ingest endpoints. This value can only be updated if the live event + // is in Standby state + UseStaticHostname *bool `json:"useStaticHostname,omitempty"` + + // READ-ONLY; The creation time for the live event + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The last modified time of the live event. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The provisioning state of the live event. + ProvisioningState *string `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The resource state of the live event. See https://go.microsoft.com/fwlink/?linkid=2139012 for more information. + ResourceState *LiveEventResourceState `json:"resourceState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEventProperties. +func (l LiveEventProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "created", (*timeRFC3339)(l.Created)) + populate(objectMap, "crossSiteAccessPolicies", l.CrossSiteAccessPolicies) + populate(objectMap, "description", l.Description) + populate(objectMap, "encoding", l.Encoding) + populate(objectMap, "hostnamePrefix", l.HostnamePrefix) + populate(objectMap, "input", l.Input) + populate(objectMap, "lastModified", (*timeRFC3339)(l.LastModified)) + populate(objectMap, "preview", l.Preview) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "resourceState", l.ResourceState) + populate(objectMap, "streamOptions", l.StreamOptions) + populate(objectMap, "transcriptions", l.Transcriptions) + populate(objectMap, "useStaticHostname", l.UseStaticHostname) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LiveEventProperties. +func (l *LiveEventProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + l.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "crossSiteAccessPolicies": + err = unpopulate(val, &l.CrossSiteAccessPolicies) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &l.Description) + delete(rawMsg, key) + case "encoding": + err = unpopulate(val, &l.Encoding) + delete(rawMsg, key) + case "hostnamePrefix": + err = unpopulate(val, &l.HostnamePrefix) + delete(rawMsg, key) + case "input": + err = unpopulate(val, &l.Input) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + l.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "preview": + err = unpopulate(val, &l.Preview) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &l.ProvisioningState) + delete(rawMsg, key) + case "resourceState": + err = unpopulate(val, &l.ResourceState) + delete(rawMsg, key) + case "streamOptions": + err = unpopulate(val, &l.StreamOptions) + delete(rawMsg, key) + case "transcriptions": + err = unpopulate(val, &l.Transcriptions) + delete(rawMsg, key) + case "useStaticHostname": + err = unpopulate(val, &l.UseStaticHostname) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// LiveEventTranscription - Describes the transcription tracks in the output of a live event, generated using speech-to-text transcription. This property +// is reserved for future use, any value set on this property will be +// ignored. +type LiveEventTranscription struct { + // Provides a mechanism to select the audio track in the input live feed, to which speech-to-text transcription is applied. This property is reserved for + // future use, any value set on this property will + // be ignored. + InputTrackSelection []*LiveEventInputTrackSelection `json:"inputTrackSelection,omitempty"` + + // Specifies the language (locale) to be used for speech-to-text transcription – it should match the spoken language in the audio track. The value should + // be in BCP-47 format (e.g: 'en-US'). See + // https://go.microsoft.com/fwlink/?linkid=2133742 for more information about the live transcription feature and the list of supported languages. + Language *string `json:"language,omitempty"` + + // Describes a transcription track in the output of a live event, generated using speech-to-text transcription. This property is reserved for future use, + // any value set on this property will be ignored. + OutputTranscriptionTrack *LiveEventOutputTranscriptionTrack `json:"outputTranscriptionTrack,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveEventTranscription. +func (l LiveEventTranscription) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "inputTrackSelection", l.InputTrackSelection) + populate(objectMap, "language", l.Language) + populate(objectMap, "outputTranscriptionTrack", l.OutputTranscriptionTrack) + return json.Marshal(objectMap) +} + +// LiveEventsBeginAllocateOptions contains the optional parameters for the LiveEvents.BeginAllocate method. +type LiveEventsBeginAllocateOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsBeginCreateOptions contains the optional parameters for the LiveEvents.BeginCreate method. +type LiveEventsBeginCreateOptions struct { + // The flag indicates if the resource should be automatically started on creation. + AutoStart *bool +} + +// LiveEventsBeginDeleteOptions contains the optional parameters for the LiveEvents.BeginDelete method. +type LiveEventsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsBeginResetOptions contains the optional parameters for the LiveEvents.BeginReset method. +type LiveEventsBeginResetOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsBeginStartOptions contains the optional parameters for the LiveEvents.BeginStart method. +type LiveEventsBeginStartOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsBeginStopOptions contains the optional parameters for the LiveEvents.BeginStop method. +type LiveEventsBeginStopOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsBeginUpdateOptions contains the optional parameters for the LiveEvents.BeginUpdate method. +type LiveEventsBeginUpdateOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsGetOptions contains the optional parameters for the LiveEvents.Get method. +type LiveEventsGetOptions struct { + // placeholder for future optional parameters +} + +// LiveEventsListOptions contains the optional parameters for the LiveEvents.List method. +type LiveEventsListOptions struct { + // placeholder for future optional parameters +} + +// LiveOutput - The Live Output. +type LiveOutput struct { + ProxyResource + // Live output properties. + Properties *LiveOutputProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveOutput. +func (l LiveOutput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + l.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", l.Properties) + populate(objectMap, "systemData", l.SystemData) + return json.Marshal(objectMap) +} + +// LiveOutputListResult - The LiveOutput list result. +type LiveOutputListResult struct { + // The number of result. + ODataCount *int32 `json:"@odata.count,omitempty"` + + // The link to the next set of results. Not empty if value contains incomplete list of live outputs. + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // The result of the List LiveOutput operation. + Value []*LiveOutput `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveOutputListResult. +func (l LiveOutputListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.count", l.ODataCount) + populate(objectMap, "@odata.nextLink", l.ODataNextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// LiveOutputProperties - The JSON object that contains the properties required to create a live output. +type LiveOutputProperties struct { + // REQUIRED; ISO 8601 time between 1 minute to 25 hours to indicate the maximum content length that can be archived in the asset for this live output. This + // also sets the maximum content length for the rewind + // window. For example, use PT1H30M to indicate 1 hour and 30 minutes of archive window. + ArchiveWindowLength *string `json:"archiveWindowLength,omitempty"` + + // REQUIRED; The asset that the live output will write to. + AssetName *string `json:"assetName,omitempty"` + + // The description of the live output. + Description *string `json:"description,omitempty"` + + // HTTP Live Streaming (HLS) packing setting for the live output. + Hls *Hls `json:"hls,omitempty"` + + // The manifest file name. If not provided, the service will generate one automatically. + ManifestName *string `json:"manifestName,omitempty"` + + // The initial timestamp that the live output will start at, any content before this value will not be archived. + OutputSnapTime *int64 `json:"outputSnapTime,omitempty"` + + // READ-ONLY; The creation time the live output. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The time the live output was last modified. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The provisioning state of the live output. + ProvisioningState *string `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The resource state of the live output. + ResourceState *LiveOutputResourceState `json:"resourceState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type LiveOutputProperties. +func (l LiveOutputProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "archiveWindowLength", l.ArchiveWindowLength) + populate(objectMap, "assetName", l.AssetName) + populate(objectMap, "created", (*timeRFC3339)(l.Created)) + populate(objectMap, "description", l.Description) + populate(objectMap, "hls", l.Hls) + populate(objectMap, "lastModified", (*timeRFC3339)(l.LastModified)) + populate(objectMap, "manifestName", l.ManifestName) + populate(objectMap, "outputSnapTime", l.OutputSnapTime) + populate(objectMap, "provisioningState", l.ProvisioningState) + populate(objectMap, "resourceState", l.ResourceState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type LiveOutputProperties. +func (l *LiveOutputProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "archiveWindowLength": + err = unpopulate(val, &l.ArchiveWindowLength) + delete(rawMsg, key) + case "assetName": + err = unpopulate(val, &l.AssetName) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + l.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &l.Description) + delete(rawMsg, key) + case "hls": + err = unpopulate(val, &l.Hls) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + l.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "manifestName": + err = unpopulate(val, &l.ManifestName) + delete(rawMsg, key) + case "outputSnapTime": + err = unpopulate(val, &l.OutputSnapTime) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &l.ProvisioningState) + delete(rawMsg, key) + case "resourceState": + err = unpopulate(val, &l.ResourceState) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// LiveOutputsBeginCreateOptions contains the optional parameters for the LiveOutputs.BeginCreate method. +type LiveOutputsBeginCreateOptions struct { + // placeholder for future optional parameters +} + +// LiveOutputsBeginDeleteOptions contains the optional parameters for the LiveOutputs.BeginDelete method. +type LiveOutputsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// LiveOutputsGetOptions contains the optional parameters for the LiveOutputs.Get method. +type LiveOutputsGetOptions struct { + // placeholder for future optional parameters +} + +// LiveOutputsListOptions contains the optional parameters for the LiveOutputs.List method. +type LiveOutputsListOptions struct { + // placeholder for future optional parameters +} + +// LocationsCheckNameAvailabilityOptions contains the optional parameters for the Locations.CheckNameAvailability method. +type LocationsCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// LogSpecification - A diagnostic log emitted by service. +type LogSpecification struct { + // READ-ONLY; The time range for requests in each blob. + BlobDuration *string `json:"blobDuration,omitempty" azure:"ro"` + + // READ-ONLY; The diagnostic log category display name. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; The diagnostic log category name. + Name *string `json:"name,omitempty" azure:"ro"` +} + +// MediaFilterProperties - The Media Filter properties. +type MediaFilterProperties struct { + // The first quality. + FirstQuality *FirstQuality `json:"firstQuality,omitempty"` + + // The presentation time range. + PresentationTimeRange *PresentationTimeRange `json:"presentationTimeRange,omitempty"` + + // The tracks selection conditions. + Tracks []*FilterTrackSelection `json:"tracks,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaFilterProperties. +func (m MediaFilterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "firstQuality", m.FirstQuality) + populate(objectMap, "presentationTimeRange", m.PresentationTimeRange) + populate(objectMap, "tracks", m.Tracks) + return json.Marshal(objectMap) +} + +// MediaService - A Media Services account. +type MediaService struct { + TrackedResource + // The Managed Identity for the Media Services account. + Identity *MediaServiceIdentity `json:"identity,omitempty"` + + // The resource properties. + Properties *MediaServiceProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaService. +func (m MediaService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + m.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "systemData", m.SystemData) + return json.Marshal(objectMap) +} + +// MediaServiceCollection - A collection of MediaService items. +type MediaServiceCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of MediaService items. + Value []*MediaService `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaServiceCollection. +func (m MediaServiceCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", m.ODataNextLink) + populate(objectMap, "value", m.Value) + return json.Marshal(objectMap) +} + +type MediaServiceIdentity struct { + // REQUIRED; The identity type. + Type *string `json:"type,omitempty"` + + // The user assigned managed identities. + UserAssignedIdentities map[string]*UserAssignedManagedIdentity `json:"userAssignedIdentities,omitempty"` + + // READ-ONLY; The Principal ID of the identity. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` + + // READ-ONLY; The Tenant ID of the identity. + TenantID *string `json:"tenantId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaServiceIdentity. +func (m MediaServiceIdentity) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "principalId", m.PrincipalID) + populate(objectMap, "tenantId", m.TenantID) + populate(objectMap, "type", m.Type) + populate(objectMap, "userAssignedIdentities", m.UserAssignedIdentities) + return json.Marshal(objectMap) +} + +// MediaServiceProperties - Properties of the Media Services account. +type MediaServiceProperties struct { + // The account encryption properties. + Encryption *AccountEncryption `json:"encryption,omitempty"` + + // The Key Delivery properties for Media Services account. + KeyDelivery *KeyDelivery `json:"keyDelivery,omitempty"` + + // Whether or not public network access is allowed for resources under the Media Services account. + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + + // The storage accounts for this resource. + StorageAccounts []*StorageAccount `json:"storageAccounts,omitempty"` + StorageAuthentication *StorageAuthentication `json:"storageAuthentication,omitempty"` + + // READ-ONLY; The Media Services account ID. + MediaServiceID *string `json:"mediaServiceId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaServiceProperties. +func (m MediaServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "encryption", m.Encryption) + populate(objectMap, "keyDelivery", m.KeyDelivery) + populate(objectMap, "mediaServiceId", m.MediaServiceID) + populate(objectMap, "publicNetworkAccess", m.PublicNetworkAccess) + populate(objectMap, "storageAccounts", m.StorageAccounts) + populate(objectMap, "storageAuthentication", m.StorageAuthentication) + return json.Marshal(objectMap) +} + +// MediaServiceUpdate - A Media Services account update. +type MediaServiceUpdate struct { + // The Managed Identity for the Media Services account. + Identity *MediaServiceIdentity `json:"identity,omitempty"` + + // The resource properties. + Properties *MediaServiceProperties `json:"properties,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type MediaServiceUpdate. +func (m MediaServiceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "identity", m.Identity) + populate(objectMap, "properties", m.Properties) + populate(objectMap, "tags", m.Tags) + return json.Marshal(objectMap) +} + +// MediaservicesCreateOrUpdateOptions contains the optional parameters for the Mediaservices.CreateOrUpdate method. +type MediaservicesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesDeleteOptions contains the optional parameters for the Mediaservices.Delete method. +type MediaservicesDeleteOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesGetOptions contains the optional parameters for the Mediaservices.Get method. +type MediaservicesGetOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesListBySubscriptionOptions contains the optional parameters for the Mediaservices.ListBySubscription method. +type MediaservicesListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesListEdgePoliciesOptions contains the optional parameters for the Mediaservices.ListEdgePolicies method. +type MediaservicesListEdgePoliciesOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesListOptions contains the optional parameters for the Mediaservices.List method. +type MediaservicesListOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesSyncStorageKeysOptions contains the optional parameters for the Mediaservices.SyncStorageKeys method. +type MediaservicesSyncStorageKeysOptions struct { + // placeholder for future optional parameters +} + +// MediaservicesUpdateOptions contains the optional parameters for the Mediaservices.Update method. +type MediaservicesUpdateOptions struct { + // placeholder for future optional parameters +} + +// MetricDimension - A metric dimension. +type MetricDimension struct { + // READ-ONLY; The display name for the dimension. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; The metric dimension name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Whether to export metric to shoebox. + ToBeExportedForShoebox *bool `json:"toBeExportedForShoebox,omitempty" azure:"ro"` +} + +// MetricSpecification - A metric emitted by service. +type MetricSpecification struct { + // Supported aggregation types. + SupportedAggregationTypes []*string `json:"supportedAggregationTypes,omitempty"` + + // READ-ONLY; The metric aggregation type + AggregationType *MetricAggregationType `json:"aggregationType,omitempty" azure:"ro"` + + // READ-ONLY; The metric dimensions. + Dimensions []*MetricDimension `json:"dimensions,omitempty" azure:"ro"` + + // READ-ONLY; The metric display description. + DisplayDescription *string `json:"displayDescription,omitempty" azure:"ro"` + + // READ-ONLY; The metric display name. + DisplayName *string `json:"displayName,omitempty" azure:"ro"` + + // READ-ONLY; Indicates whether regional MDM account is enabled. + EnableRegionalMdmAccount *bool `json:"enableRegionalMdmAccount,omitempty" azure:"ro"` + + // READ-ONLY; The metric lock aggregation type + LockAggregationType *MetricAggregationType `json:"lockAggregationType,omitempty" azure:"ro"` + + // READ-ONLY; The metric name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The source MDM account. + SourceMdmAccount *string `json:"sourceMdmAccount,omitempty" azure:"ro"` + + // READ-ONLY; The source MDM namespace. + SourceMdmNamespace *string `json:"sourceMdmNamespace,omitempty" azure:"ro"` + + // READ-ONLY; The supported time grain types. + SupportedTimeGrainTypes []*string `json:"supportedTimeGrainTypes,omitempty" azure:"ro"` + + // READ-ONLY; The metric unit + Unit *MetricUnit `json:"unit,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type MetricSpecification. +func (m MetricSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "aggregationType", m.AggregationType) + populate(objectMap, "dimensions", m.Dimensions) + populate(objectMap, "displayDescription", m.DisplayDescription) + populate(objectMap, "displayName", m.DisplayName) + populate(objectMap, "enableRegionalMdmAccount", m.EnableRegionalMdmAccount) + populate(objectMap, "lockAggregationType", m.LockAggregationType) + populate(objectMap, "name", m.Name) + populate(objectMap, "sourceMdmAccount", m.SourceMdmAccount) + populate(objectMap, "sourceMdmNamespace", m.SourceMdmNamespace) + populate(objectMap, "supportedAggregationTypes", m.SupportedAggregationTypes) + populate(objectMap, "supportedTimeGrainTypes", m.SupportedTimeGrainTypes) + populate(objectMap, "unit", m.Unit) + return json.Marshal(objectMap) +} + +// Mp4Format - Describes the properties for an output ISO MP4 file. +type Mp4Format struct { + MultiBitrateFormat +} + +// MarshalJSON implements the json.Marshaller interface for type Mp4Format. +func (m Mp4Format) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + m.MultiBitrateFormat.marshalInternal(objectMap, "#Microsoft.Media.Mp4Format") + return json.Marshal(objectMap) +} + +// MultiBitrateFormatClassification provides polymorphic access to related types. +// Call the interface's GetMultiBitrateFormat() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *Mp4Format, *MultiBitrateFormat, *TransportStreamFormat +type MultiBitrateFormatClassification interface { + FormatClassification + // GetMultiBitrateFormat returns the MultiBitrateFormat content of the underlying type. + GetMultiBitrateFormat() *MultiBitrateFormat +} + +// MultiBitrateFormat - Describes the properties for producing a collection of GOP aligned multi-bitrate files. The default behavior is to produce one output +// file for each video layer which is muxed together with all the +// audios. The exact output files produced can be controlled by specifying the outputFiles collection. +type MultiBitrateFormat struct { + Format + // The list of output files to produce. Each entry in the list is a set of audio and video layer labels to be muxed together . + OutputFiles []*OutputFile `json:"outputFiles,omitempty"` +} + +// GetMultiBitrateFormat implements the MultiBitrateFormatClassification interface for type MultiBitrateFormat. +func (m *MultiBitrateFormat) GetMultiBitrateFormat() *MultiBitrateFormat { return m } + +// MarshalJSON implements the json.Marshaller interface for type MultiBitrateFormat. +func (m MultiBitrateFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + m.marshalInternal(objectMap, "#Microsoft.Media.MultiBitrateFormat") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type MultiBitrateFormat. +func (m *MultiBitrateFormat) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return m.unmarshalInternal(rawMsg) +} + +func (m MultiBitrateFormat) marshalInternal(objectMap map[string]interface{}, discValue string) { + m.Format.marshalInternal(objectMap, discValue) + populate(objectMap, "outputFiles", m.OutputFiles) +} + +func (m *MultiBitrateFormat) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "outputFiles": + err = unpopulate(val, &m.OutputFiles) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := m.Format.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// NoEncryption - Class for NoEncryption scheme +type NoEncryption struct { + // Representing supported protocols + EnabledProtocols *EnabledProtocols `json:"enabledProtocols,omitempty"` +} + +// Operation - An operation. +type Operation struct { + // REQUIRED; The operation name. + Name *string `json:"name,omitempty"` + + // Indicates the action type. + ActionType *ActionType `json:"actionType,omitempty"` + + // The operation display name. + Display *OperationDisplay `json:"display,omitempty"` + + // Whether the operation applies to data-plane. + IsDataAction *bool `json:"isDataAction,omitempty"` + + // Origin of the operation. + Origin *string `json:"origin,omitempty"` + + // Operation properties format. + Properties *Properties `json:"properties,omitempty"` +} + +// OperationCollection - A collection of Operation items. +type OperationCollection struct { + // A collection of Operation items. + Value []*Operation `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationCollection. +func (o OperationCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationDisplay - Operation details. +type OperationDisplay struct { + // The operation description. + Description *string `json:"description,omitempty"` + + // The operation type. + Operation *string `json:"operation,omitempty"` + + // The service provider. + Provider *string `json:"provider,omitempty"` + + // Resource on which the operation is performed. + Resource *string `json:"resource,omitempty"` +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// OutputFile - Represents an output file produced. +type OutputFile struct { + // REQUIRED; The list of labels that describe how the encoder should multiplex video and audio into an output file. For example, if the encoder is producing + // two video layers with labels v1 and v2, and one audio + // layer with label a1, then an array like '[v1, a1]' tells the encoder to produce an output file with the video track represented by v1 and the audio track + // represented by a1. + Labels []*string `json:"labels,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OutputFile. +func (o OutputFile) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "labels", o.Labels) + return json.Marshal(objectMap) +} + +// OverlayClassification provides polymorphic access to related types. +// Call the interface's GetOverlay() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AudioOverlay, *Overlay, *VideoOverlay +type OverlayClassification interface { + // GetOverlay returns the Overlay content of the underlying type. + GetOverlay() *Overlay +} + +// Overlay - Base type for all overlays - image, audio or video. +type Overlay struct { + // REQUIRED; The label of the job input which is to be used as an overlay. The Input must specify exactly one file. You can specify an image file in JPG, + // PNG, GIF or BMP format, or an audio file (such as a WAV, + // MP3, WMA or M4A file), or a video file. See https://aka.ms/mesformats for the complete list of supported audio and video file formats. + InputLabel *string `json:"inputLabel,omitempty"` + + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` + + // The gain level of audio in the overlay. The value should be in the range [0, 1.0]. The default is 1.0. + AudioGainLevel *float64 `json:"audioGainLevel,omitempty"` + + // The end position, with reference to the input video, at which the overlay ends. The value should be in ISO 8601 format. For example, PT30S to end the + // overlay at 30 seconds into the input video. If not + // specified or the value is greater than the input video duration, the overlay will be applied until the end of the input video if the overlay media duration + // is greater than the input video duration, + // else the overlay will last as long as the overlay media duration. + End *string `json:"end,omitempty"` + + // The duration over which the overlay fades in onto the input video. The value should be in ISO 8601 duration format. If not specified the default behavior + // is to have no fade in (same as PT0S). + FadeInDuration *string `json:"fadeInDuration,omitempty"` + + // The duration over which the overlay fades out of the input video. The value should be in ISO 8601 duration format. If not specified the default behavior + // is to have no fade out (same as PT0S). + FadeOutDuration *string `json:"fadeOutDuration,omitempty"` + + // The start position, with reference to the input video, at which the overlay starts. The value should be in ISO 8601 format. For example, PT05S to start + // the overlay at 5 seconds into the input video. + // If not specified the overlay starts from the beginning of the input video. + Start *string `json:"start,omitempty"` +} + +// GetOverlay implements the OverlayClassification interface for type Overlay. +func (o *Overlay) GetOverlay() *Overlay { return o } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Overlay. +func (o *Overlay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return o.unmarshalInternal(rawMsg) +} + +func (o Overlay) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "audioGainLevel", o.AudioGainLevel) + populate(objectMap, "end", o.End) + populate(objectMap, "fadeInDuration", o.FadeInDuration) + populate(objectMap, "fadeOutDuration", o.FadeOutDuration) + populate(objectMap, "inputLabel", o.InputLabel) + o.ODataType = &discValue + objectMap["@odata.type"] = o.ODataType + populate(objectMap, "start", o.Start) +} + +func (o *Overlay) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "audioGainLevel": + err = unpopulate(val, &o.AudioGainLevel) + delete(rawMsg, key) + case "end": + err = unpopulate(val, &o.End) + delete(rawMsg, key) + case "fadeInDuration": + err = unpopulate(val, &o.FadeInDuration) + delete(rawMsg, key) + case "fadeOutDuration": + err = unpopulate(val, &o.FadeOutDuration) + delete(rawMsg, key) + case "inputLabel": + err = unpopulate(val, &o.InputLabel) + delete(rawMsg, key) + case "@odata.type": + err = unpopulate(val, &o.ODataType) + delete(rawMsg, key) + case "start": + err = unpopulate(val, &o.Start) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// PNGFormat - Describes the settings for producing PNG thumbnails. +type PNGFormat struct { + ImageFormat +} + +// MarshalJSON implements the json.Marshaller interface for type PNGFormat. +func (p PNGFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.ImageFormat.marshalInternal(objectMap, "#Microsoft.Media.PngFormat") + return json.Marshal(objectMap) +} + +// PNGImage - Describes the properties for producing a series of PNG images from the input video. +type PNGImage struct { + Image + // A collection of output PNG image layers to be produced by the encoder. + Layers []*PNGLayer `json:"layers,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PNGImage. +func (p PNGImage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Image.marshalInternal(objectMap, "#Microsoft.Media.PngImage") + populate(objectMap, "layers", p.Layers) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PNGImage. +func (p *PNGImage) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "layers": + err = unpopulate(val, &p.Layers) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := p.Image.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// PNGLayer - Describes the settings to produce a PNG image from the input video. +type PNGLayer struct { + Layer +} + +// MarshalJSON implements the json.Marshaller interface for type PNGLayer. +func (p PNGLayer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Layer.marshalInternal(objectMap, "#Microsoft.Media.PngLayer") + return json.Marshal(objectMap) +} + +// PresentationTimeRange - The presentation time range, this is asset related and not recommended for Account Filter. +type PresentationTimeRange struct { + // The absolute end time boundary. + EndTimestamp *int64 `json:"endTimestamp,omitempty"` + + // The indicator of forcing existing of end time stamp. + ForceEndTimestamp *bool `json:"forceEndTimestamp,omitempty"` + + // The relative to end right edge. + LiveBackoffDuration *int64 `json:"liveBackoffDuration,omitempty"` + + // The relative to end sliding window. + PresentationWindowDuration *int64 `json:"presentationWindowDuration,omitempty"` + + // The absolute start time boundary. + StartTimestamp *int64 `json:"startTimestamp,omitempty"` + + // The time scale of time stamps. + Timescale *int64 `json:"timescale,omitempty"` +} + +// PresetClassification provides polymorphic access to related types. +// Call the interface's GetPreset() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AudioAnalyzerPreset, *BuiltInStandardEncoderPreset, *FaceDetectorPreset, *Preset, *StandardEncoderPreset, *VideoAnalyzerPreset +type PresetClassification interface { + // GetPreset returns the Preset content of the underlying type. + GetPreset() *Preset +} + +// Preset - Base type for all Presets, which define the recipe or instructions on how the input media files should be processed. +type Preset struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetPreset implements the PresetClassification interface for type Preset. +func (p *Preset) GetPreset() *Preset { return p } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Preset. +func (p *Preset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return p.unmarshalInternal(rawMsg) +} + +func (p Preset) marshalInternal(objectMap map[string]interface{}, discValue string) { + p.ODataType = &discValue + objectMap["@odata.type"] = p.ODataType +} + +func (p *Preset) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &p.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// PresetConfigurations - An object of optional configuration settings for encoder. +type PresetConfigurations struct { + // Allows you to configure the encoder settings to control the balance between speed and quality. Example: set Complexity as Speed for faster encoding but + // less compression efficiency. + Complexity *Complexity `json:"complexity,omitempty"` + + // Sets the interleave mode of the output to control how audio and video are stored in the container format. Example: set InterleavedOutput as NonInterleavedOutput + // to produce audio-only and video-only + // outputs in separate MP4 files. + InterleaveOutput *InterleaveOutput `json:"interleaveOutput,omitempty"` + + // The key frame interval in seconds. Example: set KeyFrameIntervalInSeconds as 2 to reduce the playback buffering for some players. + KeyFrameIntervalInSeconds *float32 `json:"keyFrameIntervalInSeconds,omitempty"` + + // The maximum bitrate in bits per second (threshold for the top video layer). Example: set MaxBitrateBps as 6000000 to avoid producing very high bitrate + // outputs for contents with high complexity. + MaxBitrateBps *int32 `json:"maxBitrateBps,omitempty"` + + // The maximum height of output video layers. Example: set MaxHeight as 720 to produce output layers up to 720P even if the input is 4K. + MaxHeight *int32 `json:"maxHeight,omitempty"` + + // The maximum number of output video layers. Example: set MaxLayers as 4 to make sure at most 4 output layers are produced to control the overall cost + // of the encoding job. + MaxLayers *int32 `json:"maxLayers,omitempty"` + + // The minimum bitrate in bits per second (threshold for the bottom video layer). Example: set MinBitrateBps as 200000 to have a bottom layer that covers + // users with low network bandwidth. + MinBitrateBps *int32 `json:"minBitrateBps,omitempty"` + + // The minimum height of output video layers. Example: set MinHeight as 360 to avoid output layers of smaller resolutions like 180P. + MinHeight *int32 `json:"minHeight,omitempty"` +} + +// PrivateEndpoint - The Private Endpoint resource. +type PrivateEndpoint struct { + // READ-ONLY; The ARM identifier for Private Endpoint + ID *string `json:"id,omitempty" azure:"ro"` +} + +// PrivateEndpointConnection - The Private Endpoint Connection resource. +type PrivateEndpointConnection struct { + Resource + // Resource properties. + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionListResult - List of private endpoint connection associated with the specified storage account +type PrivateEndpointConnectionListResult struct { + // Array of private endpoint connections + Value []*PrivateEndpointConnection `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionProperties - Properties of the PrivateEndpointConnectProperties. +type PrivateEndpointConnectionProperties struct { + // REQUIRED; A collection of information about the state of the connection between service consumer and provider. + PrivateLinkServiceConnectionState *PrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + + // The resource of private end point. + PrivateEndpoint *PrivateEndpoint `json:"privateEndpoint,omitempty"` + + // READ-ONLY; The provisioning state of the private endpoint connection resource. + ProvisioningState *PrivateEndpointConnectionProvisioningState `json:"provisioningState,omitempty" azure:"ro"` +} + +// PrivateEndpointConnectionsCreateOrUpdateOptions contains the optional parameters for the PrivateEndpointConnections.CreateOrUpdate method. +type PrivateEndpointConnectionsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsDeleteOptions contains the optional parameters for the PrivateEndpointConnections.Delete method. +type PrivateEndpointConnectionsDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsGetOptions contains the optional parameters for the PrivateEndpointConnections.Get method. +type PrivateEndpointConnectionsGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsListOptions contains the optional parameters for the PrivateEndpointConnections.List method. +type PrivateEndpointConnectionsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResource - A private link resource +type PrivateLinkResource struct { + Resource + // Resource properties. + Properties *PrivateLinkResourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateLinkResourceListResult - A list of private link resources +type PrivateLinkResourceListResult struct { + // Array of private link resources + Value []*PrivateLinkResource `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceListResult. +func (p PrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateLinkResourceProperties - Properties of a private link resource. +type PrivateLinkResourceProperties struct { + // The private link resource Private link DNS zone name. + RequiredZoneNames []*string `json:"requiredZoneNames,omitempty"` + + // READ-ONLY; The private link resource group id. + GroupID *string `json:"groupId,omitempty" azure:"ro"` + + // READ-ONLY; The private link resource required member names. + RequiredMembers []*string `json:"requiredMembers,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + return json.Marshal(objectMap) +} + +// PrivateLinkResourcesGetOptions contains the optional parameters for the PrivateLinkResources.Get method. +type PrivateLinkResourcesGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesListOptions contains the optional parameters for the PrivateLinkResources.List method. +type PrivateLinkResourcesListOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkServiceConnectionState - A collection of information about the state of the connection between service consumer and provider. +type PrivateLinkServiceConnectionState struct { + // A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string `json:"actionsRequired,omitempty"` + + // The reason for approval/rejection of the connection. + Description *string `json:"description,omitempty"` + + // Indicates whether the connection has been Approved/Rejected/Removed by the owner of the service. + Status *PrivateEndpointServiceConnectionStatus `json:"status,omitempty"` +} + +// Properties - The service specification property. +type Properties struct { + // READ-ONLY; The service specifications. + ServiceSpecification *ServiceSpecification `json:"serviceSpecification,omitempty" azure:"ro"` +} + +// ProxyResource - The resource model definition for a Azure Resource Manager proxy resource. It will not have tags and a location +type ProxyResource struct { + Resource +} + +func (p ProxyResource) marshalInternal(objectMap map[string]interface{}) { + p.Resource.marshalInternal(objectMap) +} + +// Rectangle - Describes the properties of a rectangular window applied to the input media before processing it. +type Rectangle struct { + // The height of the rectangular region in pixels. This can be absolute pixel value (e.g 100), or relative to the size of the video (For example, 50%). + Height *string `json:"height,omitempty"` + + // The number of pixels from the left-margin. This can be absolute pixel value (e.g 100), or relative to the size of the video (For example, 50%). + Left *string `json:"left,omitempty"` + + // The number of pixels from the top-margin. This can be absolute pixel value (e.g 100), or relative to the size of the video (For example, 50%). + Top *string `json:"top,omitempty"` + + // The width of the rectangular region in pixels. This can be absolute pixel value (e.g 100), or relative to the size of the video (For example, 50%). + Width *string `json:"width,omitempty"` +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +type ResourceIdentity struct { + // REQUIRED; Indicates whether to use System Assigned Managed Identity. Mutual exclusive with User Assigned Managed Identity. + UseSystemAssignedIdentity *bool `json:"useSystemAssignedIdentity,omitempty"` + + // The user assigned managed identity's ARM ID to use when accessing a resource. + UserAssignedIdentity *string `json:"userAssignedIdentity,omitempty"` +} + +// SelectAudioTrackByAttribute - Select audio tracks from the input by specifying an attribute and an attribute filter. +type SelectAudioTrackByAttribute struct { + AudioTrackDescriptor + // REQUIRED; The TrackAttribute to filter the tracks by. + Attribute *TrackAttribute `json:"attribute,omitempty"` + + // REQUIRED; The type of AttributeFilter to apply to the TrackAttribute in order to select the tracks. + Filter *AttributeFilter `json:"filter,omitempty"` + + // The value to filter the tracks by. Only used when AttributeFilter.ValueEquals is specified for the Filter property. + FilterValue *string `json:"filterValue,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SelectAudioTrackByAttribute. +func (s SelectAudioTrackByAttribute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.AudioTrackDescriptor.marshalInternal(objectMap, "#Microsoft.Media.SelectAudioTrackByAttribute") + populate(objectMap, "attribute", s.Attribute) + populate(objectMap, "filter", s.Filter) + populate(objectMap, "filterValue", s.FilterValue) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SelectAudioTrackByAttribute. +func (s *SelectAudioTrackByAttribute) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "attribute": + err = unpopulate(val, &s.Attribute) + delete(rawMsg, key) + case "filter": + err = unpopulate(val, &s.Filter) + delete(rawMsg, key) + case "filterValue": + err = unpopulate(val, &s.FilterValue) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.AudioTrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SelectAudioTrackByID - Select audio tracks from the input by specifying a track identifier. +type SelectAudioTrackByID struct { + AudioTrackDescriptor + // REQUIRED; Track identifier to select + TrackID *int64 `json:"trackId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SelectAudioTrackByID. +func (s SelectAudioTrackByID) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.AudioTrackDescriptor.marshalInternal(objectMap, "#Microsoft.Media.SelectAudioTrackById") + populate(objectMap, "trackId", s.TrackID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SelectAudioTrackByID. +func (s *SelectAudioTrackByID) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "trackId": + err = unpopulate(val, &s.TrackID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.AudioTrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SelectVideoTrackByAttribute - Select video tracks from the input by specifying an attribute and an attribute filter. +type SelectVideoTrackByAttribute struct { + VideoTrackDescriptor + // REQUIRED; The TrackAttribute to filter the tracks by. + Attribute *TrackAttribute `json:"attribute,omitempty"` + + // REQUIRED; The type of AttributeFilter to apply to the TrackAttribute in order to select the tracks. + Filter *AttributeFilter `json:"filter,omitempty"` + + // The value to filter the tracks by. Only used when AttributeFilter.ValueEquals is specified for the Filter property. For TrackAttribute.Bitrate, this + // should be an integer value in bits per second (e.g: + // '1500000'). The TrackAttribute.Language is not supported for video tracks. + FilterValue *string `json:"filterValue,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SelectVideoTrackByAttribute. +func (s SelectVideoTrackByAttribute) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.VideoTrackDescriptor.marshalInternal(objectMap, "#Microsoft.Media.SelectVideoTrackByAttribute") + populate(objectMap, "attribute", s.Attribute) + populate(objectMap, "filter", s.Filter) + populate(objectMap, "filterValue", s.FilterValue) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SelectVideoTrackByAttribute. +func (s *SelectVideoTrackByAttribute) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "attribute": + err = unpopulate(val, &s.Attribute) + delete(rawMsg, key) + case "filter": + err = unpopulate(val, &s.Filter) + delete(rawMsg, key) + case "filterValue": + err = unpopulate(val, &s.FilterValue) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.VideoTrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SelectVideoTrackByID - Select video tracks from the input by specifying a track identifier. +type SelectVideoTrackByID struct { + VideoTrackDescriptor + // REQUIRED; Track identifier to select + TrackID *int64 `json:"trackId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SelectVideoTrackByID. +func (s SelectVideoTrackByID) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.VideoTrackDescriptor.marshalInternal(objectMap, "#Microsoft.Media.SelectVideoTrackById") + populate(objectMap, "trackId", s.TrackID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SelectVideoTrackByID. +func (s *SelectVideoTrackByID) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "trackId": + err = unpopulate(val, &s.TrackID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.VideoTrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ServiceSpecification - The service metric specifications. +type ServiceSpecification struct { + // READ-ONLY; List of log specifications. + LogSpecifications []*LogSpecification `json:"logSpecifications,omitempty" azure:"ro"` + + // READ-ONLY; List of metric specifications. + MetricSpecifications []*MetricSpecification `json:"metricSpecifications,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceSpecification. +func (s ServiceSpecification) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "logSpecifications", s.LogSpecifications) + populate(objectMap, "metricSpecifications", s.MetricSpecifications) + return json.Marshal(objectMap) +} + +// StandardEncoderPreset - Describes all the settings to be used when encoding the input video with the Standard Encoder. +type StandardEncoderPreset struct { + Preset + // REQUIRED; The list of codecs to be used when encoding the input video. + Codecs []CodecClassification `json:"codecs,omitempty"` + + // REQUIRED; The list of outputs to be produced by the encoder. + Formats []FormatClassification `json:"formats,omitempty"` + + // One or more filtering operations that are applied to the input media before encoding. + Filters *Filters `json:"filters,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StandardEncoderPreset. +func (s StandardEncoderPreset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Preset.marshalInternal(objectMap, "#Microsoft.Media.StandardEncoderPreset") + populate(objectMap, "codecs", s.Codecs) + populate(objectMap, "filters", s.Filters) + populate(objectMap, "formats", s.Formats) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StandardEncoderPreset. +func (s *StandardEncoderPreset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "codecs": + s.Codecs, err = unmarshalCodecClassificationArray(val) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, &s.Filters) + delete(rawMsg, key) + case "formats": + s.Formats, err = unmarshalFormatClassificationArray(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.Preset.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// StorageAccount - The storage account details. +type StorageAccount struct { + // REQUIRED; The type of the storage account. + Type *StorageAccountType `json:"type,omitempty"` + + // The ID of the storage account resource. Media Services relies on tables and queues as well as blobs, so the primary storage account must be a Standard + // Storage account (either Microsoft.ClassicStorage + // or Microsoft.Storage). Blob only storage accounts can be added as secondary storage accounts. + ID *string `json:"id,omitempty"` + + // The storage account identity. + Identity *ResourceIdentity `json:"identity,omitempty"` + + // READ-ONLY; The current status of the storage account mapping. + Status *string `json:"status,omitempty" azure:"ro"` +} + +// StorageEncryptedAssetDecryptionData - Data needed to decrypt asset files encrypted with legacy storage encryption. +type StorageEncryptedAssetDecryptionData struct { + // Asset File encryption metadata. + AssetFileEncryptionMetadata []*AssetFileEncryptionMetadata `json:"assetFileEncryptionMetadata,omitempty"` + + // The Asset File storage encryption key. + Key []byte `json:"key,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StorageEncryptedAssetDecryptionData. +func (s StorageEncryptedAssetDecryptionData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "assetFileEncryptionMetadata", s.AssetFileEncryptionMetadata) + populateByteArray(objectMap, "key", s.Key, runtime.Base64StdFormat) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StorageEncryptedAssetDecryptionData. +func (s *StorageEncryptedAssetDecryptionData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "assetFileEncryptionMetadata": + err = unpopulate(val, &s.AssetFileEncryptionMetadata) + delete(rawMsg, key) + case "key": + err = runtime.DecodeByteArray(string(val), &s.Key, runtime.Base64StdFormat) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamingEndpoint - The streaming endpoint. +type StreamingEndpoint struct { + TrackedResource + // The streaming endpoint properties. + Properties *StreamingEndpointProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingEndpoint. +func (s StreamingEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + return json.Marshal(objectMap) +} + +// StreamingEndpointAccessControl - Streaming endpoint access control definition. +type StreamingEndpointAccessControl struct { + // The access control of Akamai + Akamai *AkamaiAccessControl `json:"akamai,omitempty"` + + // The IP access control of the streaming endpoint. + IP *IPAccessControl `json:"ip,omitempty"` +} + +// StreamingEndpointListResult - The streaming endpoint list result. +type StreamingEndpointListResult struct { + // The number of result. + ODataCount *int32 `json:"@odata.count,omitempty"` + + // The link to the next set of results. Not empty if value contains incomplete list of streaming endpoints. + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // The result of the List StreamingEndpoint operation. + Value []*StreamingEndpoint `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingEndpointListResult. +func (s StreamingEndpointListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.count", s.ODataCount) + populate(objectMap, "@odata.nextLink", s.ODataNextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StreamingEndpointProperties - The streaming endpoint properties. +type StreamingEndpointProperties struct { + // REQUIRED; The number of scale units. Use the Scale operation to adjust this value. + ScaleUnits *int32 `json:"scaleUnits,omitempty"` + + // The access control definition of the streaming endpoint. + AccessControl *StreamingEndpointAccessControl `json:"accessControl,omitempty"` + + // This feature is deprecated, do not set a value for this property. + AvailabilitySetName *string `json:"availabilitySetName,omitempty"` + + // The CDN enabled flag. + CdnEnabled *bool `json:"cdnEnabled,omitempty"` + + // The CDN profile name. + CdnProfile *string `json:"cdnProfile,omitempty"` + + // The CDN provider name. + CdnProvider *string `json:"cdnProvider,omitempty"` + + // The streaming endpoint access policies. + CrossSiteAccessPolicies *CrossSiteAccessPolicies `json:"crossSiteAccessPolicies,omitempty"` + + // The custom host names of the streaming endpoint + CustomHostNames []*string `json:"customHostNames,omitempty"` + + // The streaming endpoint description. + Description *string `json:"description,omitempty"` + + // Max cache age + MaxCacheAge *int64 `json:"maxCacheAge,omitempty"` + + // READ-ONLY; The exact time the streaming endpoint was created. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The free trial expiration time. + FreeTrialEndTime *time.Time `json:"freeTrialEndTime,omitempty" azure:"ro"` + + // READ-ONLY; The streaming endpoint host name. + HostName *string `json:"hostName,omitempty" azure:"ro"` + + // READ-ONLY; The exact time the streaming endpoint was last modified. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` + + // READ-ONLY; The provisioning state of the streaming endpoint. + ProvisioningState *string `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The resource state of the streaming endpoint. + ResourceState *StreamingEndpointResourceState `json:"resourceState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingEndpointProperties. +func (s StreamingEndpointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "accessControl", s.AccessControl) + populate(objectMap, "availabilitySetName", s.AvailabilitySetName) + populate(objectMap, "cdnEnabled", s.CdnEnabled) + populate(objectMap, "cdnProfile", s.CdnProfile) + populate(objectMap, "cdnProvider", s.CdnProvider) + populate(objectMap, "created", (*timeRFC3339)(s.Created)) + populate(objectMap, "crossSiteAccessPolicies", s.CrossSiteAccessPolicies) + populate(objectMap, "customHostNames", s.CustomHostNames) + populate(objectMap, "description", s.Description) + populate(objectMap, "freeTrialEndTime", (*timeRFC3339)(s.FreeTrialEndTime)) + populate(objectMap, "hostName", s.HostName) + populate(objectMap, "lastModified", (*timeRFC3339)(s.LastModified)) + populate(objectMap, "maxCacheAge", s.MaxCacheAge) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "resourceState", s.ResourceState) + populate(objectMap, "scaleUnits", s.ScaleUnits) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamingEndpointProperties. +func (s *StreamingEndpointProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "accessControl": + err = unpopulate(val, &s.AccessControl) + delete(rawMsg, key) + case "availabilitySetName": + err = unpopulate(val, &s.AvailabilitySetName) + delete(rawMsg, key) + case "cdnEnabled": + err = unpopulate(val, &s.CdnEnabled) + delete(rawMsg, key) + case "cdnProfile": + err = unpopulate(val, &s.CdnProfile) + delete(rawMsg, key) + case "cdnProvider": + err = unpopulate(val, &s.CdnProvider) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "crossSiteAccessPolicies": + err = unpopulate(val, &s.CrossSiteAccessPolicies) + delete(rawMsg, key) + case "customHostNames": + err = unpopulate(val, &s.CustomHostNames) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &s.Description) + delete(rawMsg, key) + case "freeTrialEndTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.FreeTrialEndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "hostName": + err = unpopulate(val, &s.HostName) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "maxCacheAge": + err = unpopulate(val, &s.MaxCacheAge) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &s.ProvisioningState) + delete(rawMsg, key) + case "resourceState": + err = unpopulate(val, &s.ResourceState) + delete(rawMsg, key) + case "scaleUnits": + err = unpopulate(val, &s.ScaleUnits) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamingEndpointsBeginCreateOptions contains the optional parameters for the StreamingEndpoints.BeginCreate method. +type StreamingEndpointsBeginCreateOptions struct { + // The flag indicates if the resource should be automatically started on creation. + AutoStart *bool +} + +// StreamingEndpointsBeginDeleteOptions contains the optional parameters for the StreamingEndpoints.BeginDelete method. +type StreamingEndpointsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsBeginScaleOptions contains the optional parameters for the StreamingEndpoints.BeginScale method. +type StreamingEndpointsBeginScaleOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsBeginStartOptions contains the optional parameters for the StreamingEndpoints.BeginStart method. +type StreamingEndpointsBeginStartOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsBeginStopOptions contains the optional parameters for the StreamingEndpoints.BeginStop method. +type StreamingEndpointsBeginStopOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsBeginUpdateOptions contains the optional parameters for the StreamingEndpoints.BeginUpdate method. +type StreamingEndpointsBeginUpdateOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsGetOptions contains the optional parameters for the StreamingEndpoints.Get method. +type StreamingEndpointsGetOptions struct { + // placeholder for future optional parameters +} + +// StreamingEndpointsListOptions contains the optional parameters for the StreamingEndpoints.List method. +type StreamingEndpointsListOptions struct { + // placeholder for future optional parameters +} + +// StreamingEntityScaleUnit - scale units definition +type StreamingEntityScaleUnit struct { + // The scale unit number of the streaming endpoint. + ScaleUnit *int32 `json:"scaleUnit,omitempty"` +} + +// StreamingLocator - A Streaming Locator resource +type StreamingLocator struct { + ProxyResource + // Properties of the Streaming Locator. + Properties *StreamingLocatorProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingLocator. +func (s StreamingLocator) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + return json.Marshal(objectMap) +} + +// StreamingLocatorCollection - A collection of StreamingLocator items. +type StreamingLocatorCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of StreamingLocator items. + Value []*StreamingLocator `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingLocatorCollection. +func (s StreamingLocatorCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", s.ODataNextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StreamingLocatorContentKey - Class for content key in Streaming Locator +type StreamingLocatorContentKey struct { + // REQUIRED; ID of Content Key + ID *string `json:"id,omitempty"` + + // Label of Content Key as specified in the Streaming Policy + LabelReferenceInStreamingPolicy *string `json:"labelReferenceInStreamingPolicy,omitempty"` + + // Value of Content Key + Value *string `json:"value,omitempty"` + + // READ-ONLY; ContentKeyPolicy used by Content Key + PolicyName *string `json:"policyName,omitempty" azure:"ro"` + + // READ-ONLY; Tracks which use this Content Key + Tracks []*TrackSelection `json:"tracks,omitempty" azure:"ro"` + + // READ-ONLY; Encryption type of Content Key + Type *StreamingLocatorContentKeyType `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingLocatorContentKey. +func (s StreamingLocatorContentKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", s.ID) + populate(objectMap, "labelReferenceInStreamingPolicy", s.LabelReferenceInStreamingPolicy) + populate(objectMap, "policyName", s.PolicyName) + populate(objectMap, "tracks", s.Tracks) + populate(objectMap, "type", s.Type) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StreamingLocatorProperties - Properties of the Streaming Locator. +type StreamingLocatorProperties struct { + // REQUIRED; Asset Name + AssetName *string `json:"assetName,omitempty"` + + // REQUIRED; Name of the Streaming Policy used by this Streaming Locator. Either specify the name of Streaming Policy you created or use one of the predefined + // Streaming Policies. The predefined Streaming Policies + // available are: 'PredefinedDownloadOnly', 'PredefinedClearStreamingOnly', 'PredefinedDownloadAndClearStreaming', 'PredefinedClearKey', 'PredefinedMultiDrmCencStreaming' + // and 'Predefined + // MultiDrmStreaming' + StreamingPolicyName *string `json:"streamingPolicyName,omitempty"` + + // Alternative Media ID of this Streaming Locator + AlternativeMediaID *string `json:"alternativeMediaId,omitempty"` + + // The ContentKeys used by this Streaming Locator. + ContentKeys []*StreamingLocatorContentKey `json:"contentKeys,omitempty"` + + // Name of the default ContentKeyPolicy used by this Streaming Locator. + DefaultContentKeyPolicyName *string `json:"defaultContentKeyPolicyName,omitempty"` + + // The end time of the Streaming Locator. + EndTime *time.Time `json:"endTime,omitempty"` + + // A list of asset or account filters which apply to this streaming locator + Filters []*string `json:"filters,omitempty"` + + // The start time of the Streaming Locator. + StartTime *time.Time `json:"startTime,omitempty"` + + // The StreamingLocatorId of the Streaming Locator. + StreamingLocatorID *string `json:"streamingLocatorId,omitempty"` + + // READ-ONLY; The creation time of the Streaming Locator. + Created *time.Time `json:"created,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingLocatorProperties. +func (s StreamingLocatorProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "alternativeMediaId", s.AlternativeMediaID) + populate(objectMap, "assetName", s.AssetName) + populate(objectMap, "contentKeys", s.ContentKeys) + populate(objectMap, "created", (*timeRFC3339)(s.Created)) + populate(objectMap, "defaultContentKeyPolicyName", s.DefaultContentKeyPolicyName) + populate(objectMap, "endTime", (*timeRFC3339)(s.EndTime)) + populate(objectMap, "filters", s.Filters) + populate(objectMap, "startTime", (*timeRFC3339)(s.StartTime)) + populate(objectMap, "streamingLocatorId", s.StreamingLocatorID) + populate(objectMap, "streamingPolicyName", s.StreamingPolicyName) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamingLocatorProperties. +func (s *StreamingLocatorProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "alternativeMediaId": + err = unpopulate(val, &s.AlternativeMediaID) + delete(rawMsg, key) + case "assetName": + err = unpopulate(val, &s.AssetName) + delete(rawMsg, key) + case "contentKeys": + err = unpopulate(val, &s.ContentKeys) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "defaultContentKeyPolicyName": + err = unpopulate(val, &s.DefaultContentKeyPolicyName) + delete(rawMsg, key) + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "filters": + err = unpopulate(val, &s.Filters) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "streamingLocatorId": + err = unpopulate(val, &s.StreamingLocatorID) + delete(rawMsg, key) + case "streamingPolicyName": + err = unpopulate(val, &s.StreamingPolicyName) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamingLocatorsCreateOptions contains the optional parameters for the StreamingLocators.Create method. +type StreamingLocatorsCreateOptions struct { + // placeholder for future optional parameters +} + +// StreamingLocatorsDeleteOptions contains the optional parameters for the StreamingLocators.Delete method. +type StreamingLocatorsDeleteOptions struct { + // placeholder for future optional parameters +} + +// StreamingLocatorsGetOptions contains the optional parameters for the StreamingLocators.Get method. +type StreamingLocatorsGetOptions struct { + // placeholder for future optional parameters +} + +// StreamingLocatorsListContentKeysOptions contains the optional parameters for the StreamingLocators.ListContentKeys method. +type StreamingLocatorsListContentKeysOptions struct { + // placeholder for future optional parameters +} + +// StreamingLocatorsListOptions contains the optional parameters for the StreamingLocators.List method. +type StreamingLocatorsListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string + // Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to + // but not greater than the specified value n. + Top *int32 +} + +// StreamingLocatorsListPathsOptions contains the optional parameters for the StreamingLocators.ListPaths method. +type StreamingLocatorsListPathsOptions struct { + // placeholder for future optional parameters +} + +// StreamingPath - Class of paths for streaming +type StreamingPath struct { + // REQUIRED; Encryption scheme + EncryptionScheme *EncryptionScheme `json:"encryptionScheme,omitempty"` + + // REQUIRED; Streaming protocol + StreamingProtocol *StreamingPolicyStreamingProtocol `json:"streamingProtocol,omitempty"` + + // Streaming paths for each protocol and encryptionScheme pair + Paths []*string `json:"paths,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPath. +func (s StreamingPath) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "encryptionScheme", s.EncryptionScheme) + populate(objectMap, "paths", s.Paths) + populate(objectMap, "streamingProtocol", s.StreamingProtocol) + return json.Marshal(objectMap) +} + +// StreamingPoliciesCreateOptions contains the optional parameters for the StreamingPolicies.Create method. +type StreamingPoliciesCreateOptions struct { + // placeholder for future optional parameters +} + +// StreamingPoliciesDeleteOptions contains the optional parameters for the StreamingPolicies.Delete method. +type StreamingPoliciesDeleteOptions struct { + // placeholder for future optional parameters +} + +// StreamingPoliciesGetOptions contains the optional parameters for the StreamingPolicies.Get method. +type StreamingPoliciesGetOptions struct { + // placeholder for future optional parameters +} + +// StreamingPoliciesListOptions contains the optional parameters for the StreamingPolicies.List method. +type StreamingPoliciesListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string + // Specifies a non-negative integer n that limits the number of items returned from a collection. The service returns the number of available items up to + // but not greater than the specified value n. + Top *int32 +} + +// StreamingPolicy - A Streaming Policy resource +type StreamingPolicy struct { + ProxyResource + // Class to specify properties of Streaming Policy + Properties *StreamingPolicyProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPolicy. +func (s StreamingPolicy) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "systemData", s.SystemData) + return json.Marshal(objectMap) +} + +// StreamingPolicyCollection - A collection of StreamingPolicy items. +type StreamingPolicyCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of StreamingPolicy items. + Value []*StreamingPolicy `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPolicyCollection. +func (s StreamingPolicyCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", s.ODataNextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StreamingPolicyContentKey - Class to specify properties of content key +type StreamingPolicyContentKey struct { + // Label can be used to specify Content Key when creating a Streaming Locator + Label *string `json:"label,omitempty"` + + // Policy used by Content Key + PolicyName *string `json:"policyName,omitempty"` + + // Tracks which use this content key + Tracks []*TrackSelection `json:"tracks,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPolicyContentKey. +func (s StreamingPolicyContentKey) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "label", s.Label) + populate(objectMap, "policyName", s.PolicyName) + populate(objectMap, "tracks", s.Tracks) + return json.Marshal(objectMap) +} + +// StreamingPolicyContentKeys - Class to specify properties of all content keys in Streaming Policy +type StreamingPolicyContentKeys struct { + // Default content key for an encryption scheme + DefaultKey *DefaultKey `json:"defaultKey,omitempty"` + + // Representing tracks needs separate content key + KeyToTrackMappings []*StreamingPolicyContentKey `json:"keyToTrackMappings,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPolicyContentKeys. +func (s StreamingPolicyContentKeys) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "defaultKey", s.DefaultKey) + populate(objectMap, "keyToTrackMappings", s.KeyToTrackMappings) + return json.Marshal(objectMap) +} + +// StreamingPolicyFairPlayConfiguration - Class to specify configurations of FairPlay in Streaming Policy +type StreamingPolicyFairPlayConfiguration struct { + // REQUIRED; All license to be persistent or not + AllowPersistentLicense *bool `json:"allowPersistentLicense,omitempty"` + + // Template for the URL of the custom service delivering licenses to end user players. Not required when using Azure Media Services for issuing licenses. + // The template supports replaceable tokens that the + // service will update at runtime with the value specific to the request. The currently supported token values are {AlternativeMediaId}, which is replaced + // with the value of + // StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is replaced with the value of identifier of the key being requested. + CustomLicenseAcquisitionURLTemplate *string `json:"customLicenseAcquisitionUrlTemplate,omitempty"` +} + +// StreamingPolicyPlayReadyConfiguration - Class to specify configurations of PlayReady in Streaming Policy +type StreamingPolicyPlayReadyConfiguration struct { + // Template for the URL of the custom service delivering licenses to end user players. Not required when using Azure Media Services for issuing licenses. + // The template supports replaceable tokens that the + // service will update at runtime with the value specific to the request. The currently supported token values are {AlternativeMediaId}, which is replaced + // with the value of + // StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is replaced with the value of identifier of the key being requested. + CustomLicenseAcquisitionURLTemplate *string `json:"customLicenseAcquisitionUrlTemplate,omitempty"` + + // Custom attributes for PlayReady + PlayReadyCustomAttributes *string `json:"playReadyCustomAttributes,omitempty"` +} + +// StreamingPolicyProperties - Class to specify properties of Streaming Policy +type StreamingPolicyProperties struct { + // Configuration of CommonEncryptionCbcs + CommonEncryptionCbcs *CommonEncryptionCbcs `json:"commonEncryptionCbcs,omitempty"` + + // Configuration of CommonEncryptionCenc + CommonEncryptionCenc *CommonEncryptionCenc `json:"commonEncryptionCenc,omitempty"` + + // Default ContentKey used by current Streaming Policy + DefaultContentKeyPolicyName *string `json:"defaultContentKeyPolicyName,omitempty"` + + // Configuration of EnvelopeEncryption + EnvelopeEncryption *EnvelopeEncryption `json:"envelopeEncryption,omitempty"` + + // Configurations of NoEncryption + NoEncryption *NoEncryption `json:"noEncryption,omitempty"` + + // READ-ONLY; Creation time of Streaming Policy + Created *time.Time `json:"created,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingPolicyProperties. +func (s StreamingPolicyProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "commonEncryptionCbcs", s.CommonEncryptionCbcs) + populate(objectMap, "commonEncryptionCenc", s.CommonEncryptionCenc) + populate(objectMap, "created", (*timeRFC3339)(s.Created)) + populate(objectMap, "defaultContentKeyPolicyName", s.DefaultContentKeyPolicyName) + populate(objectMap, "envelopeEncryption", s.EnvelopeEncryption) + populate(objectMap, "noEncryption", s.NoEncryption) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamingPolicyProperties. +func (s *StreamingPolicyProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "commonEncryptionCbcs": + err = unpopulate(val, &s.CommonEncryptionCbcs) + delete(rawMsg, key) + case "commonEncryptionCenc": + err = unpopulate(val, &s.CommonEncryptionCenc) + delete(rawMsg, key) + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "defaultContentKeyPolicyName": + err = unpopulate(val, &s.DefaultContentKeyPolicyName) + delete(rawMsg, key) + case "envelopeEncryption": + err = unpopulate(val, &s.EnvelopeEncryption) + delete(rawMsg, key) + case "noEncryption": + err = unpopulate(val, &s.NoEncryption) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamingPolicyWidevineConfiguration - Class to specify configurations of Widevine in Streaming Policy +type StreamingPolicyWidevineConfiguration struct { + // Template for the URL of the custom service delivering licenses to end user players. Not required when using Azure Media Services for issuing licenses. + // The template supports replaceable tokens that the + // service will update at runtime with the value specific to the request. The currently supported token values are {AlternativeMediaId}, which is replaced + // with the value of + // StreamingLocatorId.AlternativeMediaId, and {ContentKeyId}, which is replaced with the value of identifier of the key being requested. + CustomLicenseAcquisitionURLTemplate *string `json:"customLicenseAcquisitionUrlTemplate,omitempty"` +} + +// SyncStorageKeysInput - The input to the sync storage keys request. +type SyncStorageKeysInput struct { + // The ID of the storage account resource. + ID *string `json:"id,omitempty"` +} + +// SystemData - Metadata pertaining to creation and last modification of the resource. +type SystemData struct { + // The timestamp of resource creation (UTC). + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // The identity that created the resource. + CreatedBy *string `json:"createdBy,omitempty"` + + // The type of identity that created the resource. + CreatedByType *CreatedByType `json:"createdByType,omitempty"` + + // The timestamp of resource last modification (UTC) + LastModifiedAt *time.Time `json:"lastModifiedAt,omitempty"` + + // The identity that last modified the resource. + LastModifiedBy *string `json:"lastModifiedBy,omitempty"` + + // The type of identity that last modified the resource. + LastModifiedByType *CreatedByType `json:"lastModifiedByType,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SystemData. +func (s SystemData) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(s.CreatedAt)) + populate(objectMap, "createdBy", s.CreatedBy) + populate(objectMap, "createdByType", s.CreatedByType) + populate(objectMap, "lastModifiedAt", (*timeRFC3339)(s.LastModifiedAt)) + populate(objectMap, "lastModifiedBy", s.LastModifiedBy) + populate(objectMap, "lastModifiedByType", s.LastModifiedByType) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SystemData. +func (s *SystemData) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "createdBy": + err = unpopulate(val, &s.CreatedBy) + delete(rawMsg, key) + case "createdByType": + err = unpopulate(val, &s.CreatedByType) + delete(rawMsg, key) + case "lastModifiedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "lastModifiedBy": + err = unpopulate(val, &s.LastModifiedBy) + delete(rawMsg, key) + case "lastModifiedByType": + err = unpopulate(val, &s.LastModifiedByType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// TrackDescriptorClassification provides polymorphic access to related types. +// Call the interface's GetTrackDescriptor() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AudioTrackDescriptor, *SelectAudioTrackByAttribute, *SelectAudioTrackById, *SelectVideoTrackByAttribute, *SelectVideoTrackById, +// - *TrackDescriptor, *VideoTrackDescriptor +type TrackDescriptorClassification interface { + // GetTrackDescriptor returns the TrackDescriptor content of the underlying type. + GetTrackDescriptor() *TrackDescriptor +} + +// TrackDescriptor - Base type for all TrackDescriptor types, which define the metadata and selection for tracks that should be processed by a Job +type TrackDescriptor struct { + // REQUIRED; The discriminator for derived types. + ODataType *string `json:"@odata.type,omitempty"` +} + +// GetTrackDescriptor implements the TrackDescriptorClassification interface for type TrackDescriptor. +func (t *TrackDescriptor) GetTrackDescriptor() *TrackDescriptor { return t } + +// UnmarshalJSON implements the json.Unmarshaller interface for type TrackDescriptor. +func (t *TrackDescriptor) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return t.unmarshalInternal(rawMsg) +} + +func (t TrackDescriptor) marshalInternal(objectMap map[string]interface{}, discValue string) { + t.ODataType = &discValue + objectMap["@odata.type"] = t.ODataType +} + +func (t *TrackDescriptor) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "@odata.type": + err = unpopulate(val, &t.ODataType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// TrackPropertyCondition - Class to specify one track property condition +type TrackPropertyCondition struct { + // REQUIRED; Track property condition operation + Operation *TrackPropertyCompareOperation `json:"operation,omitempty"` + + // REQUIRED; Track property type + Property *TrackPropertyType `json:"property,omitempty"` + + // Track property value + Value *string `json:"value,omitempty"` +} + +// TrackSelection - Class to select a track +type TrackSelection struct { + // TrackSelections is a track property condition list which can specify track(s) + TrackSelections []*TrackPropertyCondition `json:"trackSelections,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackSelection. +func (t TrackSelection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "trackSelections", t.TrackSelections) + return json.Marshal(objectMap) +} + +// TrackedResource - The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' +type TrackedResource struct { + Resource + // REQUIRED; The geo-location where the resource lives + Location *string `json:"location,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (t TrackedResource) marshalInternal(objectMap map[string]interface{}) { + t.Resource.marshalInternal(objectMap) + populate(objectMap, "location", t.Location) + populate(objectMap, "tags", t.Tags) +} + +// Transform - A Transform encapsulates the rules or instructions for generating desired outputs from input media, such as by transcoding or by extracting +// insights. After the Transform is created, it can be applied +// to input media by creating Jobs. +type Transform struct { + ProxyResource + // The resource properties. + Properties *TransformProperties `json:"properties,omitempty"` + + // READ-ONLY; The system metadata relating to this resource. + SystemData *SystemData `json:"systemData,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Transform. +func (t Transform) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "properties", t.Properties) + populate(objectMap, "systemData", t.SystemData) + return json.Marshal(objectMap) +} + +// TransformCollection - A collection of Transform items. +type TransformCollection struct { + // A link to the next page of the collection (when the collection contains too many results to return in one response). + ODataNextLink *string `json:"@odata.nextLink,omitempty"` + + // A collection of Transform items. + Value []*Transform `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TransformCollection. +func (t TransformCollection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "@odata.nextLink", t.ODataNextLink) + populate(objectMap, "value", t.Value) + return json.Marshal(objectMap) +} + +// TransformOutput - Describes the properties of a TransformOutput, which are the rules to be applied while generating the desired output. +type TransformOutput struct { + // REQUIRED; Preset that describes the operations that will be used to modify, transcode, or extract insights from the source file to generate the output. + Preset PresetClassification `json:"preset,omitempty"` + + // A Transform can define more than one outputs. This property defines what the service should do when one output fails - either continue to produce other + // outputs, or, stop the other outputs. The overall + // Job state will not reflect failures of outputs that are specified with 'ContinueJob'. The default is 'StopProcessingJob'. + OnError *OnErrorType `json:"onError,omitempty"` + + // Sets the relative priority of the TransformOutputs within a Transform. This sets the priority that the service uses for processing TransformOutputs. + // The default priority is Normal. + RelativePriority *Priority `json:"relativePriority,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TransformOutput. +func (t TransformOutput) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "onError", t.OnError) + populate(objectMap, "preset", t.Preset) + populate(objectMap, "relativePriority", t.RelativePriority) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TransformOutput. +func (t *TransformOutput) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "onError": + err = unpopulate(val, &t.OnError) + delete(rawMsg, key) + case "preset": + t.Preset, err = unmarshalPresetClassification(val) + delete(rawMsg, key) + case "relativePriority": + err = unpopulate(val, &t.RelativePriority) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// TransformProperties - A Transform. +type TransformProperties struct { + // REQUIRED; An array of one or more TransformOutputs that the Transform should generate. + Outputs []*TransformOutput `json:"outputs,omitempty"` + + // An optional verbose description of the Transform. + Description *string `json:"description,omitempty"` + + // READ-ONLY; The UTC date and time when the Transform was created, in 'YYYY-MM-DDThh:mm:ssZ' format. + Created *time.Time `json:"created,omitempty" azure:"ro"` + + // READ-ONLY; The UTC date and time when the Transform was last updated, in 'YYYY-MM-DDThh:mm:ssZ' format. + LastModified *time.Time `json:"lastModified,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type TransformProperties. +func (t TransformProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "created", (*timeRFC3339)(t.Created)) + populate(objectMap, "description", t.Description) + populate(objectMap, "lastModified", (*timeRFC3339)(t.LastModified)) + populate(objectMap, "outputs", t.Outputs) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type TransformProperties. +func (t *TransformProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "created": + var aux timeRFC3339 + err = unpopulate(val, &aux) + t.Created = (*time.Time)(&aux) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &t.Description) + delete(rawMsg, key) + case "lastModified": + var aux timeRFC3339 + err = unpopulate(val, &aux) + t.LastModified = (*time.Time)(&aux) + delete(rawMsg, key) + case "outputs": + err = unpopulate(val, &t.Outputs) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// TransformsCreateOrUpdateOptions contains the optional parameters for the Transforms.CreateOrUpdate method. +type TransformsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// TransformsDeleteOptions contains the optional parameters for the Transforms.Delete method. +type TransformsDeleteOptions struct { + // placeholder for future optional parameters +} + +// TransformsGetOptions contains the optional parameters for the Transforms.Get method. +type TransformsGetOptions struct { + // placeholder for future optional parameters +} + +// TransformsListOptions contains the optional parameters for the Transforms.List method. +type TransformsListOptions struct { + // Restricts the set of items returned. + Filter *string + // Specifies the key by which the result collection should be ordered. + Orderby *string +} + +// TransformsUpdateOptions contains the optional parameters for the Transforms.Update method. +type TransformsUpdateOptions struct { + // placeholder for future optional parameters +} + +// TransportStreamFormat - Describes the properties for generating an MPEG-2 Transport Stream (ISO/IEC 13818-1) output video file(s). +type TransportStreamFormat struct { + MultiBitrateFormat +} + +// MarshalJSON implements the json.Marshaller interface for type TransportStreamFormat. +func (t TransportStreamFormat) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.MultiBitrateFormat.marshalInternal(objectMap, "#Microsoft.Media.TransportStreamFormat") + return json.Marshal(objectMap) +} + +// UTCClipTime - Specifies the clip time as a Utc time position in the media file. The Utc time can point to a different position depending on whether the +// media file starts from a timestamp of zero or not. +type UTCClipTime struct { + ClipTime + // REQUIRED; The time position on the timeline of the input media based on Utc time. + Time *time.Time `json:"time,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type UTCClipTime. +func (u UTCClipTime) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + u.ClipTime.marshalInternal(objectMap, "#Microsoft.Media.UtcClipTime") + populate(objectMap, "time", (*timeRFC3339)(u.Time)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type UTCClipTime. +func (u *UTCClipTime) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "time": + var aux timeRFC3339 + err = unpopulate(val, &aux) + u.Time = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := u.ClipTime.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type UserAssignedManagedIdentity struct { + // READ-ONLY; The client ID. + ClientID *string `json:"clientId,omitempty" azure:"ro"` + + // READ-ONLY; The principal ID. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` +} + +// VideoClassification provides polymorphic access to related types. +// Call the interface's GetVideo() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *H264Video, *H265Video, *Image, *JpgImage, *PngImage, *Video +type VideoClassification interface { + CodecClassification + // GetVideo returns the Video content of the underlying type. + GetVideo() *Video +} + +// Video - Describes the basic properties for encoding the input video. +type Video struct { + Codec + // The distance between two key frames. The value should be non-zero in the range [0.5, 20] seconds, specified in ISO 8601 format. The default is 2 seconds(PT2S). + // Note that this setting is ignored if + // VideoSyncMode.Passthrough is set, where the KeyFrameInterval value will follow the input source setting. + KeyFrameInterval *string `json:"keyFrameInterval,omitempty"` + + // The resizing mode - how the input video will be resized to fit the desired output resolution(s). Default is AutoSize + StretchMode *StretchMode `json:"stretchMode,omitempty"` + + // The Video Sync Mode + SyncMode *VideoSyncMode `json:"syncMode,omitempty"` +} + +// GetVideo implements the VideoClassification interface for type Video. +func (v *Video) GetVideo() *Video { return v } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Video. +func (v *Video) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return v.unmarshalInternal(rawMsg) +} + +func (v Video) marshalInternal(objectMap map[string]interface{}, discValue string) { + v.Codec.marshalInternal(objectMap, discValue) + populate(objectMap, "keyFrameInterval", v.KeyFrameInterval) + populate(objectMap, "stretchMode", v.StretchMode) + populate(objectMap, "syncMode", v.SyncMode) +} + +func (v *Video) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "keyFrameInterval": + err = unpopulate(val, &v.KeyFrameInterval) + delete(rawMsg, key) + case "stretchMode": + err = unpopulate(val, &v.StretchMode) + delete(rawMsg, key) + case "syncMode": + err = unpopulate(val, &v.SyncMode) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := v.Codec.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// VideoAnalyzerPreset - A video analyzer preset that extracts insights (rich metadata) from both audio and video, and outputs a JSON format file. +type VideoAnalyzerPreset struct { + AudioAnalyzerPreset + // Defines the type of insights that you want the service to generate. The allowed values are 'AudioInsightsOnly', 'VideoInsightsOnly', and 'AllInsights'. + // The default is AllInsights. If you set this to + // AllInsights and the input is audio only, then only audio insights are generated. Similarly if the input is video only, then only video insights are generated. + // It is recommended that you not use + // AudioInsightsOnly if you expect some of your inputs to be video only; or use VideoInsightsOnly if you expect some of your inputs to be audio only. Your + // Jobs in such conditions would error out. + InsightsToExtract *InsightsType `json:"insightsToExtract,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type VideoAnalyzerPreset. +func (v VideoAnalyzerPreset) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + v.AudioAnalyzerPreset.marshalInternal(objectMap, "#Microsoft.Media.VideoAnalyzerPreset") + populate(objectMap, "insightsToExtract", v.InsightsToExtract) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VideoAnalyzerPreset. +func (v *VideoAnalyzerPreset) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "insightsToExtract": + err = unpopulate(val, &v.InsightsToExtract) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := v.AudioAnalyzerPreset.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// VideoLayerClassification provides polymorphic access to related types. +// Call the interface's GetVideoLayer() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *H264Layer, *VideoLayer +type VideoLayerClassification interface { + LayerClassification + // GetVideoLayer returns the VideoLayer content of the underlying type. + GetVideoLayer() *VideoLayer +} + +// VideoLayer - Describes the settings to be used when encoding the input video into a desired output bitrate layer. +type VideoLayer struct { + Layer + // REQUIRED; The average bitrate in bits per second at which to encode the input video when generating this layer. This is a required field. + Bitrate *int32 `json:"bitrate,omitempty"` + + // Whether or not adaptive B-frames are to be used when encoding this layer. If not specified, the encoder will turn it on whenever the video profile permits + // its use. + AdaptiveBFrame *bool `json:"adaptiveBFrame,omitempty"` + + // The number of B-frames to be used when encoding this layer. If not specified, the encoder chooses an appropriate number based on the video profile and + // level. + BFrames *int32 `json:"bFrames,omitempty"` + + // The frame rate (in frames per second) at which to encode this layer. The value can be in the form of M/N where M and N are integers (For example, 30000/1001), + // or in the form of a number (For example, + // 30, or 29.97). The encoder enforces constraints on allowed frame rates based on the profile and level. If it is not specified, the encoder will use the + // same frame rate as the input video. + FrameRate *string `json:"frameRate,omitempty"` + + // The maximum bitrate (in bits per second), at which the VBV buffer should be assumed to refill. If not specified, defaults to the same value as bitrate. + MaxBitrate *int32 `json:"maxBitrate,omitempty"` + + // The number of slices to be used when encoding this layer. If not specified, default is zero, which means that encoder will use a single slice for each + // frame. + Slices *int32 `json:"slices,omitempty"` +} + +// GetVideoLayer implements the VideoLayerClassification interface for type VideoLayer. +func (v *VideoLayer) GetVideoLayer() *VideoLayer { return v } + +// MarshalJSON implements the json.Marshaller interface for type VideoLayer. +func (v VideoLayer) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + v.marshalInternal(objectMap, "#Microsoft.Media.VideoLayer") + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VideoLayer. +func (v *VideoLayer) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return v.unmarshalInternal(rawMsg) +} + +func (v VideoLayer) marshalInternal(objectMap map[string]interface{}, discValue string) { + v.Layer.marshalInternal(objectMap, discValue) + populate(objectMap, "adaptiveBFrame", v.AdaptiveBFrame) + populate(objectMap, "bFrames", v.BFrames) + populate(objectMap, "bitrate", v.Bitrate) + populate(objectMap, "frameRate", v.FrameRate) + populate(objectMap, "maxBitrate", v.MaxBitrate) + populate(objectMap, "slices", v.Slices) +} + +func (v *VideoLayer) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "adaptiveBFrame": + err = unpopulate(val, &v.AdaptiveBFrame) + delete(rawMsg, key) + case "bFrames": + err = unpopulate(val, &v.BFrames) + delete(rawMsg, key) + case "bitrate": + err = unpopulate(val, &v.Bitrate) + delete(rawMsg, key) + case "frameRate": + err = unpopulate(val, &v.FrameRate) + delete(rawMsg, key) + case "maxBitrate": + err = unpopulate(val, &v.MaxBitrate) + delete(rawMsg, key) + case "slices": + err = unpopulate(val, &v.Slices) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := v.Layer.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// VideoOverlay - Describes the properties of a video overlay. +type VideoOverlay struct { + Overlay + // An optional rectangular window used to crop the overlay image or video. + CropRectangle *Rectangle `json:"cropRectangle,omitempty"` + + // The opacity of the overlay. This is a value in the range [0 - 1.0]. Default is 1.0 which mean the overlay is opaque. + Opacity *float64 `json:"opacity,omitempty"` + + // The location in the input video where the overlay is applied. + Position *Rectangle `json:"position,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type VideoOverlay. +func (v VideoOverlay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + v.Overlay.marshalInternal(objectMap, "#Microsoft.Media.VideoOverlay") + populate(objectMap, "cropRectangle", v.CropRectangle) + populate(objectMap, "opacity", v.Opacity) + populate(objectMap, "position", v.Position) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type VideoOverlay. +func (v *VideoOverlay) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "cropRectangle": + err = unpopulate(val, &v.CropRectangle) + delete(rawMsg, key) + case "opacity": + err = unpopulate(val, &v.Opacity) + delete(rawMsg, key) + case "position": + err = unpopulate(val, &v.Position) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := v.Overlay.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// VideoTrackDescriptorClassification provides polymorphic access to related types. +// Call the interface's GetVideoTrackDescriptor() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *SelectVideoTrackByAttribute, *SelectVideoTrackById, *VideoTrackDescriptor +type VideoTrackDescriptorClassification interface { + TrackDescriptorClassification + // GetVideoTrackDescriptor returns the VideoTrackDescriptor content of the underlying type. + GetVideoTrackDescriptor() *VideoTrackDescriptor +} + +// VideoTrackDescriptor - A TrackSelection to select video tracks. +type VideoTrackDescriptor struct { + TrackDescriptor +} + +// GetVideoTrackDescriptor implements the VideoTrackDescriptorClassification interface for type VideoTrackDescriptor. +func (v *VideoTrackDescriptor) GetVideoTrackDescriptor() *VideoTrackDescriptor { return v } + +// MarshalJSON implements the json.Marshaller interface for type VideoTrackDescriptor. +func (v VideoTrackDescriptor) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + v.marshalInternal(objectMap, "#Microsoft.Media.VideoTrackDescriptor") + return json.Marshal(objectMap) +} + +func (v VideoTrackDescriptor) marshalInternal(objectMap map[string]interface{}, discValue string) { + v.TrackDescriptor.marshalInternal(objectMap, discValue) +} + +func (v *VideoTrackDescriptor) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + if err := v.TrackDescriptor.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func populateByteArray(m map[string]interface{}, k string, b []byte, f runtime.Base64Encoding) { + if azcore.IsNullValue(b) { + m[k] = nil + } else if len(b) == 0 { + return + } else { + m[k] = runtime.EncodeByteArray(b, f) + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_operations_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_operations_client.go new file mode 100644 index 000000000000..d957efa06c27 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_operations_client.go @@ -0,0 +1,84 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all the Media Services operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(ctx context.Context, options *OperationsListOptions) (OperationsListResponse, error) { + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OperationsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OperationsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Media/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationCollection); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pagers.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pagers.go new file mode 100644 index 000000000000..dff63fd5d4e0 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pagers.go @@ -0,0 +1,720 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AccountFiltersListPager provides operations for iterating over paged responses. +type AccountFiltersListPager struct { + client *AccountFiltersClient + current AccountFiltersListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AccountFiltersListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AccountFiltersListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AccountFiltersListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AccountFilterCollection.ODataNextLink == nil || len(*p.current.AccountFilterCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AccountFiltersListResponse page. +func (p *AccountFiltersListPager) PageResponse() AccountFiltersListResponse { + return p.current +} + +// AssetFiltersListPager provides operations for iterating over paged responses. +type AssetFiltersListPager struct { + client *AssetFiltersClient + current AssetFiltersListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AssetFiltersListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AssetFiltersListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AssetFiltersListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AssetFilterCollection.ODataNextLink == nil || len(*p.current.AssetFilterCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AssetFiltersListResponse page. +func (p *AssetFiltersListPager) PageResponse() AssetFiltersListResponse { + return p.current +} + +// AssetsListPager provides operations for iterating over paged responses. +type AssetsListPager struct { + client *AssetsClient + current AssetsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AssetsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AssetsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AssetsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AssetCollection.ODataNextLink == nil || len(*p.current.AssetCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AssetsListResponse page. +func (p *AssetsListPager) PageResponse() AssetsListResponse { + return p.current +} + +// ContentKeyPoliciesListPager provides operations for iterating over paged responses. +type ContentKeyPoliciesListPager struct { + client *ContentKeyPoliciesClient + current ContentKeyPoliciesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ContentKeyPoliciesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ContentKeyPoliciesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ContentKeyPoliciesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ContentKeyPolicyCollection.ODataNextLink == nil || len(*p.current.ContentKeyPolicyCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ContentKeyPoliciesListResponse page. +func (p *ContentKeyPoliciesListPager) PageResponse() ContentKeyPoliciesListResponse { + return p.current +} + +// JobsListPager provides operations for iterating over paged responses. +type JobsListPager struct { + client *JobsClient + current JobsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, JobsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *JobsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *JobsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.JobCollection.ODataNextLink == nil || len(*p.current.JobCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current JobsListResponse page. +func (p *JobsListPager) PageResponse() JobsListResponse { + return p.current +} + +// LiveEventsListPager provides operations for iterating over paged responses. +type LiveEventsListPager struct { + client *LiveEventsClient + current LiveEventsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, LiveEventsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *LiveEventsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *LiveEventsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.LiveEventListResult.ODataNextLink == nil || len(*p.current.LiveEventListResult.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current LiveEventsListResponse page. +func (p *LiveEventsListPager) PageResponse() LiveEventsListResponse { + return p.current +} + +// LiveOutputsListPager provides operations for iterating over paged responses. +type LiveOutputsListPager struct { + client *LiveOutputsClient + current LiveOutputsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, LiveOutputsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *LiveOutputsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *LiveOutputsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.LiveOutputListResult.ODataNextLink == nil || len(*p.current.LiveOutputListResult.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current LiveOutputsListResponse page. +func (p *LiveOutputsListPager) PageResponse() LiveOutputsListResponse { + return p.current +} + +// MediaservicesListBySubscriptionPager provides operations for iterating over paged responses. +type MediaservicesListBySubscriptionPager struct { + client *MediaservicesClient + current MediaservicesListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, MediaservicesListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *MediaservicesListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *MediaservicesListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.MediaServiceCollection.ODataNextLink == nil || len(*p.current.MediaServiceCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current MediaservicesListBySubscriptionResponse page. +func (p *MediaservicesListBySubscriptionPager) PageResponse() MediaservicesListBySubscriptionResponse { + return p.current +} + +// MediaservicesListPager provides operations for iterating over paged responses. +type MediaservicesListPager struct { + client *MediaservicesClient + current MediaservicesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, MediaservicesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *MediaservicesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *MediaservicesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.MediaServiceCollection.ODataNextLink == nil || len(*p.current.MediaServiceCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current MediaservicesListResponse page. +func (p *MediaservicesListPager) PageResponse() MediaservicesListResponse { + return p.current +} + +// StreamingEndpointsListPager provides operations for iterating over paged responses. +type StreamingEndpointsListPager struct { + client *StreamingEndpointsClient + current StreamingEndpointsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StreamingEndpointsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StreamingEndpointsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StreamingEndpointsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StreamingEndpointListResult.ODataNextLink == nil || len(*p.current.StreamingEndpointListResult.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StreamingEndpointsListResponse page. +func (p *StreamingEndpointsListPager) PageResponse() StreamingEndpointsListResponse { + return p.current +} + +// StreamingLocatorsListPager provides operations for iterating over paged responses. +type StreamingLocatorsListPager struct { + client *StreamingLocatorsClient + current StreamingLocatorsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StreamingLocatorsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StreamingLocatorsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StreamingLocatorsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StreamingLocatorCollection.ODataNextLink == nil || len(*p.current.StreamingLocatorCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StreamingLocatorsListResponse page. +func (p *StreamingLocatorsListPager) PageResponse() StreamingLocatorsListResponse { + return p.current +} + +// StreamingPoliciesListPager provides operations for iterating over paged responses. +type StreamingPoliciesListPager struct { + client *StreamingPoliciesClient + current StreamingPoliciesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StreamingPoliciesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StreamingPoliciesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StreamingPoliciesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StreamingPolicyCollection.ODataNextLink == nil || len(*p.current.StreamingPolicyCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StreamingPoliciesListResponse page. +func (p *StreamingPoliciesListPager) PageResponse() StreamingPoliciesListResponse { + return p.current +} + +// TransformsListPager provides operations for iterating over paged responses. +type TransformsListPager struct { + client *TransformsClient + current TransformsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, TransformsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *TransformsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *TransformsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.TransformCollection.ODataNextLink == nil || len(*p.current.TransformCollection.ODataNextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current TransformsListResponse page. +func (p *TransformsListPager) PageResponse() TransformsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pollers.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pollers.go new file mode 100644 index 000000000000..f08a66e34141 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_pollers.go @@ -0,0 +1,661 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// LiveEventsAllocatePoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsAllocatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsAllocatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsAllocatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsAllocateResponse will be returned. +func (p *LiveEventsAllocatePoller) FinalResponse(ctx context.Context) (LiveEventsAllocateResponse, error) { + respType := LiveEventsAllocateResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveEventsAllocateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsAllocatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsCreatePoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsCreateResponse will be returned. +func (p *LiveEventsCreatePoller) FinalResponse(ctx context.Context) (LiveEventsCreateResponse, error) { + respType := LiveEventsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.LiveEvent) + if err != nil { + return LiveEventsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsDeletePoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsDeleteResponse will be returned. +func (p *LiveEventsDeletePoller) FinalResponse(ctx context.Context) (LiveEventsDeleteResponse, error) { + respType := LiveEventsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveEventsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsResetPoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsResetPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsResetPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsResetPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsResetResponse will be returned. +func (p *LiveEventsResetPoller) FinalResponse(ctx context.Context) (LiveEventsResetResponse, error) { + respType := LiveEventsResetResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveEventsResetResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsResetPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsStartPoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsStartPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsStartPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsStartPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsStartResponse will be returned. +func (p *LiveEventsStartPoller) FinalResponse(ctx context.Context) (LiveEventsStartResponse, error) { + respType := LiveEventsStartResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveEventsStartResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsStartPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsStopPoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsStopPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsStopPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsStopPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsStopResponse will be returned. +func (p *LiveEventsStopPoller) FinalResponse(ctx context.Context) (LiveEventsStopResponse, error) { + respType := LiveEventsStopResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveEventsStopResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsStopPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveEventsUpdatePoller provides polling facilities until the operation reaches a terminal state. +type LiveEventsUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveEventsUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveEventsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveEventsUpdateResponse will be returned. +func (p *LiveEventsUpdatePoller) FinalResponse(ctx context.Context) (LiveEventsUpdateResponse, error) { + respType := LiveEventsUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.LiveEvent) + if err != nil { + return LiveEventsUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveEventsUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveOutputsCreatePoller provides polling facilities until the operation reaches a terminal state. +type LiveOutputsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveOutputsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveOutputsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveOutputsCreateResponse will be returned. +func (p *LiveOutputsCreatePoller) FinalResponse(ctx context.Context) (LiveOutputsCreateResponse, error) { + respType := LiveOutputsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.LiveOutput) + if err != nil { + return LiveOutputsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveOutputsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// LiveOutputsDeletePoller provides polling facilities until the operation reaches a terminal state. +type LiveOutputsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *LiveOutputsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *LiveOutputsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final LiveOutputsDeleteResponse will be returned. +func (p *LiveOutputsDeletePoller) FinalResponse(ctx context.Context) (LiveOutputsDeleteResponse, error) { + respType := LiveOutputsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return LiveOutputsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *LiveOutputsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsCreatePoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsCreatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsCreatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsCreatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsCreateResponse will be returned. +func (p *StreamingEndpointsCreatePoller) FinalResponse(ctx context.Context) (StreamingEndpointsCreateResponse, error) { + respType := StreamingEndpointsCreateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.StreamingEndpoint) + if err != nil { + return StreamingEndpointsCreateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsCreatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsDeletePoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsDeleteResponse will be returned. +func (p *StreamingEndpointsDeletePoller) FinalResponse(ctx context.Context) (StreamingEndpointsDeleteResponse, error) { + respType := StreamingEndpointsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingEndpointsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsScalePoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsScalePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsScalePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsScalePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsScaleResponse will be returned. +func (p *StreamingEndpointsScalePoller) FinalResponse(ctx context.Context) (StreamingEndpointsScaleResponse, error) { + respType := StreamingEndpointsScaleResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingEndpointsScaleResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsScalePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsStartPoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsStartPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsStartPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsStartPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsStartResponse will be returned. +func (p *StreamingEndpointsStartPoller) FinalResponse(ctx context.Context) (StreamingEndpointsStartResponse, error) { + respType := StreamingEndpointsStartResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingEndpointsStartResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsStartPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsStopPoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsStopPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsStopPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsStopPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsStopResponse will be returned. +func (p *StreamingEndpointsStopPoller) FinalResponse(ctx context.Context) (StreamingEndpointsStopResponse, error) { + respType := StreamingEndpointsStopResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingEndpointsStopResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsStopPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingEndpointsUpdatePoller provides polling facilities until the operation reaches a terminal state. +type StreamingEndpointsUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingEndpointsUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingEndpointsUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingEndpointsUpdateResponse will be returned. +func (p *StreamingEndpointsUpdatePoller) FinalResponse(ctx context.Context) (StreamingEndpointsUpdateResponse, error) { + respType := StreamingEndpointsUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.StreamingEndpoint) + if err != nil { + return StreamingEndpointsUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingEndpointsUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_polymorphic_helpers.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_polymorphic_helpers.go new file mode 100644 index 000000000000..379fdff6a6f2 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_polymorphic_helpers.go @@ -0,0 +1,1046 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import "encoding/json" + +func unmarshalAudioAnalyzerPresetClassification(rawMsg json.RawMessage) (AudioAnalyzerPresetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AudioAnalyzerPresetClassification + switch m["@odata.type"] { + case "#Microsoft.Media.VideoAnalyzerPreset": + b = &VideoAnalyzerPreset{} + default: + b = &AudioAnalyzerPreset{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalAudioAnalyzerPresetClassificationArray(rawMsg json.RawMessage) ([]AudioAnalyzerPresetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]AudioAnalyzerPresetClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalAudioAnalyzerPresetClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalAudioClassification(rawMsg json.RawMessage) (AudioClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AudioClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AacAudio": + b = &AacAudio{} + default: + b = &Audio{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalAudioClassificationArray(rawMsg json.RawMessage) ([]AudioClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]AudioClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalAudioClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalAudioTrackDescriptorClassification(rawMsg json.RawMessage) (AudioTrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b AudioTrackDescriptorClassification + switch m["@odata.type"] { + case "#Microsoft.Media.SelectAudioTrackByAttribute": + b = &SelectAudioTrackByAttribute{} + case "#Microsoft.Media.SelectAudioTrackById": + b = &SelectAudioTrackByID{} + default: + b = &AudioTrackDescriptor{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalAudioTrackDescriptorClassificationArray(rawMsg json.RawMessage) ([]AudioTrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]AudioTrackDescriptorClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalAudioTrackDescriptorClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalClipTimeClassification(rawMsg json.RawMessage) (ClipTimeClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ClipTimeClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AbsoluteClipTime": + b = &AbsoluteClipTime{} + case "#Microsoft.Media.UtcClipTime": + b = &UTCClipTime{} + default: + b = &ClipTime{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalClipTimeClassificationArray(rawMsg json.RawMessage) ([]ClipTimeClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ClipTimeClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalClipTimeClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalCodecClassification(rawMsg json.RawMessage) (CodecClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b CodecClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AacAudio": + b = &AacAudio{} + case "#Microsoft.Media.Audio": + b = &Audio{} + case "#Microsoft.Media.CopyAudio": + b = &CopyAudio{} + case "#Microsoft.Media.CopyVideo": + b = &CopyVideo{} + case "#Microsoft.Media.H264Video": + b = &H264Video{} + case "#Microsoft.Media.H265Video": + b = &H265Video{} + case "#Microsoft.Media.Image": + b = &Image{} + case "#Microsoft.Media.JpgImage": + b = &JpgImage{} + case "#Microsoft.Media.PngImage": + b = &PNGImage{} + case "#Microsoft.Media.Video": + b = &Video{} + default: + b = &Codec{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalCodecClassificationArray(rawMsg json.RawMessage) ([]CodecClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]CodecClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalCodecClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalContentKeyPolicyConfigurationClassification(rawMsg json.RawMessage) (ContentKeyPolicyConfigurationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ContentKeyPolicyConfigurationClassification + switch m["@odata.type"] { + case "#Microsoft.Media.ContentKeyPolicyClearKeyConfiguration": + b = &ContentKeyPolicyClearKeyConfiguration{} + case "#Microsoft.Media.ContentKeyPolicyFairPlayConfiguration": + b = &ContentKeyPolicyFairPlayConfiguration{} + case "#Microsoft.Media.ContentKeyPolicyPlayReadyConfiguration": + b = &ContentKeyPolicyPlayReadyConfiguration{} + case "#Microsoft.Media.ContentKeyPolicyUnknownConfiguration": + b = &ContentKeyPolicyUnknownConfiguration{} + case "#Microsoft.Media.ContentKeyPolicyWidevineConfiguration": + b = &ContentKeyPolicyWidevineConfiguration{} + default: + b = &ContentKeyPolicyConfiguration{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalContentKeyPolicyConfigurationClassificationArray(rawMsg json.RawMessage) ([]ContentKeyPolicyConfigurationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ContentKeyPolicyConfigurationClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalContentKeyPolicyConfigurationClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalContentKeyPolicyPlayReadyContentKeyLocationClassification(rawMsg json.RawMessage) (ContentKeyPolicyPlayReadyContentKeyLocationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ContentKeyPolicyPlayReadyContentKeyLocationClassification + switch m["@odata.type"] { + case "#Microsoft.Media.ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader": + b = &ContentKeyPolicyPlayReadyContentEncryptionKeyFromHeader{} + case "#Microsoft.Media.ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier": + b = &ContentKeyPolicyPlayReadyContentEncryptionKeyFromKeyIdentifier{} + default: + b = &ContentKeyPolicyPlayReadyContentKeyLocation{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalContentKeyPolicyPlayReadyContentKeyLocationClassificationArray(rawMsg json.RawMessage) ([]ContentKeyPolicyPlayReadyContentKeyLocationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ContentKeyPolicyPlayReadyContentKeyLocationClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalContentKeyPolicyPlayReadyContentKeyLocationClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalContentKeyPolicyRestrictionClassification(rawMsg json.RawMessage) (ContentKeyPolicyRestrictionClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ContentKeyPolicyRestrictionClassification + switch m["@odata.type"] { + case "#Microsoft.Media.ContentKeyPolicyOpenRestriction": + b = &ContentKeyPolicyOpenRestriction{} + case "#Microsoft.Media.ContentKeyPolicyTokenRestriction": + b = &ContentKeyPolicyTokenRestriction{} + case "#Microsoft.Media.ContentKeyPolicyUnknownRestriction": + b = &ContentKeyPolicyUnknownRestriction{} + default: + b = &ContentKeyPolicyRestriction{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalContentKeyPolicyRestrictionClassificationArray(rawMsg json.RawMessage) ([]ContentKeyPolicyRestrictionClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ContentKeyPolicyRestrictionClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalContentKeyPolicyRestrictionClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalContentKeyPolicyRestrictionTokenKeyClassification(rawMsg json.RawMessage) (ContentKeyPolicyRestrictionTokenKeyClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ContentKeyPolicyRestrictionTokenKeyClassification + switch m["@odata.type"] { + case "#Microsoft.Media.ContentKeyPolicyRsaTokenKey": + b = &ContentKeyPolicyRsaTokenKey{} + case "#Microsoft.Media.ContentKeyPolicySymmetricTokenKey": + b = &ContentKeyPolicySymmetricTokenKey{} + case "#Microsoft.Media.ContentKeyPolicyX509CertificateTokenKey": + b = &ContentKeyPolicyX509CertificateTokenKey{} + default: + b = &ContentKeyPolicyRestrictionTokenKey{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalContentKeyPolicyRestrictionTokenKeyClassificationArray(rawMsg json.RawMessage) ([]ContentKeyPolicyRestrictionTokenKeyClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ContentKeyPolicyRestrictionTokenKeyClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalContentKeyPolicyRestrictionTokenKeyClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalFormatClassification(rawMsg json.RawMessage) (FormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FormatClassification + switch m["@odata.type"] { + case "#Microsoft.Media.ImageFormat": + b = &ImageFormat{} + case "#Microsoft.Media.JpgFormat": + b = &JpgFormat{} + case "#Microsoft.Media.Mp4Format": + b = &Mp4Format{} + case "#Microsoft.Media.MultiBitrateFormat": + b = &MultiBitrateFormat{} + case "#Microsoft.Media.PngFormat": + b = &PNGFormat{} + case "#Microsoft.Media.TransportStreamFormat": + b = &TransportStreamFormat{} + default: + b = &Format{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalFormatClassificationArray(rawMsg json.RawMessage) ([]FormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FormatClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFormatClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalH265VideoLayerClassification(rawMsg json.RawMessage) (H265VideoLayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b H265VideoLayerClassification + switch m["@odata.type"] { + case "#Microsoft.Media.H265Layer": + b = &H265Layer{} + default: + b = &H265VideoLayer{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalH265VideoLayerClassificationArray(rawMsg json.RawMessage) ([]H265VideoLayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]H265VideoLayerClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalH265VideoLayerClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalImageClassification(rawMsg json.RawMessage) (ImageClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ImageClassification + switch m["@odata.type"] { + case "#Microsoft.Media.JpgImage": + b = &JpgImage{} + case "#Microsoft.Media.PngImage": + b = &PNGImage{} + default: + b = &Image{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalImageClassificationArray(rawMsg json.RawMessage) ([]ImageClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ImageClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalImageClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalImageFormatClassification(rawMsg json.RawMessage) (ImageFormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ImageFormatClassification + switch m["@odata.type"] { + case "#Microsoft.Media.JpgFormat": + b = &JpgFormat{} + case "#Microsoft.Media.PngFormat": + b = &PNGFormat{} + default: + b = &ImageFormat{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalImageFormatClassificationArray(rawMsg json.RawMessage) ([]ImageFormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ImageFormatClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalImageFormatClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalInputDefinitionClassification(rawMsg json.RawMessage) (InputDefinitionClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b InputDefinitionClassification + switch m["@odata.type"] { + case "#Microsoft.Media.FromAllInputFile": + b = &FromAllInputFile{} + case "#Microsoft.Media.FromEachInputFile": + b = &FromEachInputFile{} + case "#Microsoft.Media.InputFile": + b = &InputFile{} + default: + b = &InputDefinition{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalInputDefinitionClassificationArray(rawMsg json.RawMessage) ([]InputDefinitionClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]InputDefinitionClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalInputDefinitionClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalJobInputClassification(rawMsg json.RawMessage) (JobInputClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b JobInputClassification + switch m["@odata.type"] { + case "#Microsoft.Media.JobInputAsset": + b = &JobInputAsset{} + case "#Microsoft.Media.JobInputClip": + b = &JobInputClip{} + case "#Microsoft.Media.JobInputHttp": + b = &JobInputHTTP{} + case "#Microsoft.Media.JobInputSequence": + b = &JobInputSequence{} + case "#Microsoft.Media.JobInputs": + b = &JobInputs{} + default: + b = &JobInput{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalJobInputClassificationArray(rawMsg json.RawMessage) ([]JobInputClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]JobInputClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalJobInputClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalJobInputClipClassification(rawMsg json.RawMessage) (JobInputClipClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b JobInputClipClassification + switch m["@odata.type"] { + case "#Microsoft.Media.JobInputAsset": + b = &JobInputAsset{} + case "#Microsoft.Media.JobInputHttp": + b = &JobInputHTTP{} + default: + b = &JobInputClip{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalJobInputClipClassificationArray(rawMsg json.RawMessage) ([]JobInputClipClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]JobInputClipClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalJobInputClipClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalJobOutputClassification(rawMsg json.RawMessage) (JobOutputClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b JobOutputClassification + switch m["@odata.type"] { + case "#Microsoft.Media.JobOutputAsset": + b = &JobOutputAsset{} + default: + b = &JobOutput{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalJobOutputClassificationArray(rawMsg json.RawMessage) ([]JobOutputClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]JobOutputClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalJobOutputClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalLayerClassification(rawMsg json.RawMessage) (LayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b LayerClassification + switch m["@odata.type"] { + case "#Microsoft.Media.H264Layer": + b = &H264Layer{} + case "#Microsoft.Media.H265Layer": + b = &H265Layer{} + case "#Microsoft.Media.H265VideoLayer": + b = &H265VideoLayer{} + case "#Microsoft.Media.JpgLayer": + b = &JpgLayer{} + case "#Microsoft.Media.PngLayer": + b = &PNGLayer{} + case "#Microsoft.Media.VideoLayer": + b = &VideoLayer{} + default: + b = &Layer{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalLayerClassificationArray(rawMsg json.RawMessage) ([]LayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]LayerClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalLayerClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalMultiBitrateFormatClassification(rawMsg json.RawMessage) (MultiBitrateFormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b MultiBitrateFormatClassification + switch m["@odata.type"] { + case "#Microsoft.Media.Mp4Format": + b = &Mp4Format{} + case "#Microsoft.Media.TransportStreamFormat": + b = &TransportStreamFormat{} + default: + b = &MultiBitrateFormat{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalMultiBitrateFormatClassificationArray(rawMsg json.RawMessage) ([]MultiBitrateFormatClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]MultiBitrateFormatClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalMultiBitrateFormatClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalOverlayClassification(rawMsg json.RawMessage) (OverlayClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b OverlayClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AudioOverlay": + b = &AudioOverlay{} + case "#Microsoft.Media.VideoOverlay": + b = &VideoOverlay{} + default: + b = &Overlay{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalOverlayClassificationArray(rawMsg json.RawMessage) ([]OverlayClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]OverlayClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalOverlayClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalPresetClassification(rawMsg json.RawMessage) (PresetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b PresetClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AudioAnalyzerPreset": + b = &AudioAnalyzerPreset{} + case "#Microsoft.Media.BuiltInStandardEncoderPreset": + b = &BuiltInStandardEncoderPreset{} + case "#Microsoft.Media.FaceDetectorPreset": + b = &FaceDetectorPreset{} + case "#Microsoft.Media.StandardEncoderPreset": + b = &StandardEncoderPreset{} + case "#Microsoft.Media.VideoAnalyzerPreset": + b = &VideoAnalyzerPreset{} + default: + b = &Preset{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalPresetClassificationArray(rawMsg json.RawMessage) ([]PresetClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]PresetClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalPresetClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalTrackDescriptorClassification(rawMsg json.RawMessage) (TrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b TrackDescriptorClassification + switch m["@odata.type"] { + case "#Microsoft.Media.AudioTrackDescriptor": + b = &AudioTrackDescriptor{} + case "#Microsoft.Media.SelectAudioTrackByAttribute": + b = &SelectAudioTrackByAttribute{} + case "#Microsoft.Media.SelectAudioTrackById": + b = &SelectAudioTrackByID{} + case "#Microsoft.Media.SelectVideoTrackByAttribute": + b = &SelectVideoTrackByAttribute{} + case "#Microsoft.Media.SelectVideoTrackById": + b = &SelectVideoTrackByID{} + case "#Microsoft.Media.VideoTrackDescriptor": + b = &VideoTrackDescriptor{} + default: + b = &TrackDescriptor{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalTrackDescriptorClassificationArray(rawMsg json.RawMessage) ([]TrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]TrackDescriptorClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalTrackDescriptorClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalVideoClassification(rawMsg json.RawMessage) (VideoClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b VideoClassification + switch m["@odata.type"] { + case "#Microsoft.Media.H264Video": + b = &H264Video{} + case "#Microsoft.Media.H265Video": + b = &H265Video{} + case "#Microsoft.Media.Image": + b = &Image{} + case "#Microsoft.Media.JpgImage": + b = &JpgImage{} + case "#Microsoft.Media.PngImage": + b = &PNGImage{} + default: + b = &Video{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalVideoClassificationArray(rawMsg json.RawMessage) ([]VideoClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]VideoClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalVideoClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalVideoLayerClassification(rawMsg json.RawMessage) (VideoLayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b VideoLayerClassification + switch m["@odata.type"] { + case "#Microsoft.Media.H264Layer": + b = &H264Layer{} + default: + b = &VideoLayer{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalVideoLayerClassificationArray(rawMsg json.RawMessage) ([]VideoLayerClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]VideoLayerClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalVideoLayerClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalVideoTrackDescriptorClassification(rawMsg json.RawMessage) (VideoTrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b VideoTrackDescriptorClassification + switch m["@odata.type"] { + case "#Microsoft.Media.SelectVideoTrackByAttribute": + b = &SelectVideoTrackByAttribute{} + case "#Microsoft.Media.SelectVideoTrackById": + b = &SelectVideoTrackByID{} + default: + b = &VideoTrackDescriptor{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalVideoTrackDescriptorClassificationArray(rawMsg json.RawMessage) ([]VideoTrackDescriptorClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]VideoTrackDescriptorClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalVideoTrackDescriptorClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privateendpointconnections_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privateendpointconnections_client.go new file mode 100644 index 000000000000..a8c00e4d3fff --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privateendpointconnections_client.go @@ -0,0 +1,298 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +func NewPrivateEndpointConnectionsClient(con *arm.Connection, subscriptionID string) *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Update private endpoint connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, name string, parameters PrivateEndpointConnection, options *PrivateEndpointConnectionsCreateOrUpdateOptions) (PrivateEndpointConnectionsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, name, parameters, options) + if err != nil { + return PrivateEndpointConnectionsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrivateEndpointConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, name string, parameters PrivateEndpointConnection, options *PrivateEndpointConnectionsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateEndpointConnections/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *PrivateEndpointConnectionsClient) createOrUpdateHandleResponse(resp *http.Response) (PrivateEndpointConnectionsCreateOrUpdateResponse, error) { + result := PrivateEndpointConnectionsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *PrivateEndpointConnectionsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Delete private endpoint connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateEndpointConnectionsDeleteOptions) (PrivateEndpointConnectionsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, name, options) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return PrivateEndpointConnectionsDeleteResponse{}, client.deleteHandleError(resp) + } + return PrivateEndpointConnectionsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateEndpointConnectionsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateEndpointConnections/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *PrivateEndpointConnectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get private endpoint connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateEndpointConnectionsGetOptions) (PrivateEndpointConnectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, name, options) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateEndpointConnectionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateEndpointConnections/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsGetResponse, error) { + result := PrivateEndpointConnectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateEndpointConnectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Get all private endpoint connections. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateEndpointConnectionsClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsListOptions) (PrivateEndpointConnectionsListResponse, error) { + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *PrivateEndpointConnectionsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateEndpointConnectionsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateEndpointConnectionsClient) listHandleResponse(resp *http.Response) (PrivateEndpointConnectionsListResponse, error) { + result := PrivateEndpointConnectionsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateEndpointConnectionsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privatelinkresources_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privatelinkresources_client.go new file mode 100644 index 000000000000..3f2956544409 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_privatelinkresources_client.go @@ -0,0 +1,169 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +func NewPrivateLinkResourcesClient(con *arm.Connection, subscriptionID string) *PrivateLinkResourcesClient { + return &PrivateLinkResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Get - Get group ID. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateLinkResourcesGetOptions) (PrivateLinkResourcesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, name, options) + if err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateLinkResourcesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateLinkResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, name string, options *PrivateLinkResourcesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateLinkResources/{name}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateLinkResourcesClient) getHandleResponse(resp *http.Response) (PrivateLinkResourcesGetResponse, error) { + result := PrivateLinkResourcesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResource); err != nil { + return PrivateLinkResourcesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateLinkResourcesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Get list of group IDs. +// If the operation fails it returns the *ErrorResponse error type. +func (client *PrivateLinkResourcesClient) List(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesListOptions) (PrivateLinkResourcesListResponse, error) { + req, err := client.listCreateRequest(ctx, resourceGroupName, accountName, options) + if err != nil { + return PrivateLinkResourcesListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateLinkResourcesListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateLinkResourcesListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *PrivateLinkResourcesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *PrivateLinkResourcesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *PrivateLinkResourcesClient) listHandleResponse(resp *http.Response) (PrivateLinkResourcesListResponse, error) { + result := PrivateLinkResourcesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourceListResult); err != nil { + return PrivateLinkResourcesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *PrivateLinkResourcesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_response_types.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_response_types.go new file mode 100644 index 000000000000..3544909512a5 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_response_types.go @@ -0,0 +1,1439 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// AccountFiltersCreateOrUpdateResponse contains the response from method AccountFilters.CreateOrUpdate. +type AccountFiltersCreateOrUpdateResponse struct { + AccountFiltersCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountFiltersCreateOrUpdateResult contains the result from method AccountFilters.CreateOrUpdate. +type AccountFiltersCreateOrUpdateResult struct { + AccountFilter +} + +// AccountFiltersDeleteResponse contains the response from method AccountFilters.Delete. +type AccountFiltersDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountFiltersGetResponse contains the response from method AccountFilters.Get. +type AccountFiltersGetResponse struct { + AccountFiltersGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountFiltersGetResult contains the result from method AccountFilters.Get. +type AccountFiltersGetResult struct { + AccountFilter +} + +// AccountFiltersListResponse contains the response from method AccountFilters.List. +type AccountFiltersListResponse struct { + AccountFiltersListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountFiltersListResult contains the result from method AccountFilters.List. +type AccountFiltersListResult struct { + AccountFilterCollection +} + +// AccountFiltersUpdateResponse contains the response from method AccountFilters.Update. +type AccountFiltersUpdateResponse struct { + AccountFiltersUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AccountFiltersUpdateResult contains the result from method AccountFilters.Update. +type AccountFiltersUpdateResult struct { + AccountFilter +} + +// AssetFiltersCreateOrUpdateResponse contains the response from method AssetFilters.CreateOrUpdate. +type AssetFiltersCreateOrUpdateResponse struct { + AssetFiltersCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetFiltersCreateOrUpdateResult contains the result from method AssetFilters.CreateOrUpdate. +type AssetFiltersCreateOrUpdateResult struct { + AssetFilter +} + +// AssetFiltersDeleteResponse contains the response from method AssetFilters.Delete. +type AssetFiltersDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetFiltersGetResponse contains the response from method AssetFilters.Get. +type AssetFiltersGetResponse struct { + AssetFiltersGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetFiltersGetResult contains the result from method AssetFilters.Get. +type AssetFiltersGetResult struct { + AssetFilter +} + +// AssetFiltersListResponse contains the response from method AssetFilters.List. +type AssetFiltersListResponse struct { + AssetFiltersListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetFiltersListResult contains the result from method AssetFilters.List. +type AssetFiltersListResult struct { + AssetFilterCollection +} + +// AssetFiltersUpdateResponse contains the response from method AssetFilters.Update. +type AssetFiltersUpdateResponse struct { + AssetFiltersUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetFiltersUpdateResult contains the result from method AssetFilters.Update. +type AssetFiltersUpdateResult struct { + AssetFilter +} + +// AssetsCreateOrUpdateResponse contains the response from method Assets.CreateOrUpdate. +type AssetsCreateOrUpdateResponse struct { + AssetsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsCreateOrUpdateResult contains the result from method Assets.CreateOrUpdate. +type AssetsCreateOrUpdateResult struct { + Asset +} + +// AssetsDeleteResponse contains the response from method Assets.Delete. +type AssetsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsGetEncryptionKeyResponse contains the response from method Assets.GetEncryptionKey. +type AssetsGetEncryptionKeyResponse struct { + AssetsGetEncryptionKeyResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsGetEncryptionKeyResult contains the result from method Assets.GetEncryptionKey. +type AssetsGetEncryptionKeyResult struct { + StorageEncryptedAssetDecryptionData +} + +// AssetsGetResponse contains the response from method Assets.Get. +type AssetsGetResponse struct { + AssetsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsGetResult contains the result from method Assets.Get. +type AssetsGetResult struct { + Asset +} + +// AssetsListContainerSasResponse contains the response from method Assets.ListContainerSas. +type AssetsListContainerSasResponse struct { + AssetsListContainerSasResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsListContainerSasResult contains the result from method Assets.ListContainerSas. +type AssetsListContainerSasResult struct { + AssetContainerSas +} + +// AssetsListResponse contains the response from method Assets.List. +type AssetsListResponse struct { + AssetsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsListResult contains the result from method Assets.List. +type AssetsListResult struct { + AssetCollection +} + +// AssetsListStreamingLocatorsResponse contains the response from method Assets.ListStreamingLocators. +type AssetsListStreamingLocatorsResponse struct { + AssetsListStreamingLocatorsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsListStreamingLocatorsResult contains the result from method Assets.ListStreamingLocators. +type AssetsListStreamingLocatorsResult struct { + ListStreamingLocatorsResponse +} + +// AssetsUpdateResponse contains the response from method Assets.Update. +type AssetsUpdateResponse struct { + AssetsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AssetsUpdateResult contains the result from method Assets.Update. +type AssetsUpdateResult struct { + Asset +} + +// ContentKeyPoliciesCreateOrUpdateResponse contains the response from method ContentKeyPolicies.CreateOrUpdate. +type ContentKeyPoliciesCreateOrUpdateResponse struct { + ContentKeyPoliciesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesCreateOrUpdateResult contains the result from method ContentKeyPolicies.CreateOrUpdate. +type ContentKeyPoliciesCreateOrUpdateResult struct { + ContentKeyPolicy +} + +// ContentKeyPoliciesDeleteResponse contains the response from method ContentKeyPolicies.Delete. +type ContentKeyPoliciesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse contains the response from method ContentKeyPolicies.GetPolicyPropertiesWithSecrets. +type ContentKeyPoliciesGetPolicyPropertiesWithSecretsResponse struct { + ContentKeyPoliciesGetPolicyPropertiesWithSecretsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesGetPolicyPropertiesWithSecretsResult contains the result from method ContentKeyPolicies.GetPolicyPropertiesWithSecrets. +type ContentKeyPoliciesGetPolicyPropertiesWithSecretsResult struct { + ContentKeyPolicyProperties +} + +// ContentKeyPoliciesGetResponse contains the response from method ContentKeyPolicies.Get. +type ContentKeyPoliciesGetResponse struct { + ContentKeyPoliciesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesGetResult contains the result from method ContentKeyPolicies.Get. +type ContentKeyPoliciesGetResult struct { + ContentKeyPolicy +} + +// ContentKeyPoliciesListResponse contains the response from method ContentKeyPolicies.List. +type ContentKeyPoliciesListResponse struct { + ContentKeyPoliciesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesListResult contains the result from method ContentKeyPolicies.List. +type ContentKeyPoliciesListResult struct { + ContentKeyPolicyCollection +} + +// ContentKeyPoliciesUpdateResponse contains the response from method ContentKeyPolicies.Update. +type ContentKeyPoliciesUpdateResponse struct { + ContentKeyPoliciesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ContentKeyPoliciesUpdateResult contains the result from method ContentKeyPolicies.Update. +type ContentKeyPoliciesUpdateResult struct { + ContentKeyPolicy +} + +// JobsCancelJobResponse contains the response from method Jobs.CancelJob. +type JobsCancelJobResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsCreateResponse contains the response from method Jobs.Create. +type JobsCreateResponse struct { + JobsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsCreateResult contains the result from method Jobs.Create. +type JobsCreateResult struct { + Job +} + +// JobsDeleteResponse contains the response from method Jobs.Delete. +type JobsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsGetResponse contains the response from method Jobs.Get. +type JobsGetResponse struct { + JobsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsGetResult contains the result from method Jobs.Get. +type JobsGetResult struct { + Job +} + +// JobsListResponse contains the response from method Jobs.List. +type JobsListResponse struct { + JobsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsListResult contains the result from method Jobs.List. +type JobsListResult struct { + JobCollection +} + +// JobsUpdateResponse contains the response from method Jobs.Update. +type JobsUpdateResponse struct { + JobsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsUpdateResult contains the result from method Jobs.Update. +type JobsUpdateResult struct { + Job +} + +// LiveEventsAllocatePollerResponse contains the response from method LiveEvents.Allocate. +type LiveEventsAllocatePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsAllocatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsAllocatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsAllocateResponse, error) { + respType := LiveEventsAllocateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsAllocatePollerResponse from the provided client and resume token. +func (l *LiveEventsAllocatePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Allocate", token, client.pl, client.allocateHandleError) + if err != nil { + return err + } + poller := &LiveEventsAllocatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsAllocateResponse contains the response from method LiveEvents.Allocate. +type LiveEventsAllocateResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsCreatePollerResponse contains the response from method LiveEvents.Create. +type LiveEventsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsCreateResponse, error) { + respType := LiveEventsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.LiveEvent) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsCreatePollerResponse from the provided client and resume token. +func (l *LiveEventsCreatePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &LiveEventsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsCreateResponse contains the response from method LiveEvents.Create. +type LiveEventsCreateResponse struct { + LiveEventsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsCreateResult contains the result from method LiveEvents.Create. +type LiveEventsCreateResult struct { + LiveEvent +} + +// LiveEventsDeletePollerResponse contains the response from method LiveEvents.Delete. +type LiveEventsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsDeleteResponse, error) { + respType := LiveEventsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsDeletePollerResponse from the provided client and resume token. +func (l *LiveEventsDeletePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &LiveEventsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsDeleteResponse contains the response from method LiveEvents.Delete. +type LiveEventsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsGetResponse contains the response from method LiveEvents.Get. +type LiveEventsGetResponse struct { + LiveEventsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsGetResult contains the result from method LiveEvents.Get. +type LiveEventsGetResult struct { + LiveEvent +} + +// LiveEventsListResponse contains the response from method LiveEvents.List. +type LiveEventsListResponse struct { + LiveEventsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsListResult contains the result from method LiveEvents.List. +type LiveEventsListResult struct { + LiveEventListResult +} + +// LiveEventsResetPollerResponse contains the response from method LiveEvents.Reset. +type LiveEventsResetPollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsResetPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsResetPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsResetResponse, error) { + respType := LiveEventsResetResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsResetPollerResponse from the provided client and resume token. +func (l *LiveEventsResetPollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Reset", token, client.pl, client.resetHandleError) + if err != nil { + return err + } + poller := &LiveEventsResetPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsResetResponse contains the response from method LiveEvents.Reset. +type LiveEventsResetResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsStartPollerResponse contains the response from method LiveEvents.Start. +type LiveEventsStartPollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsStartPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsStartPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsStartResponse, error) { + respType := LiveEventsStartResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsStartPollerResponse from the provided client and resume token. +func (l *LiveEventsStartPollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Start", token, client.pl, client.startHandleError) + if err != nil { + return err + } + poller := &LiveEventsStartPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsStartResponse contains the response from method LiveEvents.Start. +type LiveEventsStartResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsStopPollerResponse contains the response from method LiveEvents.Stop. +type LiveEventsStopPollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsStopPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsStopPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsStopResponse, error) { + respType := LiveEventsStopResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsStopPollerResponse from the provided client and resume token. +func (l *LiveEventsStopPollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Stop", token, client.pl, client.stopHandleError) + if err != nil { + return err + } + poller := &LiveEventsStopPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsStopResponse contains the response from method LiveEvents.Stop. +type LiveEventsStopResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsUpdatePollerResponse contains the response from method LiveEvents.Update. +type LiveEventsUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveEventsUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveEventsUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveEventsUpdateResponse, error) { + respType := LiveEventsUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.LiveEvent) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveEventsUpdatePollerResponse from the provided client and resume token. +func (l *LiveEventsUpdatePollerResponse) Resume(ctx context.Context, client *LiveEventsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveEventsClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &LiveEventsUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveEventsUpdateResponse contains the response from method LiveEvents.Update. +type LiveEventsUpdateResponse struct { + LiveEventsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveEventsUpdateResult contains the result from method LiveEvents.Update. +type LiveEventsUpdateResult struct { + LiveEvent +} + +// LiveOutputsCreatePollerResponse contains the response from method LiveOutputs.Create. +type LiveOutputsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveOutputsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveOutputsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveOutputsCreateResponse, error) { + respType := LiveOutputsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.LiveOutput) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveOutputsCreatePollerResponse from the provided client and resume token. +func (l *LiveOutputsCreatePollerResponse) Resume(ctx context.Context, client *LiveOutputsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveOutputsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &LiveOutputsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveOutputsCreateResponse contains the response from method LiveOutputs.Create. +type LiveOutputsCreateResponse struct { + LiveOutputsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveOutputsCreateResult contains the result from method LiveOutputs.Create. +type LiveOutputsCreateResult struct { + LiveOutput +} + +// LiveOutputsDeletePollerResponse contains the response from method LiveOutputs.Delete. +type LiveOutputsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *LiveOutputsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l LiveOutputsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (LiveOutputsDeleteResponse, error) { + respType := LiveOutputsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a LiveOutputsDeletePollerResponse from the provided client and resume token. +func (l *LiveOutputsDeletePollerResponse) Resume(ctx context.Context, client *LiveOutputsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("LiveOutputsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &LiveOutputsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// LiveOutputsDeleteResponse contains the response from method LiveOutputs.Delete. +type LiveOutputsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveOutputsGetResponse contains the response from method LiveOutputs.Get. +type LiveOutputsGetResponse struct { + LiveOutputsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveOutputsGetResult contains the result from method LiveOutputs.Get. +type LiveOutputsGetResult struct { + LiveOutput +} + +// LiveOutputsListResponse contains the response from method LiveOutputs.List. +type LiveOutputsListResponse struct { + LiveOutputsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LiveOutputsListResult contains the result from method LiveOutputs.List. +type LiveOutputsListResult struct { + LiveOutputListResult +} + +// LocationsCheckNameAvailabilityResponse contains the response from method Locations.CheckNameAvailability. +type LocationsCheckNameAvailabilityResponse struct { + LocationsCheckNameAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// LocationsCheckNameAvailabilityResult contains the result from method Locations.CheckNameAvailability. +type LocationsCheckNameAvailabilityResult struct { + EntityNameAvailabilityCheckOutput +} + +// MediaservicesCreateOrUpdateResponse contains the response from method Mediaservices.CreateOrUpdate. +type MediaservicesCreateOrUpdateResponse struct { + MediaservicesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesCreateOrUpdateResult contains the result from method Mediaservices.CreateOrUpdate. +type MediaservicesCreateOrUpdateResult struct { + MediaService +} + +// MediaservicesDeleteResponse contains the response from method Mediaservices.Delete. +type MediaservicesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesGetResponse contains the response from method Mediaservices.Get. +type MediaservicesGetResponse struct { + MediaservicesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesGetResult contains the result from method Mediaservices.Get. +type MediaservicesGetResult struct { + MediaService +} + +// MediaservicesListBySubscriptionResponse contains the response from method Mediaservices.ListBySubscription. +type MediaservicesListBySubscriptionResponse struct { + MediaservicesListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesListBySubscriptionResult contains the result from method Mediaservices.ListBySubscription. +type MediaservicesListBySubscriptionResult struct { + MediaServiceCollection +} + +// MediaservicesListEdgePoliciesResponse contains the response from method Mediaservices.ListEdgePolicies. +type MediaservicesListEdgePoliciesResponse struct { + MediaservicesListEdgePoliciesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesListEdgePoliciesResult contains the result from method Mediaservices.ListEdgePolicies. +type MediaservicesListEdgePoliciesResult struct { + EdgePolicies +} + +// MediaservicesListResponse contains the response from method Mediaservices.List. +type MediaservicesListResponse struct { + MediaservicesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesListResult contains the result from method Mediaservices.List. +type MediaservicesListResult struct { + MediaServiceCollection +} + +// MediaservicesSyncStorageKeysResponse contains the response from method Mediaservices.SyncStorageKeys. +type MediaservicesSyncStorageKeysResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesUpdateResponse contains the response from method Mediaservices.Update. +type MediaservicesUpdateResponse struct { + MediaservicesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// MediaservicesUpdateResult contains the result from method Mediaservices.Update. +type MediaservicesUpdateResult struct { + MediaService +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationCollection +} + +// PrivateEndpointConnectionsCreateOrUpdateResponse contains the response from method PrivateEndpointConnections.CreateOrUpdate. +type PrivateEndpointConnectionsCreateOrUpdateResponse struct { + PrivateEndpointConnectionsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsCreateOrUpdateResult contains the result from method PrivateEndpointConnections.CreateOrUpdate. +type PrivateEndpointConnectionsCreateOrUpdateResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsDeleteResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResponse contains the response from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResponse struct { + PrivateEndpointConnectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResult contains the result from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsListResponse contains the response from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResponse struct { + PrivateEndpointConnectionsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsListResult contains the result from method PrivateEndpointConnections.List. +type PrivateEndpointConnectionsListResult struct { + PrivateEndpointConnectionListResult +} + +// PrivateLinkResourcesGetResponse contains the response from method PrivateLinkResources.Get. +type PrivateLinkResourcesGetResponse struct { + PrivateLinkResourcesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesGetResult contains the result from method PrivateLinkResources.Get. +type PrivateLinkResourcesGetResult struct { + PrivateLinkResource +} + +// PrivateLinkResourcesListResponse contains the response from method PrivateLinkResources.List. +type PrivateLinkResourcesListResponse struct { + PrivateLinkResourcesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesListResult contains the result from method PrivateLinkResources.List. +type PrivateLinkResourcesListResult struct { + PrivateLinkResourceListResult +} + +// StreamingEndpointsCreatePollerResponse contains the response from method StreamingEndpoints.Create. +type StreamingEndpointsCreatePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsCreatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsCreatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsCreateResponse, error) { + respType := StreamingEndpointsCreateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.StreamingEndpoint) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsCreatePollerResponse from the provided client and resume token. +func (l *StreamingEndpointsCreatePollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Create", token, client.pl, client.createHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsCreatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsCreateResponse contains the response from method StreamingEndpoints.Create. +type StreamingEndpointsCreateResponse struct { + StreamingEndpointsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsCreateResult contains the result from method StreamingEndpoints.Create. +type StreamingEndpointsCreateResult struct { + StreamingEndpoint +} + +// StreamingEndpointsDeletePollerResponse contains the response from method StreamingEndpoints.Delete. +type StreamingEndpointsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsDeleteResponse, error) { + respType := StreamingEndpointsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsDeletePollerResponse from the provided client and resume token. +func (l *StreamingEndpointsDeletePollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsDeleteResponse contains the response from method StreamingEndpoints.Delete. +type StreamingEndpointsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsGetResponse contains the response from method StreamingEndpoints.Get. +type StreamingEndpointsGetResponse struct { + StreamingEndpointsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsGetResult contains the result from method StreamingEndpoints.Get. +type StreamingEndpointsGetResult struct { + StreamingEndpoint +} + +// StreamingEndpointsListResponse contains the response from method StreamingEndpoints.List. +type StreamingEndpointsListResponse struct { + StreamingEndpointsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsListResult contains the result from method StreamingEndpoints.List. +type StreamingEndpointsListResult struct { + StreamingEndpointListResult +} + +// StreamingEndpointsScalePollerResponse contains the response from method StreamingEndpoints.Scale. +type StreamingEndpointsScalePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsScalePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsScalePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsScaleResponse, error) { + respType := StreamingEndpointsScaleResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsScalePollerResponse from the provided client and resume token. +func (l *StreamingEndpointsScalePollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Scale", token, client.pl, client.scaleHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsScalePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsScaleResponse contains the response from method StreamingEndpoints.Scale. +type StreamingEndpointsScaleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsStartPollerResponse contains the response from method StreamingEndpoints.Start. +type StreamingEndpointsStartPollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsStartPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsStartPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsStartResponse, error) { + respType := StreamingEndpointsStartResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsStartPollerResponse from the provided client and resume token. +func (l *StreamingEndpointsStartPollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Start", token, client.pl, client.startHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsStartPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsStartResponse contains the response from method StreamingEndpoints.Start. +type StreamingEndpointsStartResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsStopPollerResponse contains the response from method StreamingEndpoints.Stop. +type StreamingEndpointsStopPollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsStopPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsStopPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsStopResponse, error) { + respType := StreamingEndpointsStopResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsStopPollerResponse from the provided client and resume token. +func (l *StreamingEndpointsStopPollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Stop", token, client.pl, client.stopHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsStopPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsStopResponse contains the response from method StreamingEndpoints.Stop. +type StreamingEndpointsStopResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsUpdatePollerResponse contains the response from method StreamingEndpoints.Update. +type StreamingEndpointsUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingEndpointsUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingEndpointsUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingEndpointsUpdateResponse, error) { + respType := StreamingEndpointsUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.StreamingEndpoint) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingEndpointsUpdatePollerResponse from the provided client and resume token. +func (l *StreamingEndpointsUpdatePollerResponse) Resume(ctx context.Context, client *StreamingEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingEndpointsClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &StreamingEndpointsUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingEndpointsUpdateResponse contains the response from method StreamingEndpoints.Update. +type StreamingEndpointsUpdateResponse struct { + StreamingEndpointsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingEndpointsUpdateResult contains the result from method StreamingEndpoints.Update. +type StreamingEndpointsUpdateResult struct { + StreamingEndpoint +} + +// StreamingLocatorsCreateResponse contains the response from method StreamingLocators.Create. +type StreamingLocatorsCreateResponse struct { + StreamingLocatorsCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsCreateResult contains the result from method StreamingLocators.Create. +type StreamingLocatorsCreateResult struct { + StreamingLocator +} + +// StreamingLocatorsDeleteResponse contains the response from method StreamingLocators.Delete. +type StreamingLocatorsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsGetResponse contains the response from method StreamingLocators.Get. +type StreamingLocatorsGetResponse struct { + StreamingLocatorsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsGetResult contains the result from method StreamingLocators.Get. +type StreamingLocatorsGetResult struct { + StreamingLocator +} + +// StreamingLocatorsListContentKeysResponse contains the response from method StreamingLocators.ListContentKeys. +type StreamingLocatorsListContentKeysResponse struct { + StreamingLocatorsListContentKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsListContentKeysResult contains the result from method StreamingLocators.ListContentKeys. +type StreamingLocatorsListContentKeysResult struct { + ListContentKeysResponse +} + +// StreamingLocatorsListPathsResponse contains the response from method StreamingLocators.ListPaths. +type StreamingLocatorsListPathsResponse struct { + StreamingLocatorsListPathsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsListPathsResult contains the result from method StreamingLocators.ListPaths. +type StreamingLocatorsListPathsResult struct { + ListPathsResponse +} + +// StreamingLocatorsListResponse contains the response from method StreamingLocators.List. +type StreamingLocatorsListResponse struct { + StreamingLocatorsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingLocatorsListResult contains the result from method StreamingLocators.List. +type StreamingLocatorsListResult struct { + StreamingLocatorCollection +} + +// StreamingPoliciesCreateResponse contains the response from method StreamingPolicies.Create. +type StreamingPoliciesCreateResponse struct { + StreamingPoliciesCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingPoliciesCreateResult contains the result from method StreamingPolicies.Create. +type StreamingPoliciesCreateResult struct { + StreamingPolicy +} + +// StreamingPoliciesDeleteResponse contains the response from method StreamingPolicies.Delete. +type StreamingPoliciesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingPoliciesGetResponse contains the response from method StreamingPolicies.Get. +type StreamingPoliciesGetResponse struct { + StreamingPoliciesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingPoliciesGetResult contains the result from method StreamingPolicies.Get. +type StreamingPoliciesGetResult struct { + StreamingPolicy +} + +// StreamingPoliciesListResponse contains the response from method StreamingPolicies.List. +type StreamingPoliciesListResponse struct { + StreamingPoliciesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingPoliciesListResult contains the result from method StreamingPolicies.List. +type StreamingPoliciesListResult struct { + StreamingPolicyCollection +} + +// TransformsCreateOrUpdateResponse contains the response from method Transforms.CreateOrUpdate. +type TransformsCreateOrUpdateResponse struct { + TransformsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformsCreateOrUpdateResult contains the result from method Transforms.CreateOrUpdate. +type TransformsCreateOrUpdateResult struct { + Transform +} + +// TransformsDeleteResponse contains the response from method Transforms.Delete. +type TransformsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformsGetResponse contains the response from method Transforms.Get. +type TransformsGetResponse struct { + TransformsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformsGetResult contains the result from method Transforms.Get. +type TransformsGetResult struct { + Transform +} + +// TransformsListResponse contains the response from method Transforms.List. +type TransformsListResponse struct { + TransformsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformsListResult contains the result from method Transforms.List. +type TransformsListResult struct { + TransformCollection +} + +// TransformsUpdateResponse contains the response from method Transforms.Update. +type TransformsUpdateResponse struct { + TransformsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformsUpdateResult contains the result from method Transforms.Update. +type TransformsUpdateResult struct { + Transform +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingendpoints_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingendpoints_client.go new file mode 100644 index 000000000000..9af6acc7c078 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingendpoints_client.go @@ -0,0 +1,651 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// StreamingEndpointsClient contains the methods for the StreamingEndpoints group. +// Don't use this type directly, use NewStreamingEndpointsClient() instead. +type StreamingEndpointsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewStreamingEndpointsClient creates a new instance of StreamingEndpointsClient with the specified values. +func NewStreamingEndpointsClient(con *arm.Connection, subscriptionID string) *StreamingEndpointsClient { + return &StreamingEndpointsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreate - Creates a streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginCreate(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginCreateOptions) (StreamingEndpointsCreatePollerResponse, error) { + resp, err := client.create(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return StreamingEndpointsCreatePollerResponse{}, err + } + result := StreamingEndpointsCreatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Create", "", resp, client.pl, client.createHandleError) + if err != nil { + return StreamingEndpointsCreatePollerResponse{}, err + } + result.Poller = &StreamingEndpointsCreatePoller{ + pt: pt, + } + return result, nil +} + +// Create - Creates a streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) create(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginCreateOptions) (*http.Response, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createHandleError(resp) + } + return resp, nil +} + +// createCreateRequest creates the Create request. +func (client *StreamingEndpointsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.AutoStart != nil { + reqQP.Set("autoStart", strconv.FormatBool(*options.AutoStart)) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleError handles the Create error response. +func (client *StreamingEndpointsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes a streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginDelete(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginDeleteOptions) (StreamingEndpointsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return StreamingEndpointsDeletePollerResponse{}, err + } + result := StreamingEndpointsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return StreamingEndpointsDeletePollerResponse{}, err + } + result.Poller = &StreamingEndpointsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) deleteOperation(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StreamingEndpointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *StreamingEndpointsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets a streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) Get(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsGetOptions) (StreamingEndpointsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return StreamingEndpointsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingEndpointsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingEndpointsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *StreamingEndpointsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StreamingEndpointsClient) getHandleResponse(resp *http.Response) (StreamingEndpointsGetResponse, error) { + result := StreamingEndpointsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingEndpoint); err != nil { + return StreamingEndpointsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *StreamingEndpointsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the streaming endpoints in the account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) List(resourceGroupName string, accountName string, options *StreamingEndpointsListOptions) *StreamingEndpointsListPager { + return &StreamingEndpointsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp StreamingEndpointsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StreamingEndpointListResult.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *StreamingEndpointsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *StreamingEndpointsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StreamingEndpointsClient) listHandleResponse(resp *http.Response) (StreamingEndpointsListResponse, error) { + result := StreamingEndpointsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingEndpointListResult); err != nil { + return StreamingEndpointsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *StreamingEndpointsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginScale - Scales an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginScale(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEntityScaleUnit, options *StreamingEndpointsBeginScaleOptions) (StreamingEndpointsScalePollerResponse, error) { + resp, err := client.scale(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return StreamingEndpointsScalePollerResponse{}, err + } + result := StreamingEndpointsScalePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Scale", "", resp, client.pl, client.scaleHandleError) + if err != nil { + return StreamingEndpointsScalePollerResponse{}, err + } + result.Poller = &StreamingEndpointsScalePoller{ + pt: pt, + } + return result, nil +} + +// Scale - Scales an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) scale(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEntityScaleUnit, options *StreamingEndpointsBeginScaleOptions) (*http.Response, error) { + req, err := client.scaleCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.scaleHandleError(resp) + } + return resp, nil +} + +// scaleCreateRequest creates the Scale request. +func (client *StreamingEndpointsClient) scaleCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEntityScaleUnit, options *StreamingEndpointsBeginScaleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}/scale" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// scaleHandleError handles the Scale error response. +func (client *StreamingEndpointsClient) scaleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStart - Starts an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginStart(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStartOptions) (StreamingEndpointsStartPollerResponse, error) { + resp, err := client.start(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return StreamingEndpointsStartPollerResponse{}, err + } + result := StreamingEndpointsStartPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Start", "", resp, client.pl, client.startHandleError) + if err != nil { + return StreamingEndpointsStartPollerResponse{}, err + } + result.Poller = &StreamingEndpointsStartPoller{ + pt: pt, + } + return result, nil +} + +// Start - Starts an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) start(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStartOptions) (*http.Response, error) { + req, err := client.startCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.startHandleError(resp) + } + return resp, nil +} + +// startCreateRequest creates the Start request. +func (client *StreamingEndpointsClient) startCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// startHandleError handles the Start error response. +func (client *StreamingEndpointsClient) startHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStop - Stops an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginStop(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStopOptions) (StreamingEndpointsStopPollerResponse, error) { + resp, err := client.stop(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return StreamingEndpointsStopPollerResponse{}, err + } + result := StreamingEndpointsStopPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Stop", "", resp, client.pl, client.stopHandleError) + if err != nil { + return StreamingEndpointsStopPollerResponse{}, err + } + result.Poller = &StreamingEndpointsStopPoller{ + pt: pt, + } + return result, nil +} + +// Stop - Stops an existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) stop(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStopOptions) (*http.Response, error) { + req, err := client.stopCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.stopHandleError(resp) + } + return resp, nil +} + +// stopCreateRequest creates the Stop request. +func (client *StreamingEndpointsClient) stopCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, options *StreamingEndpointsBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}/stop" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// stopHandleError handles the Stop error response. +func (client *StreamingEndpointsClient) stopHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates a existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) BeginUpdate(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginUpdateOptions) (StreamingEndpointsUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return StreamingEndpointsUpdatePollerResponse{}, err + } + result := StreamingEndpointsUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingEndpointsClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return StreamingEndpointsUpdatePollerResponse{}, err + } + result.Poller = &StreamingEndpointsUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates a existing streaming endpoint. +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingEndpointsClient) update(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, streamingEndpointName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *StreamingEndpointsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingEndpointName string, parameters StreamingEndpoint, options *StreamingEndpointsBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaservices/{accountName}/streamingEndpoints/{streamingEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingEndpointName == "" { + return nil, errors.New("parameter streamingEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingEndpointName}", url.PathEscape(streamingEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleError handles the Update error response. +func (client *StreamingEndpointsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streaminglocators_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streaminglocators_client.go new file mode 100644 index 000000000000..bcecdc9f0691 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streaminglocators_client.go @@ -0,0 +1,443 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// StreamingLocatorsClient contains the methods for the StreamingLocators group. +// Don't use this type directly, use NewStreamingLocatorsClient() instead. +type StreamingLocatorsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewStreamingLocatorsClient creates a new instance of StreamingLocatorsClient with the specified values. +func NewStreamingLocatorsClient(con *arm.Connection, subscriptionID string) *StreamingLocatorsClient { + return &StreamingLocatorsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Create - Create a Streaming Locator in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) Create(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, parameters StreamingLocator, options *StreamingLocatorsCreateOptions) (StreamingLocatorsCreateResponse, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, streamingLocatorName, parameters, options) + if err != nil { + return StreamingLocatorsCreateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingLocatorsCreateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusCreated) { + return StreamingLocatorsCreateResponse{}, client.createHandleError(resp) + } + return client.createHandleResponse(resp) +} + +// createCreateRequest creates the Create request. +func (client *StreamingLocatorsClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, parameters StreamingLocator, options *StreamingLocatorsCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators/{streamingLocatorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingLocatorName == "" { + return nil, errors.New("parameter streamingLocatorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingLocatorName}", url.PathEscape(streamingLocatorName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleResponse handles the Create response. +func (client *StreamingLocatorsClient) createHandleResponse(resp *http.Response) (StreamingLocatorsCreateResponse, error) { + result := StreamingLocatorsCreateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingLocator); err != nil { + return StreamingLocatorsCreateResponse{}, err + } + return result, nil +} + +// createHandleError handles the Create error response. +func (client *StreamingLocatorsClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Streaming Locator in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsDeleteOptions) (StreamingLocatorsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, streamingLocatorName, options) + if err != nil { + return StreamingLocatorsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingLocatorsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return StreamingLocatorsDeleteResponse{}, client.deleteHandleError(resp) + } + return StreamingLocatorsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StreamingLocatorsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators/{streamingLocatorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingLocatorName == "" { + return nil, errors.New("parameter streamingLocatorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingLocatorName}", url.PathEscape(streamingLocatorName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *StreamingLocatorsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of a Streaming Locator in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) Get(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsGetOptions) (StreamingLocatorsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, streamingLocatorName, options) + if err != nil { + return StreamingLocatorsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingLocatorsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingLocatorsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *StreamingLocatorsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators/{streamingLocatorName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingLocatorName == "" { + return nil, errors.New("parameter streamingLocatorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingLocatorName}", url.PathEscape(streamingLocatorName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StreamingLocatorsClient) getHandleResponse(resp *http.Response) (StreamingLocatorsGetResponse, error) { + result := StreamingLocatorsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingLocator); err != nil { + return StreamingLocatorsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *StreamingLocatorsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the Streaming Locators in the account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) List(resourceGroupName string, accountName string, options *StreamingLocatorsListOptions) *StreamingLocatorsListPager { + return &StreamingLocatorsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp StreamingLocatorsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StreamingLocatorCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *StreamingLocatorsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *StreamingLocatorsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StreamingLocatorsClient) listHandleResponse(resp *http.Response) (StreamingLocatorsListResponse, error) { + result := StreamingLocatorsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingLocatorCollection); err != nil { + return StreamingLocatorsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *StreamingLocatorsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListContentKeys - List Content Keys used by this Streaming Locator +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) ListContentKeys(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsListContentKeysOptions) (StreamingLocatorsListContentKeysResponse, error) { + req, err := client.listContentKeysCreateRequest(ctx, resourceGroupName, accountName, streamingLocatorName, options) + if err != nil { + return StreamingLocatorsListContentKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingLocatorsListContentKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingLocatorsListContentKeysResponse{}, client.listContentKeysHandleError(resp) + } + return client.listContentKeysHandleResponse(resp) +} + +// listContentKeysCreateRequest creates the ListContentKeys request. +func (client *StreamingLocatorsClient) listContentKeysCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsListContentKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators/{streamingLocatorName}/listContentKeys" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingLocatorName == "" { + return nil, errors.New("parameter streamingLocatorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingLocatorName}", url.PathEscape(streamingLocatorName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listContentKeysHandleResponse handles the ListContentKeys response. +func (client *StreamingLocatorsClient) listContentKeysHandleResponse(resp *http.Response) (StreamingLocatorsListContentKeysResponse, error) { + result := StreamingLocatorsListContentKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ListContentKeysResponse); err != nil { + return StreamingLocatorsListContentKeysResponse{}, err + } + return result, nil +} + +// listContentKeysHandleError handles the ListContentKeys error response. +func (client *StreamingLocatorsClient) listContentKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListPaths - List Paths supported by this Streaming Locator +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingLocatorsClient) ListPaths(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsListPathsOptions) (StreamingLocatorsListPathsResponse, error) { + req, err := client.listPathsCreateRequest(ctx, resourceGroupName, accountName, streamingLocatorName, options) + if err != nil { + return StreamingLocatorsListPathsResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingLocatorsListPathsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingLocatorsListPathsResponse{}, client.listPathsHandleError(resp) + } + return client.listPathsHandleResponse(resp) +} + +// listPathsCreateRequest creates the ListPaths request. +func (client *StreamingLocatorsClient) listPathsCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingLocatorName string, options *StreamingLocatorsListPathsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingLocators/{streamingLocatorName}/listPaths" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingLocatorName == "" { + return nil, errors.New("parameter streamingLocatorName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingLocatorName}", url.PathEscape(streamingLocatorName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listPathsHandleResponse handles the ListPaths response. +func (client *StreamingLocatorsClient) listPathsHandleResponse(resp *http.Response) (StreamingLocatorsListPathsResponse, error) { + result := StreamingLocatorsListPathsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ListPathsResponse); err != nil { + return StreamingLocatorsListPathsResponse{}, err + } + return result, nil +} + +// listPathsHandleError handles the ListPaths error response. +func (client *StreamingLocatorsClient) listPathsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingpolicies_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingpolicies_client.go new file mode 100644 index 000000000000..7625d1c9e153 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_streamingpolicies_client.go @@ -0,0 +1,305 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// StreamingPoliciesClient contains the methods for the StreamingPolicies group. +// Don't use this type directly, use NewStreamingPoliciesClient() instead. +type StreamingPoliciesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewStreamingPoliciesClient creates a new instance of StreamingPoliciesClient with the specified values. +func NewStreamingPoliciesClient(con *arm.Connection, subscriptionID string) *StreamingPoliciesClient { + return &StreamingPoliciesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Create - Create a Streaming Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingPoliciesClient) Create(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, parameters StreamingPolicy, options *StreamingPoliciesCreateOptions) (StreamingPoliciesCreateResponse, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, accountName, streamingPolicyName, parameters, options) + if err != nil { + return StreamingPoliciesCreateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingPoliciesCreateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusCreated) { + return StreamingPoliciesCreateResponse{}, client.createHandleError(resp) + } + return client.createHandleResponse(resp) +} + +// createCreateRequest creates the Create request. +func (client *StreamingPoliciesClient) createCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, parameters StreamingPolicy, options *StreamingPoliciesCreateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingPolicies/{streamingPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingPolicyName == "" { + return nil, errors.New("parameter streamingPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingPolicyName}", url.PathEscape(streamingPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createHandleResponse handles the Create response. +func (client *StreamingPoliciesClient) createHandleResponse(resp *http.Response) (StreamingPoliciesCreateResponse, error) { + result := StreamingPoliciesCreateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingPolicy); err != nil { + return StreamingPoliciesCreateResponse{}, err + } + return result, nil +} + +// createHandleError handles the Create error response. +func (client *StreamingPoliciesClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Streaming Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingPoliciesClient) Delete(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, options *StreamingPoliciesDeleteOptions) (StreamingPoliciesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, streamingPolicyName, options) + if err != nil { + return StreamingPoliciesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingPoliciesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return StreamingPoliciesDeleteResponse{}, client.deleteHandleError(resp) + } + return StreamingPoliciesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StreamingPoliciesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, options *StreamingPoliciesDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingPolicies/{streamingPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingPolicyName == "" { + return nil, errors.New("parameter streamingPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingPolicyName}", url.PathEscape(streamingPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *StreamingPoliciesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Get the details of a Streaming Policy in the Media Services account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingPoliciesClient) Get(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, options *StreamingPoliciesGetOptions) (StreamingPoliciesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, streamingPolicyName, options) + if err != nil { + return StreamingPoliciesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingPoliciesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingPoliciesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *StreamingPoliciesClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, streamingPolicyName string, options *StreamingPoliciesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingPolicies/{streamingPolicyName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if streamingPolicyName == "" { + return nil, errors.New("parameter streamingPolicyName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{streamingPolicyName}", url.PathEscape(streamingPolicyName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StreamingPoliciesClient) getHandleResponse(resp *http.Response) (StreamingPoliciesGetResponse, error) { + result := StreamingPoliciesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingPolicy); err != nil { + return StreamingPoliciesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *StreamingPoliciesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the Streaming Policies in the account +// If the operation fails it returns the *ErrorResponse error type. +func (client *StreamingPoliciesClient) List(resourceGroupName string, accountName string, options *StreamingPoliciesListOptions) *StreamingPoliciesListPager { + return &StreamingPoliciesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp StreamingPoliciesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StreamingPolicyCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *StreamingPoliciesClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *StreamingPoliciesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingPolicies" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StreamingPoliciesClient) listHandleResponse(resp *http.Response) (StreamingPoliciesListResponse, error) { + result := StreamingPoliciesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingPolicyCollection); err != nil { + return StreamingPoliciesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *StreamingPoliciesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_time_rfc3339.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..44240b77addf --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_transforms_client.go b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_transforms_client.go new file mode 100644 index 000000000000..55547feef6b7 --- /dev/null +++ b/sdk/resourcemanager/mediaservices/armmediaservices/zz_generated_transforms_client.go @@ -0,0 +1,370 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armmediaservices + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// TransformsClient contains the methods for the Transforms group. +// Don't use this type directly, use NewTransformsClient() instead. +type TransformsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewTransformsClient creates a new instance of TransformsClient with the specified values. +func NewTransformsClient(con *arm.Connection, subscriptionID string) *TransformsClient { + return &TransformsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates a new Transform. +// If the operation fails it returns the *ErrorResponse error type. +func (client *TransformsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, accountName string, transformName string, parameters Transform, options *TransformsCreateOrUpdateOptions) (TransformsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, accountName, transformName, parameters, options) + if err != nil { + return TransformsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return TransformsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *TransformsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, parameters Transform, options *TransformsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *TransformsClient) createOrUpdateHandleResponse(resp *http.Response) (TransformsCreateOrUpdateResponse, error) { + result := TransformsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Transform); err != nil { + return TransformsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *TransformsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a Transform. +// If the operation fails it returns the *ErrorResponse error type. +func (client *TransformsClient) Delete(ctx context.Context, resourceGroupName string, accountName string, transformName string, options *TransformsDeleteOptions) (TransformsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, accountName, transformName, options) + if err != nil { + return TransformsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return TransformsDeleteResponse{}, client.deleteHandleError(resp) + } + return TransformsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *TransformsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, options *TransformsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *TransformsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets a Transform. +// If the operation fails it returns the *ErrorResponse error type. +func (client *TransformsClient) Get(ctx context.Context, resourceGroupName string, accountName string, transformName string, options *TransformsGetOptions) (TransformsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, accountName, transformName, options) + if err != nil { + return TransformsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return TransformsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *TransformsClient) getCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, options *TransformsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TransformsClient) getHandleResponse(resp *http.Response) (TransformsGetResponse, error) { + result := TransformsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Transform); err != nil { + return TransformsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *TransformsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the Transforms in the account. +// If the operation fails it returns the *ErrorResponse error type. +func (client *TransformsClient) List(resourceGroupName string, accountName string, options *TransformsListOptions) *TransformsListPager { + return &TransformsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, accountName, options) + }, + advancer: func(ctx context.Context, resp TransformsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.TransformCollection.ODataNextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *TransformsClient) listCreateRequest(ctx context.Context, resourceGroupName string, accountName string, options *TransformsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Orderby != nil { + reqQP.Set("$orderby", *options.Orderby) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *TransformsClient) listHandleResponse(resp *http.Response) (TransformsListResponse, error) { + result := TransformsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.TransformCollection); err != nil { + return TransformsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *TransformsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates a Transform. +// If the operation fails it returns the *ErrorResponse error type. +func (client *TransformsClient) Update(ctx context.Context, resourceGroupName string, accountName string, transformName string, parameters Transform, options *TransformsUpdateOptions) (TransformsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, accountName, transformName, parameters, options) + if err != nil { + return TransformsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return TransformsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *TransformsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, accountName string, transformName string, parameters Transform, options *TransformsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/transforms/{transformName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if accountName == "" { + return nil, errors.New("parameter accountName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{accountName}", url.PathEscape(accountName)) + if transformName == "" { + return nil, errors.New("parameter transformName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformName}", url.PathEscape(transformName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2021-06-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *TransformsClient) updateHandleResponse(resp *http.Response) (TransformsUpdateResponse, error) { + result := TransformsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Transform); err != nil { + return TransformsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *TransformsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/mysql/armmysql/CHANGELOG.md b/sdk/resourcemanager/mysql/armmysql/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/mysql/armmysql/CHANGELOG.md +++ b/sdk/resourcemanager/mysql/armmysql/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/mysql/armmysql/zz_generated_constants.go b/sdk/resourcemanager/mysql/armmysql/zz_generated_constants.go index a28300d9f4b3..17b00d51379a 100644 --- a/sdk/resourcemanager/mysql/armmysql/zz_generated_constants.go +++ b/sdk/resourcemanager/mysql/armmysql/zz_generated_constants.go @@ -10,7 +10,7 @@ package armmysql const ( module = "armmysql" - version = "v0.1.0" + version = "v0.1.1" ) // CreateMode - The mode to create a new server. diff --git a/sdk/resourcemanager/mysql/armmysqlflexibleservers/CHANGELOG.md b/sdk/resourcemanager/mysql/armmysqlflexibleservers/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/mysql/armmysqlflexibleservers/CHANGELOG.md +++ b/sdk/resourcemanager/mysql/armmysqlflexibleservers/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/mysql/armmysqlflexibleservers/zz_generated_constants.go b/sdk/resourcemanager/mysql/armmysqlflexibleservers/zz_generated_constants.go index 36525eca8907..446ca11f857e 100644 --- a/sdk/resourcemanager/mysql/armmysqlflexibleservers/zz_generated_constants.go +++ b/sdk/resourcemanager/mysql/armmysqlflexibleservers/zz_generated_constants.go @@ -10,7 +10,7 @@ package armmysqlflexibleservers const ( module = "armmysqlflexibleservers" - version = "v0.1.0" + version = "v0.1.1" ) // ConfigurationSource - Source of the configuration. diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/CHANGELOG.md b/sdk/resourcemanager/notificationhubs/armnotificationhubs/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/LICENSE.txt b/sdk/resourcemanager/notificationhubs/armnotificationhubs/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/README.md b/sdk/resourcemanager/notificationhubs/armnotificationhubs/README.md new file mode 100644 index 000000000000..cd89580b6d4c --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/README.md @@ -0,0 +1,76 @@ +# Azure Notification Hubs Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/notificationhubs/armnotificationhubs)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/notificationhubs/armnotificationhubs) + +The `armnotificationhubs` module provides operations for working with Azure Notification Hubs. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/notificationhubs/armnotificationhubs) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Notification Hubs module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/notificationhubs/armnotificationhubs +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Notification Hubs. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Notification Hubs + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Notification Hubs modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armnotificationhubs.NewNamespacesClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Notification Hubs` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/autorest.md b/sdk/resourcemanager/notificationhubs/armnotificationhubs/autorest.md new file mode 100644 index 000000000000..736ea5635b05 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/2a5304178ab7416e40622808dea5b630fb7854d9/specification/notificationhubs/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/2a5304178ab7416e40622808dea5b630fb7854d9/specification/notificationhubs/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/build.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/build.go new file mode 100644 index 000000000000..ef40cac7a0be --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/notificationhubs/armnotificationhubs + +package armnotificationhubs diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/ci.yml b/sdk/resourcemanager/notificationhubs/armnotificationhubs/ci.yml new file mode 100644 index 000000000000..9a81b4dbf54c --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/notificationhubs/armnotificationhubs/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/notificationhubs/armnotificationhubs/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/notificationhubs/armnotificationhubs' diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.mod b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.mod new file mode 100644 index 000000000000..cc384ed9ddc4 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/notificationhubs/armnotificationhubs + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.sum b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/go_mod_tidy_hack.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go_mod_tidy_hack.go new file mode 100644 index 000000000000..2bcc2cf5f694 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armnotificationhubs + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_constants.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_constants.go new file mode 100644 index 000000000000..511c519d44ce --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_constants.go @@ -0,0 +1,80 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +const ( + module = "armnotificationhubs" + version = "v0.1.1" +) + +type AccessRights string + +const ( + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" + AccessRightsListen AccessRights = "Listen" +) + +// PossibleAccessRightsValues returns the possible values for the AccessRights const type. +func PossibleAccessRightsValues() []AccessRights { + return []AccessRights{ + AccessRightsManage, + AccessRightsSend, + AccessRightsListen, + } +} + +// ToPtr returns a *AccessRights pointing to the current value. +func (c AccessRights) ToPtr() *AccessRights { + return &c +} + +// NamespaceType - The namespace type. +type NamespaceType string + +const ( + NamespaceTypeMessaging NamespaceType = "Messaging" + NamespaceTypeNotificationHub NamespaceType = "NotificationHub" +) + +// PossibleNamespaceTypeValues returns the possible values for the NamespaceType const type. +func PossibleNamespaceTypeValues() []NamespaceType { + return []NamespaceType{ + NamespaceTypeMessaging, + NamespaceTypeNotificationHub, + } +} + +// ToPtr returns a *NamespaceType pointing to the current value. +func (c NamespaceType) ToPtr() *NamespaceType { + return &c +} + +// SKUName - Name of the notification hub sku +type SKUName string + +const ( + SKUNameBasic SKUName = "Basic" + SKUNameFree SKUName = "Free" + SKUNameStandard SKUName = "Standard" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNameBasic, + SKUNameFree, + SKUNameStandard, + } +} + +// ToPtr returns a *SKUName pointing to the current value. +func (c SKUName) ToPtr() *SKUName { + return &c +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_models.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_models.go new file mode 100644 index 000000000000..ac991cbc4e13 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_models.go @@ -0,0 +1,939 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AdmCredential - Description of a NotificationHub AdmCredential. +type AdmCredential struct { + // Properties of NotificationHub AdmCredential. + Properties *AdmCredentialProperties `json:"properties,omitempty"` +} + +// AdmCredentialProperties - Description of a NotificationHub AdmCredential. +type AdmCredentialProperties struct { + // The URL of the authorization token. + AuthTokenURL *string `json:"authTokenUrl,omitempty"` + + // The client identifier. + ClientID *string `json:"clientId,omitempty"` + + // The credential secret access key. + ClientSecret *string `json:"clientSecret,omitempty"` +} + +// ApnsCredential - Description of a NotificationHub ApnsCredential. +type ApnsCredential struct { + // Properties of NotificationHub ApnsCredential. + Properties *ApnsCredentialProperties `json:"properties,omitempty"` +} + +// ApnsCredentialProperties - Description of a NotificationHub ApnsCredential. Note that there is no explicit switch between Certificate and Token Authentication +// Modes. The mode is determined based on the properties passed in. +type ApnsCredentialProperties struct { + // The APNS certificate. Specify if using Certificate Authentication Mode. + ApnsCertificate *string `json:"apnsCertificate,omitempty"` + + // The issuer (iss) registered claim key. The value is a 10-character TeamId, obtained from your developer account. Specify if using Token Authentication + // Mode. + AppID *string `json:"appId,omitempty"` + + // The name of the application or BundleId. Specify if using Token Authentication Mode. + AppName *string `json:"appName,omitempty"` + + // The APNS certificate password if it exists. + CertificateKey *string `json:"certificateKey,omitempty"` + + // The APNS endpoint of this credential. If using Certificate Authentication Mode and Sandbox specify 'gateway.sandbox.push.apple.com'. If using Certificate + // Authentication Mode and Production specify + // 'gateway.push.apple.com'. If using Token Authentication Mode and Sandbox specify 'https://api.development.push.apple.com:443/3/device'. If using Token + // Authentication Mode and Production specify + // 'https://api.push.apple.com:443/3/device'. + Endpoint *string `json:"endpoint,omitempty"` + + // A 10-character key identifier (kid) key, obtained from your developer account. Specify if using Token Authentication Mode. + KeyID *string `json:"keyId,omitempty"` + + // The APNS certificate thumbprint. Specify if using Certificate Authentication Mode. + Thumbprint *string `json:"thumbprint,omitempty"` + + // Provider Authentication Token, obtained through your developer account. Specify if using Token Authentication Mode. + Token *string `json:"token,omitempty"` +} + +// BaiduCredential - Description of a NotificationHub BaiduCredential. +type BaiduCredential struct { + // Properties of NotificationHub BaiduCredential. + Properties *BaiduCredentialProperties `json:"properties,omitempty"` +} + +// BaiduCredentialProperties - Description of a NotificationHub BaiduCredential. +type BaiduCredentialProperties struct { + // Baidu Api Key. + BaiduAPIKey *string `json:"baiduApiKey,omitempty"` + + // Baidu Endpoint. + BaiduEndPoint *string `json:"baiduEndPoint,omitempty"` + + // Baidu Secret Key + BaiduSecretKey *string `json:"baiduSecretKey,omitempty"` +} + +// CheckAvailabilityParameters - Parameters supplied to the Check Name Availability for Namespace and NotificationHubs. +type CheckAvailabilityParameters struct { + // REQUIRED; Resource name + Name *string `json:"name,omitempty"` + + // True if the name is available and can be used to create new Namespace/NotificationHub. Otherwise false. + IsAvailiable *bool `json:"isAvailiable,omitempty"` + + // Resource location + Location *string `json:"location,omitempty"` + + // The sku of the created namespace + SKU *SKU `json:"sku,omitempty"` + + // Resource tags + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; Resource Id + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Resource type + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type CheckAvailabilityParameters. +func (c CheckAvailabilityParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", c.ID) + populate(objectMap, "isAvailiable", c.IsAvailiable) + populate(objectMap, "location", c.Location) + populate(objectMap, "name", c.Name) + populate(objectMap, "sku", c.SKU) + populate(objectMap, "tags", c.Tags) + populate(objectMap, "type", c.Type) + return json.Marshal(objectMap) +} + +// CheckAvailabilityResult - Description of a CheckAvailability resource. +type CheckAvailabilityResult struct { + Resource + // True if the name is available and can be used to create new Namespace/NotificationHub. Otherwise false. + IsAvailiable *bool `json:"isAvailiable,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CheckAvailabilityResult. +func (c CheckAvailabilityResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.Resource.marshalInternal(objectMap) + populate(objectMap, "isAvailiable", c.IsAvailiable) + return json.Marshal(objectMap) +} + +// DebugSendResponse - Description of a NotificationHub Resource. +type DebugSendResponse struct { + Resource + // Properties of the NotificationHub. + Properties *DebugSendResult `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type DebugSendResponse. +func (d DebugSendResponse) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", d.Properties) + return json.Marshal(objectMap) +} + +type DebugSendResult struct { + // send failure + Failure *float32 `json:"failure,omitempty"` + + // actual failure description + Results map[string]interface{} `json:"results,omitempty"` + + // successful send + Success *float32 `json:"success,omitempty"` +} + +// ErrorResponse - Error response indicates NotificationHubs service is not able to process the incoming request. The reason is provided in the error message. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // Error code. + Code *string `json:"code,omitempty"` + + // Error message indicating why the operation failed. + Message *string `json:"message,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// GCMCredential - Description of a NotificationHub GcmCredential. +type GCMCredential struct { + // Properties of NotificationHub GcmCredential. + Properties *GCMCredentialProperties `json:"properties,omitempty"` +} + +// GCMCredentialProperties - Description of a NotificationHub GcmCredential. +type GCMCredentialProperties struct { + // The FCM legacy endpoint. Default value is 'https://fcm.googleapis.com/fcm/send' + GCMEndpoint *string `json:"gcmEndpoint,omitempty"` + + // The Google API key. + GoogleAPIKey *string `json:"googleApiKey,omitempty"` +} + +// MpnsCredential - Description of a NotificationHub MpnsCredential. +type MpnsCredential struct { + // Properties of NotificationHub MpnsCredential. + Properties *MpnsCredentialProperties `json:"properties,omitempty"` +} + +// MpnsCredentialProperties - Description of a NotificationHub MpnsCredential. +type MpnsCredentialProperties struct { + // The certificate key for this credential. + CertificateKey *string `json:"certificateKey,omitempty"` + + // The MPNS certificate. + MpnsCertificate *string `json:"mpnsCertificate,omitempty"` + + // The MPNS certificate Thumbprint + Thumbprint *string `json:"thumbprint,omitempty"` +} + +// NamespaceCreateOrUpdateParameters - Parameters supplied to the CreateOrUpdate Namespace operation. +type NamespaceCreateOrUpdateParameters struct { + Resource + // Properties of the Namespace. + Properties *NamespaceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NamespaceCreateOrUpdateParameters. +func (n NamespaceCreateOrUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + n.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// NamespaceListResult - The response of the List Namespace operation. +type NamespaceListResult struct { + // Link to the next set of results. Not empty if Value contains incomplete list of Namespaces + NextLink *string `json:"nextLink,omitempty"` + + // Result of the List Namespace operation. + Value []*NamespaceResource `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NamespaceListResult. +func (n NamespaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// NamespacePatchParameters - Parameters supplied to the Patch Namespace operation. +type NamespacePatchParameters struct { + // The sku of the created namespace + SKU *SKU `json:"sku,omitempty"` + + // Resource tags + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NamespacePatchParameters. +func (n NamespacePatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "sku", n.SKU) + populate(objectMap, "tags", n.Tags) + return json.Marshal(objectMap) +} + +// NamespaceProperties - Namespace properties. +type NamespaceProperties struct { + // The time the namespace was created. + CreatedAt *time.Time `json:"createdAt,omitempty"` + + // Whether or not the namespace is set as Critical. + Critical *bool `json:"critical,omitempty"` + + // Data center for the namespace + DataCenter *string `json:"dataCenter,omitempty"` + + // Whether or not the namespace is currently enabled. + Enabled *bool `json:"enabled,omitempty"` + + // The name of the namespace. + Name *string `json:"name,omitempty"` + + // The namespace type. + NamespaceType *NamespaceType `json:"namespaceType,omitempty"` + + // Provisioning state of the Namespace. + ProvisioningState *string `json:"provisioningState,omitempty"` + + // Specifies the targeted region in which the namespace should be created. It can be any of the following values: Australia East, Australia Southeast, Central + // US, East US, East US 2, West US, North + // Central US, South Central US, East Asia, Southeast Asia, Brazil South, Japan East, Japan West, North Europe, West Europe + Region *string `json:"region,omitempty"` + + // ScaleUnit where the namespace gets created + ScaleUnit *string `json:"scaleUnit,omitempty"` + + // Endpoint you can use to perform NotificationHub operations. + ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty"` + + // Status of the namespace. It can be any of these values:1 = Created/Active2 = Creating3 = Suspended4 = Deleting + Status *string `json:"status,omitempty"` + + // The Id of the Azure subscription associated with the namespace. + SubscriptionID *string `json:"subscriptionId,omitempty"` + + // The time the namespace was updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty"` + + // READ-ONLY; Identifier for Azure Insights metrics + MetricID *string `json:"metricId,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type NamespaceProperties. +func (n NamespaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(n.CreatedAt)) + populate(objectMap, "critical", n.Critical) + populate(objectMap, "dataCenter", n.DataCenter) + populate(objectMap, "enabled", n.Enabled) + populate(objectMap, "metricId", n.MetricID) + populate(objectMap, "name", n.Name) + populate(objectMap, "namespaceType", n.NamespaceType) + populate(objectMap, "provisioningState", n.ProvisioningState) + populate(objectMap, "region", n.Region) + populate(objectMap, "scaleUnit", n.ScaleUnit) + populate(objectMap, "serviceBusEndpoint", n.ServiceBusEndpoint) + populate(objectMap, "status", n.Status) + populate(objectMap, "subscriptionId", n.SubscriptionID) + populate(objectMap, "updatedAt", (*timeRFC3339)(n.UpdatedAt)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type NamespaceProperties. +func (n *NamespaceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + n.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "critical": + err = unpopulate(val, &n.Critical) + delete(rawMsg, key) + case "dataCenter": + err = unpopulate(val, &n.DataCenter) + delete(rawMsg, key) + case "enabled": + err = unpopulate(val, &n.Enabled) + delete(rawMsg, key) + case "metricId": + err = unpopulate(val, &n.MetricID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, &n.Name) + delete(rawMsg, key) + case "namespaceType": + err = unpopulate(val, &n.NamespaceType) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &n.ProvisioningState) + delete(rawMsg, key) + case "region": + err = unpopulate(val, &n.Region) + delete(rawMsg, key) + case "scaleUnit": + err = unpopulate(val, &n.ScaleUnit) + delete(rawMsg, key) + case "serviceBusEndpoint": + err = unpopulate(val, &n.ServiceBusEndpoint) + delete(rawMsg, key) + case "status": + err = unpopulate(val, &n.Status) + delete(rawMsg, key) + case "subscriptionId": + err = unpopulate(val, &n.SubscriptionID) + delete(rawMsg, key) + case "updatedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + n.UpdatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// NamespaceResource - Description of a Namespace resource. +type NamespaceResource struct { + Resource + // Properties of the Namespace. + Properties *NamespaceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NamespaceResource. +func (n NamespaceResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + n.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// NamespacesBeginDeleteOptions contains the optional parameters for the Namespaces.BeginDelete method. +type NamespacesBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// NamespacesCheckAvailabilityOptions contains the optional parameters for the Namespaces.CheckAvailability method. +type NamespacesCheckAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// NamespacesCreateOrUpdateAuthorizationRuleOptions contains the optional parameters for the Namespaces.CreateOrUpdateAuthorizationRule method. +type NamespacesCreateOrUpdateAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesCreateOrUpdateOptions contains the optional parameters for the Namespaces.CreateOrUpdate method. +type NamespacesCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// NamespacesDeleteAuthorizationRuleOptions contains the optional parameters for the Namespaces.DeleteAuthorizationRule method. +type NamespacesDeleteAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesGetAuthorizationRuleOptions contains the optional parameters for the Namespaces.GetAuthorizationRule method. +type NamespacesGetAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesGetOptions contains the optional parameters for the Namespaces.Get method. +type NamespacesGetOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListAllOptions contains the optional parameters for the Namespaces.ListAll method. +type NamespacesListAllOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListAuthorizationRulesOptions contains the optional parameters for the Namespaces.ListAuthorizationRules method. +type NamespacesListAuthorizationRulesOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListKeysOptions contains the optional parameters for the Namespaces.ListKeys method. +type NamespacesListKeysOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListOptions contains the optional parameters for the Namespaces.List method. +type NamespacesListOptions struct { + // placeholder for future optional parameters +} + +// NamespacesPatchOptions contains the optional parameters for the Namespaces.Patch method. +type NamespacesPatchOptions struct { + // placeholder for future optional parameters +} + +// NamespacesRegenerateKeysOptions contains the optional parameters for the Namespaces.RegenerateKeys method. +type NamespacesRegenerateKeysOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubCreateOrUpdateParameters - Parameters supplied to the CreateOrUpdate NotificationHub operation. +type NotificationHubCreateOrUpdateParameters struct { + Resource + // REQUIRED; Properties of the NotificationHub. + Properties *NotificationHubProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationHubCreateOrUpdateParameters. +func (n NotificationHubCreateOrUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + n.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// NotificationHubListResult - The response of the List NotificationHub operation. +type NotificationHubListResult struct { + // Link to the next set of results. Not empty if Value contains incomplete list of NotificationHub + NextLink *string `json:"nextLink,omitempty"` + + // Result of the List NotificationHub operation. + Value []*NotificationHubResource `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationHubListResult. +func (n NotificationHubListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", n.NextLink) + populate(objectMap, "value", n.Value) + return json.Marshal(objectMap) +} + +// NotificationHubPatchParameters - Parameters supplied to the patch NotificationHub operation. +type NotificationHubPatchParameters struct { + Resource + // Properties of the NotificationHub. + Properties *NotificationHubProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationHubPatchParameters. +func (n NotificationHubPatchParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + n.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// NotificationHubProperties - NotificationHub properties. +type NotificationHubProperties struct { + // The AdmCredential of the created NotificationHub + AdmCredential *AdmCredential `json:"admCredential,omitempty"` + + // The ApnsCredential of the created NotificationHub + ApnsCredential *ApnsCredential `json:"apnsCredential,omitempty"` + + // The AuthorizationRules of the created NotificationHub + AuthorizationRules []*SharedAccessAuthorizationRuleProperties `json:"authorizationRules,omitempty"` + + // The BaiduCredential of the created NotificationHub + BaiduCredential *BaiduCredential `json:"baiduCredential,omitempty"` + + // The GcmCredential of the created NotificationHub + GCMCredential *GCMCredential `json:"gcmCredential,omitempty"` + + // The MpnsCredential of the created NotificationHub + MpnsCredential *MpnsCredential `json:"mpnsCredential,omitempty"` + + // The NotificationHub name. + Name *string `json:"name,omitempty"` + + // The RegistrationTtl of the created NotificationHub + RegistrationTTL *string `json:"registrationTtl,omitempty"` + + // The WnsCredential of the created NotificationHub + WnsCredential *WnsCredential `json:"wnsCredential,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationHubProperties. +func (n NotificationHubProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "admCredential", n.AdmCredential) + populate(objectMap, "apnsCredential", n.ApnsCredential) + populate(objectMap, "authorizationRules", n.AuthorizationRules) + populate(objectMap, "baiduCredential", n.BaiduCredential) + populate(objectMap, "gcmCredential", n.GCMCredential) + populate(objectMap, "mpnsCredential", n.MpnsCredential) + populate(objectMap, "name", n.Name) + populate(objectMap, "registrationTtl", n.RegistrationTTL) + populate(objectMap, "wnsCredential", n.WnsCredential) + return json.Marshal(objectMap) +} + +// NotificationHubResource - Description of a NotificationHub Resource. +type NotificationHubResource struct { + Resource + // Properties of the NotificationHub. + Properties *NotificationHubProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NotificationHubResource. +func (n NotificationHubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + n.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", n.Properties) + return json.Marshal(objectMap) +} + +// NotificationHubsCheckNotificationHubAvailabilityOptions contains the optional parameters for the NotificationHubs.CheckNotificationHubAvailability method. +type NotificationHubsCheckNotificationHubAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsCreateOrUpdateAuthorizationRuleOptions contains the optional parameters for the NotificationHubs.CreateOrUpdateAuthorizationRule method. +type NotificationHubsCreateOrUpdateAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsCreateOrUpdateOptions contains the optional parameters for the NotificationHubs.CreateOrUpdate method. +type NotificationHubsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsDebugSendOptions contains the optional parameters for the NotificationHubs.DebugSend method. +type NotificationHubsDebugSendOptions struct { + // Debug send parameters + Parameters map[string]interface{} +} + +// NotificationHubsDeleteAuthorizationRuleOptions contains the optional parameters for the NotificationHubs.DeleteAuthorizationRule method. +type NotificationHubsDeleteAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsDeleteOptions contains the optional parameters for the NotificationHubs.Delete method. +type NotificationHubsDeleteOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsGetAuthorizationRuleOptions contains the optional parameters for the NotificationHubs.GetAuthorizationRule method. +type NotificationHubsGetAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsGetOptions contains the optional parameters for the NotificationHubs.Get method. +type NotificationHubsGetOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsGetPnsCredentialsOptions contains the optional parameters for the NotificationHubs.GetPnsCredentials method. +type NotificationHubsGetPnsCredentialsOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsListAuthorizationRulesOptions contains the optional parameters for the NotificationHubs.ListAuthorizationRules method. +type NotificationHubsListAuthorizationRulesOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsListKeysOptions contains the optional parameters for the NotificationHubs.ListKeys method. +type NotificationHubsListKeysOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsListOptions contains the optional parameters for the NotificationHubs.List method. +type NotificationHubsListOptions struct { + // placeholder for future optional parameters +} + +// NotificationHubsPatchOptions contains the optional parameters for the NotificationHubs.Patch method. +type NotificationHubsPatchOptions struct { + // Parameters supplied to patch a NotificationHub Resource. + Parameters *NotificationHubPatchParameters +} + +// NotificationHubsRegenerateKeysOptions contains the optional parameters for the NotificationHubs.RegenerateKeys method. +type NotificationHubsRegenerateKeysOptions struct { + // placeholder for future optional parameters +} + +// Operation - A NotificationHubs REST API operation +type Operation struct { + // The object that represents the operation. + Display *OperationDisplay `json:"display,omitempty"` + + // READ-ONLY; Operation name: {provider}/{resource}/{operation} + Name *string `json:"name,omitempty" azure:"ro"` +} + +// OperationDisplay - The object that represents the operation. +type OperationDisplay struct { + // READ-ONLY; Operation type: Read, write, delete, etc. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; Service provider: Microsoft.NotificationHubs + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; Resource on which the operation is performed: Invoice, etc. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - Result of the request to list NotificationHubs operations. It contains a list of operations and a URL link to get the next set +// of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; List of NotificationHubs operations supported by the Microsoft.NotificationHubs resource provider. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// PnsCredentialsProperties - Description of a NotificationHub PNS Credentials. +type PnsCredentialsProperties struct { + // The AdmCredential of the created NotificationHub + AdmCredential *AdmCredential `json:"admCredential,omitempty"` + + // The ApnsCredential of the created NotificationHub + ApnsCredential *ApnsCredential `json:"apnsCredential,omitempty"` + + // The BaiduCredential of the created NotificationHub + BaiduCredential *BaiduCredential `json:"baiduCredential,omitempty"` + + // The GcmCredential of the created NotificationHub + GCMCredential *GCMCredential `json:"gcmCredential,omitempty"` + + // The MpnsCredential of the created NotificationHub + MpnsCredential *MpnsCredential `json:"mpnsCredential,omitempty"` + + // The WnsCredential of the created NotificationHub + WnsCredential *WnsCredential `json:"wnsCredential,omitempty"` +} + +// PnsCredentialsResource - Description of a NotificationHub PNS Credentials. +type PnsCredentialsResource struct { + Resource + // NotificationHub PNS Credentials. + Properties *PnsCredentialsProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PnsCredentialsResource. +func (p PnsCredentialsResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PolicykeyResource - Namespace/NotificationHub Regenerate Keys +type PolicykeyResource struct { + // Name of the key that has to be regenerated for the Namespace/Notification Hub Authorization Rule. The value can be Primary Key/Secondary Key. + PolicyKey *string `json:"policyKey,omitempty"` +} + +type Resource struct { + // Resource location + Location *string `json:"location,omitempty"` + + // The sku of the created namespace + SKU *SKU `json:"sku,omitempty"` + + // Resource tags + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; Resource Id + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Resource name + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Resource type + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "location", r.Location) + populate(objectMap, "name", r.Name) + populate(objectMap, "sku", r.SKU) + populate(objectMap, "tags", r.Tags) + populate(objectMap, "type", r.Type) +} + +// ResourceListKeys - Namespace/NotificationHub Connection String +type ResourceListKeys struct { + // KeyName of the created AuthorizationRule + KeyName *string `json:"keyName,omitempty"` + + // PrimaryConnectionString of the AuthorizationRule. + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + + // PrimaryKey of the created AuthorizationRule. + PrimaryKey *string `json:"primaryKey,omitempty"` + + // SecondaryConnectionString of the created AuthorizationRule + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + + // SecondaryKey of the created AuthorizationRule + SecondaryKey *string `json:"secondaryKey,omitempty"` +} + +// SKU - The Sku description for a namespace +type SKU struct { + // REQUIRED; Name of the notification hub sku + Name *SKUName `json:"name,omitempty"` + + // The capacity of the resource + Capacity *int32 `json:"capacity,omitempty"` + + // The Sku Family + Family *string `json:"family,omitempty"` + + // The Sku size + Size *string `json:"size,omitempty"` + + // The tier of particular sku + Tier *string `json:"tier,omitempty"` +} + +// SharedAccessAuthorizationRuleCreateOrUpdateParameters - Parameters supplied to the CreateOrUpdate Namespace AuthorizationRules. +type SharedAccessAuthorizationRuleCreateOrUpdateParameters struct { + // REQUIRED; Properties of the Namespace AuthorizationRules. + Properties *SharedAccessAuthorizationRuleProperties `json:"properties,omitempty"` +} + +// SharedAccessAuthorizationRuleListResult - The response of the List Namespace operation. +type SharedAccessAuthorizationRuleListResult struct { + // Link to the next set of results. Not empty if Value contains incomplete list of AuthorizationRules + NextLink *string `json:"nextLink,omitempty"` + + // Result of the List AuthorizationRules operation. + Value []*SharedAccessAuthorizationRuleResource `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SharedAccessAuthorizationRuleListResult. +func (s SharedAccessAuthorizationRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// SharedAccessAuthorizationRuleProperties - SharedAccessAuthorizationRule properties. +type SharedAccessAuthorizationRuleProperties struct { + // The rights associated with the rule. + Rights []*AccessRights `json:"rights,omitempty"` + + // READ-ONLY; A string that describes the claim type + ClaimType *string `json:"claimType,omitempty" azure:"ro"` + + // READ-ONLY; A string that describes the claim value + ClaimValue *string `json:"claimValue,omitempty" azure:"ro"` + + // READ-ONLY; The created time for this rule + CreatedTime *string `json:"createdTime,omitempty" azure:"ro"` + + // READ-ONLY; A string that describes the authorization rule. + KeyName *string `json:"keyName,omitempty" azure:"ro"` + + // READ-ONLY; The last modified time for this rule + ModifiedTime *string `json:"modifiedTime,omitempty" azure:"ro"` + + // READ-ONLY; A base64-encoded 256-bit primary key for signing and validating the SAS token. + PrimaryKey *string `json:"primaryKey,omitempty" azure:"ro"` + + // READ-ONLY; The revision number for the rule + Revision *int32 `json:"revision,omitempty" azure:"ro"` + + // READ-ONLY; A base64-encoded 256-bit primary key for signing and validating the SAS token. + SecondaryKey *string `json:"secondaryKey,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SharedAccessAuthorizationRuleProperties. +func (s SharedAccessAuthorizationRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "claimType", s.ClaimType) + populate(objectMap, "claimValue", s.ClaimValue) + populate(objectMap, "createdTime", s.CreatedTime) + populate(objectMap, "keyName", s.KeyName) + populate(objectMap, "modifiedTime", s.ModifiedTime) + populate(objectMap, "primaryKey", s.PrimaryKey) + populate(objectMap, "revision", s.Revision) + populate(objectMap, "rights", s.Rights) + populate(objectMap, "secondaryKey", s.SecondaryKey) + return json.Marshal(objectMap) +} + +// SharedAccessAuthorizationRuleResource - Description of a Namespace AuthorizationRules. +type SharedAccessAuthorizationRuleResource struct { + Resource + // Properties of the Namespace AuthorizationRule. + Properties *SharedAccessAuthorizationRuleProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SharedAccessAuthorizationRuleResource. +func (s SharedAccessAuthorizationRuleResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +type SubResource struct { + // Resource Id + ID *string `json:"id,omitempty"` +} + +// WnsCredential - Description of a NotificationHub WnsCredential. +type WnsCredential struct { + // Properties of NotificationHub WnsCredential. + Properties *WnsCredentialProperties `json:"properties,omitempty"` +} + +// WnsCredentialProperties - Description of a NotificationHub WnsCredential. +type WnsCredentialProperties struct { + // The package ID for this credential. + PackageSid *string `json:"packageSid,omitempty"` + + // The secret key. + SecretKey *string `json:"secretKey,omitempty"` + + // The Windows Live endpoint. + WindowsLiveEndpoint *string `json:"windowsLiveEndpoint,omitempty"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_namespaces_client.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_namespaces_client.go new file mode 100644 index 000000000000..e010f011df4d --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_namespaces_client.go @@ -0,0 +1,859 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NamespacesClient contains the methods for the Namespaces group. +// Don't use this type directly, use NewNamespacesClient() instead. +type NamespacesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewNamespacesClient creates a new instance of NamespacesClient with the specified values. +func NewNamespacesClient(con *arm.Connection, subscriptionID string) *NamespacesClient { + return &NamespacesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckAvailability - Checks the availability of the given service namespace across all Azure subscriptions. This is useful because the domain name is +// created based on the service namespace name. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) CheckAvailability(ctx context.Context, parameters CheckAvailabilityParameters, options *NamespacesCheckAvailabilityOptions) (NamespacesCheckAvailabilityResponse, error) { + req, err := client.checkAvailabilityCreateRequest(ctx, parameters, options) + if err != nil { + return NamespacesCheckAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesCheckAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesCheckAvailabilityResponse{}, client.checkAvailabilityHandleError(resp) + } + return client.checkAvailabilityHandleResponse(resp) +} + +// checkAvailabilityCreateRequest creates the CheckAvailability request. +func (client *NamespacesClient) checkAvailabilityCreateRequest(ctx context.Context, parameters CheckAvailabilityParameters, options *NamespacesCheckAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/checkNamespaceAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkAvailabilityHandleResponse handles the CheckAvailability response. +func (client *NamespacesClient) checkAvailabilityHandleResponse(resp *http.Response) (NamespacesCheckAvailabilityResponse, error) { + result := NamespacesCheckAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckAvailabilityResult); err != nil { + return NamespacesCheckAvailabilityResponse{}, err + } + return result, nil +} + +// checkAvailabilityHandleError handles the CheckAvailability error response. +func (client *NamespacesClient) checkAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// CreateOrUpdate - Creates/Updates a service namespace. Once created, this namespace's resource manifest is immutable. This operation is idempotent. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, parameters NamespaceCreateOrUpdateParameters, options *NamespacesCreateOrUpdateOptions) (NamespacesCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return NamespacesCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return NamespacesCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *NamespacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, parameters NamespaceCreateOrUpdateParameters, options *NamespacesCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *NamespacesClient) createOrUpdateHandleResponse(resp *http.Response) (NamespacesCreateOrUpdateResponse, error) { + result := NamespacesCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NamespaceResource); err != nil { + return NamespacesCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *NamespacesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// CreateOrUpdateAuthorizationRule - Creates an authorization rule for a namespace +// If the operation fails it returns a generic error. +func (client *NamespacesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters SharedAccessAuthorizationRuleCreateOrUpdateParameters, options *NamespacesCreateOrUpdateAuthorizationRuleOptions) (NamespacesCreateOrUpdateAuthorizationRuleResponse, error) { + req, err := client.createOrUpdateAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters, options) + if err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, client.createOrUpdateAuthorizationRuleHandleError(resp) + } + return client.createOrUpdateAuthorizationRuleHandleResponse(resp) +} + +// createOrUpdateAuthorizationRuleCreateRequest creates the CreateOrUpdateAuthorizationRule request. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters SharedAccessAuthorizationRuleCreateOrUpdateParameters, options *NamespacesCreateOrUpdateAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateAuthorizationRuleHandleResponse handles the CreateOrUpdateAuthorizationRule response. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleHandleResponse(resp *http.Response) (NamespacesCreateOrUpdateAuthorizationRuleResponse, error) { + result := NamespacesCreateOrUpdateAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleResource); err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + return result, nil +} + +// createOrUpdateAuthorizationRuleHandleError handles the CreateOrUpdateAuthorizationRule error response. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// BeginDelete - Deletes an existing namespace. This operation also removes all associated notificationHubs under the namespace. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) BeginDelete(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (NamespacesDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return NamespacesDeletePollerResponse{}, err + } + result := NamespacesDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("NamespacesClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return NamespacesDeletePollerResponse{}, err + } + result.Poller = &NamespacesDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes an existing namespace. This operation also removes all associated notificationHubs under the namespace. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) deleteOperation(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *NamespacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *NamespacesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// DeleteAuthorizationRule - Deletes a namespace authorization rule +// If the operation fails it returns a generic error. +func (client *NamespacesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesDeleteAuthorizationRuleOptions) (NamespacesDeleteAuthorizationRuleResponse, error) { + req, err := client.deleteAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesDeleteAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesDeleteAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return NamespacesDeleteAuthorizationRuleResponse{}, client.deleteAuthorizationRuleHandleError(resp) + } + return NamespacesDeleteAuthorizationRuleResponse{RawResponse: resp}, nil +} + +// deleteAuthorizationRuleCreateRequest creates the DeleteAuthorizationRule request. +func (client *NamespacesClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesDeleteAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteAuthorizationRuleHandleError handles the DeleteAuthorizationRule error response. +func (client *NamespacesClient) deleteAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Get - Returns the description for the specified namespace. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesGetOptions) (NamespacesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return NamespacesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *NamespacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NamespacesClient) getHandleResponse(resp *http.Response) (NamespacesGetResponse, error) { + result := NamespacesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NamespaceResource); err != nil { + return NamespacesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *NamespacesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// GetAuthorizationRule - Gets an authorization rule for a namespace by name. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesGetAuthorizationRuleOptions) (NamespacesGetAuthorizationRuleResponse, error) { + req, err := client.getAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesGetAuthorizationRuleResponse{}, client.getAuthorizationRuleHandleError(resp) + } + return client.getAuthorizationRuleHandleResponse(resp) +} + +// getAuthorizationRuleCreateRequest creates the GetAuthorizationRule request. +func (client *NamespacesClient) getAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesGetAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAuthorizationRuleHandleResponse handles the GetAuthorizationRule response. +func (client *NamespacesClient) getAuthorizationRuleHandleResponse(resp *http.Response) (NamespacesGetAuthorizationRuleResponse, error) { + result := NamespacesGetAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleResource); err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + return result, nil +} + +// getAuthorizationRuleHandleError handles the GetAuthorizationRule error response. +func (client *NamespacesClient) getAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// List - Lists the available namespaces within a resourceGroup. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) List(resourceGroupName string, options *NamespacesListOptions) *NamespacesListPager { + return &NamespacesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp NamespacesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.NamespaceListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *NamespacesClient) listCreateRequest(ctx context.Context, resourceGroupName string, options *NamespacesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *NamespacesClient) listHandleResponse(resp *http.Response) (NamespacesListResponse, error) { + result := NamespacesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NamespaceListResult); err != nil { + return NamespacesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *NamespacesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListAll - Lists all the available namespaces within the subscription irrespective of the resourceGroups. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) ListAll(options *NamespacesListAllOptions) *NamespacesListAllPager { + return &NamespacesListAllPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAllCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp NamespacesListAllResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.NamespaceListResult.NextLink) + }, + } +} + +// listAllCreateRequest creates the ListAll request. +func (client *NamespacesClient) listAllCreateRequest(ctx context.Context, options *NamespacesListAllOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.NotificationHubs/namespaces" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAllHandleResponse handles the ListAll response. +func (client *NamespacesClient) listAllHandleResponse(resp *http.Response) (NamespacesListAllResponse, error) { + result := NamespacesListAllResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NamespaceListResult); err != nil { + return NamespacesListAllResponse{}, err + } + return result, nil +} + +// listAllHandleError handles the ListAll error response. +func (client *NamespacesClient) listAllHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListAuthorizationRules - Gets the authorization rules for a namespace. +// If the operation fails it returns a generic error. +func (client *NamespacesClient) ListAuthorizationRules(resourceGroupName string, namespaceName string, options *NamespacesListAuthorizationRulesOptions) *NamespacesListAuthorizationRulesPager { + return &NamespacesListAuthorizationRulesPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAuthorizationRulesCreateRequest(ctx, resourceGroupName, namespaceName, options) + }, + advancer: func(ctx context.Context, resp NamespacesListAuthorizationRulesResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SharedAccessAuthorizationRuleListResult.NextLink) + }, + } +} + +// listAuthorizationRulesCreateRequest creates the ListAuthorizationRules request. +func (client *NamespacesClient) listAuthorizationRulesCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesListAuthorizationRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAuthorizationRulesHandleResponse handles the ListAuthorizationRules response. +func (client *NamespacesClient) listAuthorizationRulesHandleResponse(resp *http.Response) (NamespacesListAuthorizationRulesResponse, error) { + result := NamespacesListAuthorizationRulesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleListResult); err != nil { + return NamespacesListAuthorizationRulesResponse{}, err + } + return result, nil +} + +// listAuthorizationRulesHandleError handles the ListAuthorizationRules error response. +func (client *NamespacesClient) listAuthorizationRulesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListKeys - Gets the Primary and Secondary ConnectionStrings to the namespace +// If the operation fails it returns a generic error. +func (client *NamespacesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesListKeysOptions) (NamespacesListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *NamespacesClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *NamespacesClient) listKeysHandleResponse(resp *http.Response) (NamespacesListKeysResponse, error) { + result := NamespacesListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleListResult); err != nil { + return NamespacesListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *NamespacesClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Patch - Patches the existing namespace +// If the operation fails it returns a generic error. +func (client *NamespacesClient) Patch(ctx context.Context, resourceGroupName string, namespaceName string, parameters NamespacePatchParameters, options *NamespacesPatchOptions) (NamespacesPatchResponse, error) { + req, err := client.patchCreateRequest(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return NamespacesPatchResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesPatchResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesPatchResponse{}, client.patchHandleError(resp) + } + return client.patchHandleResponse(resp) +} + +// patchCreateRequest creates the Patch request. +func (client *NamespacesClient) patchCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, parameters NamespacePatchParameters, options *NamespacesPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// patchHandleResponse handles the Patch response. +func (client *NamespacesClient) patchHandleResponse(resp *http.Response) (NamespacesPatchResponse, error) { + result := NamespacesPatchResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NamespaceResource); err != nil { + return NamespacesPatchResponse{}, err + } + return result, nil +} + +// patchHandleError handles the Patch error response. +func (client *NamespacesClient) patchHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// RegenerateKeys - Regenerates the Primary/Secondary Keys to the Namespace Authorization Rule +// If the operation fails it returns a generic error. +func (client *NamespacesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters PolicykeyResource, options *NamespacesRegenerateKeysOptions) (NamespacesRegenerateKeysResponse, error) { + req, err := client.regenerateKeysCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters, options) + if err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesRegenerateKeysResponse{}, client.regenerateKeysHandleError(resp) + } + return client.regenerateKeysHandleResponse(resp) +} + +// regenerateKeysCreateRequest creates the RegenerateKeys request. +func (client *NamespacesClient) regenerateKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters PolicykeyResource, options *NamespacesRegenerateKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeysHandleResponse handles the RegenerateKeys response. +func (client *NamespacesClient) regenerateKeysHandleResponse(resp *http.Response) (NamespacesRegenerateKeysResponse, error) { + result := NamespacesRegenerateKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceListKeys); err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + return result, nil +} + +// regenerateKeysHandleError handles the RegenerateKeys error response. +func (client *NamespacesClient) regenerateKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_notificationhubs_client.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_notificationhubs_client.go new file mode 100644 index 000000000000..af12c9aa5965 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_notificationhubs_client.go @@ -0,0 +1,978 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NotificationHubsClient contains the methods for the NotificationHubs group. +// Don't use this type directly, use NewNotificationHubsClient() instead. +type NotificationHubsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewNotificationHubsClient creates a new instance of NotificationHubsClient with the specified values. +func NewNotificationHubsClient(con *arm.Connection, subscriptionID string) *NotificationHubsClient { + return &NotificationHubsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckNotificationHubAvailability - Checks the availability of the given notificationHub in a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) CheckNotificationHubAvailability(ctx context.Context, resourceGroupName string, namespaceName string, parameters CheckAvailabilityParameters, options *NotificationHubsCheckNotificationHubAvailabilityOptions) (NotificationHubsCheckNotificationHubAvailabilityResponse, error) { + req, err := client.checkNotificationHubAvailabilityCreateRequest(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return NotificationHubsCheckNotificationHubAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsCheckNotificationHubAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsCheckNotificationHubAvailabilityResponse{}, client.checkNotificationHubAvailabilityHandleError(resp) + } + return client.checkNotificationHubAvailabilityHandleResponse(resp) +} + +// checkNotificationHubAvailabilityCreateRequest creates the CheckNotificationHubAvailability request. +func (client *NotificationHubsClient) checkNotificationHubAvailabilityCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, parameters CheckAvailabilityParameters, options *NotificationHubsCheckNotificationHubAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/checkNotificationHubAvailability" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkNotificationHubAvailabilityHandleResponse handles the CheckNotificationHubAvailability response. +func (client *NotificationHubsClient) checkNotificationHubAvailabilityHandleResponse(resp *http.Response) (NotificationHubsCheckNotificationHubAvailabilityResponse, error) { + result := NotificationHubsCheckNotificationHubAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckAvailabilityResult); err != nil { + return NotificationHubsCheckNotificationHubAvailabilityResponse{}, err + } + return result, nil +} + +// checkNotificationHubAvailabilityHandleError handles the CheckNotificationHubAvailability error response. +func (client *NotificationHubsClient) checkNotificationHubAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// CreateOrUpdate - Creates/Update a NotificationHub in a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, parameters NotificationHubCreateOrUpdateParameters, options *NotificationHubsCreateOrUpdateOptions) (NotificationHubsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, parameters, options) + if err != nil { + return NotificationHubsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return NotificationHubsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *NotificationHubsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, parameters NotificationHubCreateOrUpdateParameters, options *NotificationHubsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *NotificationHubsClient) createOrUpdateHandleResponse(resp *http.Response) (NotificationHubsCreateOrUpdateResponse, error) { + result := NotificationHubsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NotificationHubResource); err != nil { + return NotificationHubsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *NotificationHubsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// CreateOrUpdateAuthorizationRule - Creates/Updates an authorization rule for a NotificationHub +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, parameters SharedAccessAuthorizationRuleCreateOrUpdateParameters, options *NotificationHubsCreateOrUpdateAuthorizationRuleOptions) (NotificationHubsCreateOrUpdateAuthorizationRuleResponse, error) { + req, err := client.createOrUpdateAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters, options) + if err != nil { + return NotificationHubsCreateOrUpdateAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsCreateOrUpdateAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsCreateOrUpdateAuthorizationRuleResponse{}, client.createOrUpdateAuthorizationRuleHandleError(resp) + } + return client.createOrUpdateAuthorizationRuleHandleResponse(resp) +} + +// createOrUpdateAuthorizationRuleCreateRequest creates the CreateOrUpdateAuthorizationRule request. +func (client *NotificationHubsClient) createOrUpdateAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, parameters SharedAccessAuthorizationRuleCreateOrUpdateParameters, options *NotificationHubsCreateOrUpdateAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateAuthorizationRuleHandleResponse handles the CreateOrUpdateAuthorizationRule response. +func (client *NotificationHubsClient) createOrUpdateAuthorizationRuleHandleResponse(resp *http.Response) (NotificationHubsCreateOrUpdateAuthorizationRuleResponse, error) { + result := NotificationHubsCreateOrUpdateAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleResource); err != nil { + return NotificationHubsCreateOrUpdateAuthorizationRuleResponse{}, err + } + return result, nil +} + +// createOrUpdateAuthorizationRuleHandleError handles the CreateOrUpdateAuthorizationRule error response. +func (client *NotificationHubsClient) createOrUpdateAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// DebugSend - test send a push notification +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) DebugSend(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsDebugSendOptions) (NotificationHubsDebugSendResponse, error) { + req, err := client.debugSendCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + if err != nil { + return NotificationHubsDebugSendResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsDebugSendResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusCreated) { + return NotificationHubsDebugSendResponse{}, client.debugSendHandleError(resp) + } + return client.debugSendHandleResponse(resp) +} + +// debugSendCreateRequest creates the DebugSend request. +func (client *NotificationHubsClient) debugSendCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsDebugSendOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/debugsend" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, options.Parameters) + } + return req, nil +} + +// debugSendHandleResponse handles the DebugSend response. +func (client *NotificationHubsClient) debugSendHandleResponse(resp *http.Response) (NotificationHubsDebugSendResponse, error) { + result := NotificationHubsDebugSendResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.DebugSendResponse); err != nil { + return NotificationHubsDebugSendResponse{}, err + } + return result, nil +} + +// debugSendHandleError handles the DebugSend error response. +func (client *NotificationHubsClient) debugSendHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Delete - Deletes a notification hub associated with a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsDeleteOptions) (NotificationHubsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + if err != nil { + return NotificationHubsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsDeleteResponse{}, client.deleteHandleError(resp) + } + return NotificationHubsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *NotificationHubsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *NotificationHubsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// DeleteAuthorizationRule - Deletes a notificationHub authorization rule +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsDeleteAuthorizationRuleOptions) (NotificationHubsDeleteAuthorizationRuleResponse, error) { + req, err := client.deleteAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options) + if err != nil { + return NotificationHubsDeleteAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsDeleteAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return NotificationHubsDeleteAuthorizationRuleResponse{}, client.deleteAuthorizationRuleHandleError(resp) + } + return NotificationHubsDeleteAuthorizationRuleResponse{RawResponse: resp}, nil +} + +// deleteAuthorizationRuleCreateRequest creates the DeleteAuthorizationRule request. +func (client *NotificationHubsClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsDeleteAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteAuthorizationRuleHandleError handles the DeleteAuthorizationRule error response. +func (client *NotificationHubsClient) deleteAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Get - Lists the notification hubs associated with a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsGetOptions) (NotificationHubsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + if err != nil { + return NotificationHubsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *NotificationHubsClient) getCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NotificationHubsClient) getHandleResponse(resp *http.Response) (NotificationHubsGetResponse, error) { + result := NotificationHubsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NotificationHubResource); err != nil { + return NotificationHubsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *NotificationHubsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// GetAuthorizationRule - Gets an authorization rule for a NotificationHub by name. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsGetAuthorizationRuleOptions) (NotificationHubsGetAuthorizationRuleResponse, error) { + req, err := client.getAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options) + if err != nil { + return NotificationHubsGetAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsGetAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsGetAuthorizationRuleResponse{}, client.getAuthorizationRuleHandleError(resp) + } + return client.getAuthorizationRuleHandleResponse(resp) +} + +// getAuthorizationRuleCreateRequest creates the GetAuthorizationRule request. +func (client *NotificationHubsClient) getAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsGetAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAuthorizationRuleHandleResponse handles the GetAuthorizationRule response. +func (client *NotificationHubsClient) getAuthorizationRuleHandleResponse(resp *http.Response) (NotificationHubsGetAuthorizationRuleResponse, error) { + result := NotificationHubsGetAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleResource); err != nil { + return NotificationHubsGetAuthorizationRuleResponse{}, err + } + return result, nil +} + +// getAuthorizationRuleHandleError handles the GetAuthorizationRule error response. +func (client *NotificationHubsClient) getAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// GetPnsCredentials - Lists the PNS Credentials associated with a notification hub . +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) GetPnsCredentials(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsGetPnsCredentialsOptions) (NotificationHubsGetPnsCredentialsResponse, error) { + req, err := client.getPnsCredentialsCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + if err != nil { + return NotificationHubsGetPnsCredentialsResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsGetPnsCredentialsResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsGetPnsCredentialsResponse{}, client.getPnsCredentialsHandleError(resp) + } + return client.getPnsCredentialsHandleResponse(resp) +} + +// getPnsCredentialsCreateRequest creates the GetPnsCredentials request. +func (client *NotificationHubsClient) getPnsCredentialsCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsGetPnsCredentialsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/pnsCredentials" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getPnsCredentialsHandleResponse handles the GetPnsCredentials response. +func (client *NotificationHubsClient) getPnsCredentialsHandleResponse(resp *http.Response) (NotificationHubsGetPnsCredentialsResponse, error) { + result := NotificationHubsGetPnsCredentialsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PnsCredentialsResource); err != nil { + return NotificationHubsGetPnsCredentialsResponse{}, err + } + return result, nil +} + +// getPnsCredentialsHandleError handles the GetPnsCredentials error response. +func (client *NotificationHubsClient) getPnsCredentialsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// List - Lists the notification hubs associated with a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) List(resourceGroupName string, namespaceName string, options *NotificationHubsListOptions) *NotificationHubsListPager { + return &NotificationHubsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, namespaceName, options) + }, + advancer: func(ctx context.Context, resp NotificationHubsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.NotificationHubListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *NotificationHubsClient) listCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NotificationHubsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *NotificationHubsClient) listHandleResponse(resp *http.Response) (NotificationHubsListResponse, error) { + result := NotificationHubsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NotificationHubListResult); err != nil { + return NotificationHubsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *NotificationHubsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListAuthorizationRules - Gets the authorization rules for a NotificationHub. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) ListAuthorizationRules(resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsListAuthorizationRulesOptions) *NotificationHubsListAuthorizationRulesPager { + return &NotificationHubsListAuthorizationRulesPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAuthorizationRulesCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + }, + advancer: func(ctx context.Context, resp NotificationHubsListAuthorizationRulesResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SharedAccessAuthorizationRuleListResult.NextLink) + }, + } +} + +// listAuthorizationRulesCreateRequest creates the ListAuthorizationRules request. +func (client *NotificationHubsClient) listAuthorizationRulesCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsListAuthorizationRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAuthorizationRulesHandleResponse handles the ListAuthorizationRules response. +func (client *NotificationHubsClient) listAuthorizationRulesHandleResponse(resp *http.Response) (NotificationHubsListAuthorizationRulesResponse, error) { + result := NotificationHubsListAuthorizationRulesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedAccessAuthorizationRuleListResult); err != nil { + return NotificationHubsListAuthorizationRulesResponse{}, err + } + return result, nil +} + +// listAuthorizationRulesHandleError handles the ListAuthorizationRules error response. +func (client *NotificationHubsClient) listAuthorizationRulesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListKeys - Gets the Primary and Secondary ConnectionStrings to the NotificationHub +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsListKeysOptions) (NotificationHubsListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, options) + if err != nil { + return NotificationHubsListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *NotificationHubsClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, options *NotificationHubsListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *NotificationHubsClient) listKeysHandleResponse(resp *http.Response) (NotificationHubsListKeysResponse, error) { + result := NotificationHubsListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceListKeys); err != nil { + return NotificationHubsListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *NotificationHubsClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Patch - Patch a NotificationHub in a namespace. +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) Patch(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsPatchOptions) (NotificationHubsPatchResponse, error) { + req, err := client.patchCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, options) + if err != nil { + return NotificationHubsPatchResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsPatchResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsPatchResponse{}, client.patchHandleError(resp) + } + return client.patchHandleResponse(resp) +} + +// patchCreateRequest creates the Patch request. +func (client *NotificationHubsClient) patchCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, options *NotificationHubsPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Parameters != nil { + return req, runtime.MarshalAsJSON(req, *options.Parameters) + } + return req, nil +} + +// patchHandleResponse handles the Patch response. +func (client *NotificationHubsClient) patchHandleResponse(resp *http.Response) (NotificationHubsPatchResponse, error) { + result := NotificationHubsPatchResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.NotificationHubResource); err != nil { + return NotificationHubsPatchResponse{}, err + } + return result, nil +} + +// patchHandleError handles the Patch error response. +func (client *NotificationHubsClient) patchHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// RegenerateKeys - Regenerates the Primary/Secondary Keys to the NotificationHub Authorization Rule +// If the operation fails it returns a generic error. +func (client *NotificationHubsClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, parameters PolicykeyResource, options *NotificationHubsRegenerateKeysOptions) (NotificationHubsRegenerateKeysResponse, error) { + req, err := client.regenerateKeysCreateRequest(ctx, resourceGroupName, namespaceName, notificationHubName, authorizationRuleName, parameters, options) + if err != nil { + return NotificationHubsRegenerateKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NotificationHubsRegenerateKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NotificationHubsRegenerateKeysResponse{}, client.regenerateKeysHandleError(resp) + } + return client.regenerateKeysHandleResponse(resp) +} + +// regenerateKeysCreateRequest creates the RegenerateKeys request. +func (client *NotificationHubsClient) regenerateKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, notificationHubName string, authorizationRuleName string, parameters PolicykeyResource, options *NotificationHubsRegenerateKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NotificationHubs/namespaces/{namespaceName}/notificationHubs/{notificationHubName}/AuthorizationRules/{authorizationRuleName}/regenerateKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if notificationHubName == "" { + return nil, errors.New("parameter notificationHubName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{notificationHubName}", url.PathEscape(notificationHubName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeysHandleResponse handles the RegenerateKeys response. +func (client *NotificationHubsClient) regenerateKeysHandleResponse(resp *http.Response) (NotificationHubsRegenerateKeysResponse, error) { + result := NotificationHubsRegenerateKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ResourceListKeys); err != nil { + return NotificationHubsRegenerateKeysResponse{}, err + } + return result, nil +} + +// regenerateKeysHandleError handles the RegenerateKeys error response. +func (client *NotificationHubsClient) regenerateKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_operations_client.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_operations_client.go new file mode 100644 index 000000000000..4ba85102c070 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available NotificationHubs REST API operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.NotificationHubs/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pagers.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pagers.go new file mode 100644 index 000000000000..ebfc75754ca3 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pagers.go @@ -0,0 +1,342 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NamespacesListAllPager provides operations for iterating over paged responses. +type NamespacesListAllPager struct { + client *NamespacesClient + current NamespacesListAllResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListAllResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListAllPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListAllPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.NamespaceListResult.NextLink == nil || len(*p.current.NamespaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAllHandleError(resp) + return false + } + result, err := p.client.listAllHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListAllResponse page. +func (p *NamespacesListAllPager) PageResponse() NamespacesListAllResponse { + return p.current +} + +// NamespacesListAuthorizationRulesPager provides operations for iterating over paged responses. +type NamespacesListAuthorizationRulesPager struct { + client *NamespacesClient + current NamespacesListAuthorizationRulesResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListAuthorizationRulesResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListAuthorizationRulesPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListAuthorizationRulesPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SharedAccessAuthorizationRuleListResult.NextLink == nil || len(*p.current.SharedAccessAuthorizationRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAuthorizationRulesHandleError(resp) + return false + } + result, err := p.client.listAuthorizationRulesHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListAuthorizationRulesResponse page. +func (p *NamespacesListAuthorizationRulesPager) PageResponse() NamespacesListAuthorizationRulesResponse { + return p.current +} + +// NamespacesListPager provides operations for iterating over paged responses. +type NamespacesListPager struct { + client *NamespacesClient + current NamespacesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.NamespaceListResult.NextLink == nil || len(*p.current.NamespaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListResponse page. +func (p *NamespacesListPager) PageResponse() NamespacesListResponse { + return p.current +} + +// NotificationHubsListAuthorizationRulesPager provides operations for iterating over paged responses. +type NotificationHubsListAuthorizationRulesPager struct { + client *NotificationHubsClient + current NotificationHubsListAuthorizationRulesResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NotificationHubsListAuthorizationRulesResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NotificationHubsListAuthorizationRulesPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NotificationHubsListAuthorizationRulesPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SharedAccessAuthorizationRuleListResult.NextLink == nil || len(*p.current.SharedAccessAuthorizationRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAuthorizationRulesHandleError(resp) + return false + } + result, err := p.client.listAuthorizationRulesHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NotificationHubsListAuthorizationRulesResponse page. +func (p *NotificationHubsListAuthorizationRulesPager) PageResponse() NotificationHubsListAuthorizationRulesResponse { + return p.current +} + +// NotificationHubsListPager provides operations for iterating over paged responses. +type NotificationHubsListPager struct { + client *NotificationHubsClient + current NotificationHubsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NotificationHubsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NotificationHubsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NotificationHubsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.NotificationHubListResult.NextLink == nil || len(*p.current.NotificationHubListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NotificationHubsListResponse page. +func (p *NotificationHubsListPager) PageResponse() NotificationHubsListResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pollers.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pollers.go new file mode 100644 index 000000000000..65e6ba7287e0 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_pollers.go @@ -0,0 +1,59 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// NamespacesDeletePoller provides polling facilities until the operation reaches a terminal state. +type NamespacesDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *NamespacesDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *NamespacesDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final NamespacesDeleteResponse will be returned. +func (p *NamespacesDeletePoller) FinalResponse(ctx context.Context) (NamespacesDeleteResponse, error) { + respType := NamespacesDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return NamespacesDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *NamespacesDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_response_types.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_response_types.go new file mode 100644 index 000000000000..dad4dff2930e --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_response_types.go @@ -0,0 +1,367 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// NamespacesCheckAvailabilityResponse contains the response from method Namespaces.CheckAvailability. +type NamespacesCheckAvailabilityResponse struct { + NamespacesCheckAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCheckAvailabilityResult contains the result from method Namespaces.CheckAvailability. +type NamespacesCheckAvailabilityResult struct { + CheckAvailabilityResult +} + +// NamespacesCreateOrUpdateAuthorizationRuleResponse contains the response from method Namespaces.CreateOrUpdateAuthorizationRule. +type NamespacesCreateOrUpdateAuthorizationRuleResponse struct { + NamespacesCreateOrUpdateAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCreateOrUpdateAuthorizationRuleResult contains the result from method Namespaces.CreateOrUpdateAuthorizationRule. +type NamespacesCreateOrUpdateAuthorizationRuleResult struct { + SharedAccessAuthorizationRuleResource +} + +// NamespacesCreateOrUpdateResponse contains the response from method Namespaces.CreateOrUpdate. +type NamespacesCreateOrUpdateResponse struct { + NamespacesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCreateOrUpdateResult contains the result from method Namespaces.CreateOrUpdate. +type NamespacesCreateOrUpdateResult struct { + NamespaceResource +} + +// NamespacesDeleteAuthorizationRuleResponse contains the response from method Namespaces.DeleteAuthorizationRule. +type NamespacesDeleteAuthorizationRuleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesDeletePollerResponse contains the response from method Namespaces.Delete. +type NamespacesDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *NamespacesDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l NamespacesDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (NamespacesDeleteResponse, error) { + respType := NamespacesDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a NamespacesDeletePollerResponse from the provided client and resume token. +func (l *NamespacesDeletePollerResponse) Resume(ctx context.Context, client *NamespacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("NamespacesClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &NamespacesDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// NamespacesDeleteResponse contains the response from method Namespaces.Delete. +type NamespacesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetAuthorizationRuleResponse contains the response from method Namespaces.GetAuthorizationRule. +type NamespacesGetAuthorizationRuleResponse struct { + NamespacesGetAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetAuthorizationRuleResult contains the result from method Namespaces.GetAuthorizationRule. +type NamespacesGetAuthorizationRuleResult struct { + SharedAccessAuthorizationRuleResource +} + +// NamespacesGetResponse contains the response from method Namespaces.Get. +type NamespacesGetResponse struct { + NamespacesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetResult contains the result from method Namespaces.Get. +type NamespacesGetResult struct { + NamespaceResource +} + +// NamespacesListAllResponse contains the response from method Namespaces.ListAll. +type NamespacesListAllResponse struct { + NamespacesListAllResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListAllResult contains the result from method Namespaces.ListAll. +type NamespacesListAllResult struct { + NamespaceListResult +} + +// NamespacesListAuthorizationRulesResponse contains the response from method Namespaces.ListAuthorizationRules. +type NamespacesListAuthorizationRulesResponse struct { + NamespacesListAuthorizationRulesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListAuthorizationRulesResult contains the result from method Namespaces.ListAuthorizationRules. +type NamespacesListAuthorizationRulesResult struct { + SharedAccessAuthorizationRuleListResult +} + +// NamespacesListKeysResponse contains the response from method Namespaces.ListKeys. +type NamespacesListKeysResponse struct { + NamespacesListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListKeysResult contains the result from method Namespaces.ListKeys. +type NamespacesListKeysResult struct { + SharedAccessAuthorizationRuleListResult +} + +// NamespacesListResponse contains the response from method Namespaces.List. +type NamespacesListResponse struct { + NamespacesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListResult contains the result from method Namespaces.List. +type NamespacesListResult struct { + NamespaceListResult +} + +// NamespacesPatchResponse contains the response from method Namespaces.Patch. +type NamespacesPatchResponse struct { + NamespacesPatchResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesPatchResult contains the result from method Namespaces.Patch. +type NamespacesPatchResult struct { + NamespaceResource +} + +// NamespacesRegenerateKeysResponse contains the response from method Namespaces.RegenerateKeys. +type NamespacesRegenerateKeysResponse struct { + NamespacesRegenerateKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesRegenerateKeysResult contains the result from method Namespaces.RegenerateKeys. +type NamespacesRegenerateKeysResult struct { + ResourceListKeys +} + +// NotificationHubsCheckNotificationHubAvailabilityResponse contains the response from method NotificationHubs.CheckNotificationHubAvailability. +type NotificationHubsCheckNotificationHubAvailabilityResponse struct { + NotificationHubsCheckNotificationHubAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsCheckNotificationHubAvailabilityResult contains the result from method NotificationHubs.CheckNotificationHubAvailability. +type NotificationHubsCheckNotificationHubAvailabilityResult struct { + CheckAvailabilityResult +} + +// NotificationHubsCreateOrUpdateAuthorizationRuleResponse contains the response from method NotificationHubs.CreateOrUpdateAuthorizationRule. +type NotificationHubsCreateOrUpdateAuthorizationRuleResponse struct { + NotificationHubsCreateOrUpdateAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsCreateOrUpdateAuthorizationRuleResult contains the result from method NotificationHubs.CreateOrUpdateAuthorizationRule. +type NotificationHubsCreateOrUpdateAuthorizationRuleResult struct { + SharedAccessAuthorizationRuleResource +} + +// NotificationHubsCreateOrUpdateResponse contains the response from method NotificationHubs.CreateOrUpdate. +type NotificationHubsCreateOrUpdateResponse struct { + NotificationHubsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsCreateOrUpdateResult contains the result from method NotificationHubs.CreateOrUpdate. +type NotificationHubsCreateOrUpdateResult struct { + NotificationHubResource +} + +// NotificationHubsDebugSendResponse contains the response from method NotificationHubs.DebugSend. +type NotificationHubsDebugSendResponse struct { + NotificationHubsDebugSendResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsDebugSendResult contains the result from method NotificationHubs.DebugSend. +type NotificationHubsDebugSendResult struct { + DebugSendResponse +} + +// NotificationHubsDeleteAuthorizationRuleResponse contains the response from method NotificationHubs.DeleteAuthorizationRule. +type NotificationHubsDeleteAuthorizationRuleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsDeleteResponse contains the response from method NotificationHubs.Delete. +type NotificationHubsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsGetAuthorizationRuleResponse contains the response from method NotificationHubs.GetAuthorizationRule. +type NotificationHubsGetAuthorizationRuleResponse struct { + NotificationHubsGetAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsGetAuthorizationRuleResult contains the result from method NotificationHubs.GetAuthorizationRule. +type NotificationHubsGetAuthorizationRuleResult struct { + SharedAccessAuthorizationRuleResource +} + +// NotificationHubsGetPnsCredentialsResponse contains the response from method NotificationHubs.GetPnsCredentials. +type NotificationHubsGetPnsCredentialsResponse struct { + NotificationHubsGetPnsCredentialsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsGetPnsCredentialsResult contains the result from method NotificationHubs.GetPnsCredentials. +type NotificationHubsGetPnsCredentialsResult struct { + PnsCredentialsResource +} + +// NotificationHubsGetResponse contains the response from method NotificationHubs.Get. +type NotificationHubsGetResponse struct { + NotificationHubsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsGetResult contains the result from method NotificationHubs.Get. +type NotificationHubsGetResult struct { + NotificationHubResource +} + +// NotificationHubsListAuthorizationRulesResponse contains the response from method NotificationHubs.ListAuthorizationRules. +type NotificationHubsListAuthorizationRulesResponse struct { + NotificationHubsListAuthorizationRulesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsListAuthorizationRulesResult contains the result from method NotificationHubs.ListAuthorizationRules. +type NotificationHubsListAuthorizationRulesResult struct { + SharedAccessAuthorizationRuleListResult +} + +// NotificationHubsListKeysResponse contains the response from method NotificationHubs.ListKeys. +type NotificationHubsListKeysResponse struct { + NotificationHubsListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsListKeysResult contains the result from method NotificationHubs.ListKeys. +type NotificationHubsListKeysResult struct { + ResourceListKeys +} + +// NotificationHubsListResponse contains the response from method NotificationHubs.List. +type NotificationHubsListResponse struct { + NotificationHubsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsListResult contains the result from method NotificationHubs.List. +type NotificationHubsListResult struct { + NotificationHubListResult +} + +// NotificationHubsPatchResponse contains the response from method NotificationHubs.Patch. +type NotificationHubsPatchResponse struct { + NotificationHubsPatchResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsPatchResult contains the result from method NotificationHubs.Patch. +type NotificationHubsPatchResult struct { + NotificationHubResource +} + +// NotificationHubsRegenerateKeysResponse contains the response from method NotificationHubs.RegenerateKeys. +type NotificationHubsRegenerateKeysResponse struct { + NotificationHubsRegenerateKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NotificationHubsRegenerateKeysResult contains the result from method NotificationHubs.RegenerateKeys. +type NotificationHubsRegenerateKeysResult struct { + ResourceListKeys +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} diff --git a/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_time_rfc3339.go b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..ffb676153bd9 --- /dev/null +++ b/sdk/resourcemanager/notificationhubs/armnotificationhubs/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armnotificationhubs + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/CHANGELOG.md b/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/CHANGELOG.md +++ b/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/zz_generated_constants.go b/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/zz_generated_constants.go index 02903e3038e0..ed31e0671802 100644 --- a/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/zz_generated_constants.go +++ b/sdk/resourcemanager/operationsmanagement/armoperationsmanagement/zz_generated_constants.go @@ -10,5 +10,5 @@ package armoperationsmanagement const ( module = "armoperationsmanagement" - version = "v0.1.0" + version = "v0.1.1" ) diff --git a/sdk/resourcemanager/recoveryservices/armrecoveryservices/CHANGELOG.md b/sdk/resourcemanager/recoveryservices/armrecoveryservices/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/recoveryservices/armrecoveryservices/CHANGELOG.md +++ b/sdk/resourcemanager/recoveryservices/armrecoveryservices/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/recoveryservices/armrecoveryservices/zz_generated_constants.go b/sdk/resourcemanager/recoveryservices/armrecoveryservices/zz_generated_constants.go index 8dc9023e3a38..0450b6142300 100644 --- a/sdk/resourcemanager/recoveryservices/armrecoveryservices/zz_generated_constants.go +++ b/sdk/resourcemanager/recoveryservices/armrecoveryservices/zz_generated_constants.go @@ -10,7 +10,7 @@ package armrecoveryservices const ( module = "armrecoveryservices" - version = "v0.1.0" + version = "v0.1.1" ) // AuthType - Specifies the authentication type. diff --git a/sdk/resourcemanager/relay/armrelay/CHANGELOG.md b/sdk/resourcemanager/relay/armrelay/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/relay/armrelay/LICENSE.txt b/sdk/resourcemanager/relay/armrelay/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/relay/armrelay/README.md b/sdk/resourcemanager/relay/armrelay/README.md new file mode 100644 index 000000000000..670dba642153 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/README.md @@ -0,0 +1,76 @@ +# Azure Relay Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/relay/armrelay)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/relay/armrelay) + +The `armrelay` module provides operations for working with Azure Relay. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/relay/armrelay) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Relay module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/relay/armrelay +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Relay. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Relay + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Relay modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armrelay.NewHybridConnectionsClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Relay` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/relay/armrelay/autorest.md b/sdk/resourcemanager/relay/armrelay/autorest.md new file mode 100644 index 000000000000..e19e788c1c8b --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/769e09cac92c50b1f9fa6468775b7cb7de16bb06/specification/relay/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/769e09cac92c50b1f9fa6468775b7cb7de16bb06/specification/relay/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/relay/armrelay/build.go b/sdk/resourcemanager/relay/armrelay/build.go new file mode 100644 index 000000000000..f4674a1c5cbf --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/relay/armrelay + +package armrelay diff --git a/sdk/resourcemanager/relay/armrelay/ci.yml b/sdk/resourcemanager/relay/armrelay/ci.yml new file mode 100644 index 000000000000..cb68617afb49 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/relay/armrelay/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/relay/armrelay/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/relay/armrelay' diff --git a/sdk/resourcemanager/relay/armrelay/go.mod b/sdk/resourcemanager/relay/armrelay/go.mod new file mode 100644 index 000000000000..f4423119de30 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/relay/armrelay + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/relay/armrelay/go.sum b/sdk/resourcemanager/relay/armrelay/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/relay/armrelay/go_mod_tidy_hack.go b/sdk/resourcemanager/relay/armrelay/go_mod_tidy_hack.go new file mode 100644 index 000000000000..7614ac160563 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armrelay + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_constants.go b/sdk/resourcemanager/relay/armrelay/zz_generated_constants.go new file mode 100644 index 000000000000..d8c7723b7ee1 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_constants.go @@ -0,0 +1,135 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +const ( + module = "armrelay" + version = "v0.1.1" +) + +type AccessRights string + +const ( + AccessRightsManage AccessRights = "Manage" + AccessRightsSend AccessRights = "Send" + AccessRightsListen AccessRights = "Listen" +) + +// PossibleAccessRightsValues returns the possible values for the AccessRights const type. +func PossibleAccessRightsValues() []AccessRights { + return []AccessRights{ + AccessRightsManage, + AccessRightsSend, + AccessRightsListen, + } +} + +// ToPtr returns a *AccessRights pointing to the current value. +func (c AccessRights) ToPtr() *AccessRights { + return &c +} + +// KeyType - The access key to regenerate. +type KeyType string + +const ( + KeyTypePrimaryKey KeyType = "PrimaryKey" + KeyTypeSecondaryKey KeyType = "SecondaryKey" +) + +// PossibleKeyTypeValues returns the possible values for the KeyType const type. +func PossibleKeyTypeValues() []KeyType { + return []KeyType{ + KeyTypePrimaryKey, + KeyTypeSecondaryKey, + } +} + +// ToPtr returns a *KeyType pointing to the current value. +func (c KeyType) ToPtr() *KeyType { + return &c +} + +type ProvisioningStateEnum string + +const ( + ProvisioningStateEnumCreated ProvisioningStateEnum = "Created" + ProvisioningStateEnumSucceeded ProvisioningStateEnum = "Succeeded" + ProvisioningStateEnumDeleted ProvisioningStateEnum = "Deleted" + ProvisioningStateEnumFailed ProvisioningStateEnum = "Failed" + ProvisioningStateEnumUpdating ProvisioningStateEnum = "Updating" + ProvisioningStateEnumUnknown ProvisioningStateEnum = "Unknown" +) + +// PossibleProvisioningStateEnumValues returns the possible values for the ProvisioningStateEnum const type. +func PossibleProvisioningStateEnumValues() []ProvisioningStateEnum { + return []ProvisioningStateEnum{ + ProvisioningStateEnumCreated, + ProvisioningStateEnumSucceeded, + ProvisioningStateEnumDeleted, + ProvisioningStateEnumFailed, + ProvisioningStateEnumUpdating, + ProvisioningStateEnumUnknown, + } +} + +// ToPtr returns a *ProvisioningStateEnum pointing to the current value. +func (c ProvisioningStateEnum) ToPtr() *ProvisioningStateEnum { + return &c +} + +// Relaytype - WCF relay type. +type Relaytype string + +const ( + RelaytypeNetTCP Relaytype = "NetTcp" + RelaytypeHTTP Relaytype = "Http" +) + +// PossibleRelaytypeValues returns the possible values for the Relaytype const type. +func PossibleRelaytypeValues() []Relaytype { + return []Relaytype{ + RelaytypeNetTCP, + RelaytypeHTTP, + } +} + +// ToPtr returns a *Relaytype pointing to the current value. +func (c Relaytype) ToPtr() *Relaytype { + return &c +} + +// UnavailableReason - Specifies the reason for the unavailability of the service. +type UnavailableReason string + +const ( + UnavailableReasonNone UnavailableReason = "None" + UnavailableReasonInvalidName UnavailableReason = "InvalidName" + UnavailableReasonSubscriptionIsDisabled UnavailableReason = "SubscriptionIsDisabled" + UnavailableReasonNameInUse UnavailableReason = "NameInUse" + UnavailableReasonNameInLockdown UnavailableReason = "NameInLockdown" + UnavailableReasonTooManyNamespaceInCurrentSubscription UnavailableReason = "TooManyNamespaceInCurrentSubscription" +) + +// PossibleUnavailableReasonValues returns the possible values for the UnavailableReason const type. +func PossibleUnavailableReasonValues() []UnavailableReason { + return []UnavailableReason{ + UnavailableReasonNone, + UnavailableReasonInvalidName, + UnavailableReasonSubscriptionIsDisabled, + UnavailableReasonNameInUse, + UnavailableReasonNameInLockdown, + UnavailableReasonTooManyNamespaceInCurrentSubscription, + } +} + +// ToPtr returns a *UnavailableReason pointing to the current value. +func (c UnavailableReason) ToPtr() *UnavailableReason { + return &c +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_hybridconnections_client.go b/sdk/resourcemanager/relay/armrelay/zz_generated_hybridconnections_client.go new file mode 100644 index 000000000000..2a2517582a44 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_hybridconnections_client.go @@ -0,0 +1,717 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// HybridConnectionsClient contains the methods for the HybridConnections group. +// Don't use this type directly, use NewHybridConnectionsClient() instead. +type HybridConnectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewHybridConnectionsClient creates a new instance of HybridConnectionsClient with the specified values. +func NewHybridConnectionsClient(con *arm.Connection, subscriptionID string) *HybridConnectionsClient { + return &HybridConnectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates a service hybrid connection. This operation is idempotent. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, parameters HybridConnection, options *HybridConnectionsCreateOrUpdateOptions) (HybridConnectionsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, parameters, options) + if err != nil { + return HybridConnectionsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *HybridConnectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, parameters HybridConnection, options *HybridConnectionsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *HybridConnectionsClient) createOrUpdateHandleResponse(resp *http.Response) (HybridConnectionsCreateOrUpdateResponse, error) { + result := HybridConnectionsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HybridConnection); err != nil { + return HybridConnectionsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *HybridConnectionsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// CreateOrUpdateAuthorizationRule - Creates or updates an authorization rule for a hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, parameters AuthorizationRule, options *HybridConnectionsCreateOrUpdateAuthorizationRuleOptions) (HybridConnectionsCreateOrUpdateAuthorizationRuleResponse, error) { + req, err := client.createOrUpdateAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, parameters, options) + if err != nil { + return HybridConnectionsCreateOrUpdateAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsCreateOrUpdateAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsCreateOrUpdateAuthorizationRuleResponse{}, client.createOrUpdateAuthorizationRuleHandleError(resp) + } + return client.createOrUpdateAuthorizationRuleHandleResponse(resp) +} + +// createOrUpdateAuthorizationRuleCreateRequest creates the CreateOrUpdateAuthorizationRule request. +func (client *HybridConnectionsClient) createOrUpdateAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, parameters AuthorizationRule, options *HybridConnectionsCreateOrUpdateAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateAuthorizationRuleHandleResponse handles the CreateOrUpdateAuthorizationRule response. +func (client *HybridConnectionsClient) createOrUpdateAuthorizationRuleHandleResponse(resp *http.Response) (HybridConnectionsCreateOrUpdateAuthorizationRuleResponse, error) { + result := HybridConnectionsCreateOrUpdateAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return HybridConnectionsCreateOrUpdateAuthorizationRuleResponse{}, err + } + return result, nil +} + +// createOrUpdateAuthorizationRuleHandleError handles the CreateOrUpdateAuthorizationRule error response. +func (client *HybridConnectionsClient) createOrUpdateAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsDeleteOptions) (HybridConnectionsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, options) + if err != nil { + return HybridConnectionsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return HybridConnectionsDeleteResponse{}, client.deleteHandleError(resp) + } + return HybridConnectionsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *HybridConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *HybridConnectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// DeleteAuthorizationRule - Deletes a hybrid connection authorization rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsDeleteAuthorizationRuleOptions) (HybridConnectionsDeleteAuthorizationRuleResponse, error) { + req, err := client.deleteAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options) + if err != nil { + return HybridConnectionsDeleteAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsDeleteAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return HybridConnectionsDeleteAuthorizationRuleResponse{}, client.deleteAuthorizationRuleHandleError(resp) + } + return HybridConnectionsDeleteAuthorizationRuleResponse{RawResponse: resp}, nil +} + +// deleteAuthorizationRuleCreateRequest creates the DeleteAuthorizationRule request. +func (client *HybridConnectionsClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsDeleteAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteAuthorizationRuleHandleError handles the DeleteAuthorizationRule error response. +func (client *HybridConnectionsClient) deleteAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Returns the description for the specified hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsGetOptions) (HybridConnectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, options) + if err != nil { + return HybridConnectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *HybridConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *HybridConnectionsClient) getHandleResponse(resp *http.Response) (HybridConnectionsGetResponse, error) { + result := HybridConnectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HybridConnection); err != nil { + return HybridConnectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *HybridConnectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetAuthorizationRule - Hybrid connection authorization rule for a hybrid connection by name. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsGetAuthorizationRuleOptions) (HybridConnectionsGetAuthorizationRuleResponse, error) { + req, err := client.getAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options) + if err != nil { + return HybridConnectionsGetAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsGetAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsGetAuthorizationRuleResponse{}, client.getAuthorizationRuleHandleError(resp) + } + return client.getAuthorizationRuleHandleResponse(resp) +} + +// getAuthorizationRuleCreateRequest creates the GetAuthorizationRule request. +func (client *HybridConnectionsClient) getAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsGetAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAuthorizationRuleHandleResponse handles the GetAuthorizationRule response. +func (client *HybridConnectionsClient) getAuthorizationRuleHandleResponse(resp *http.Response) (HybridConnectionsGetAuthorizationRuleResponse, error) { + result := HybridConnectionsGetAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return HybridConnectionsGetAuthorizationRuleResponse{}, err + } + return result, nil +} + +// getAuthorizationRuleHandleError handles the GetAuthorizationRule error response. +func (client *HybridConnectionsClient) getAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListAuthorizationRules - Authorization rules for a hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) ListAuthorizationRules(resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsListAuthorizationRulesOptions) *HybridConnectionsListAuthorizationRulesPager { + return &HybridConnectionsListAuthorizationRulesPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAuthorizationRulesCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, options) + }, + advancer: func(ctx context.Context, resp HybridConnectionsListAuthorizationRulesResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AuthorizationRuleListResult.NextLink) + }, + } +} + +// listAuthorizationRulesCreateRequest creates the ListAuthorizationRules request. +func (client *HybridConnectionsClient) listAuthorizationRulesCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, options *HybridConnectionsListAuthorizationRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAuthorizationRulesHandleResponse handles the ListAuthorizationRules response. +func (client *HybridConnectionsClient) listAuthorizationRulesHandleResponse(resp *http.Response) (HybridConnectionsListAuthorizationRulesResponse, error) { + result := HybridConnectionsListAuthorizationRulesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRuleListResult); err != nil { + return HybridConnectionsListAuthorizationRulesResponse{}, err + } + return result, nil +} + +// listAuthorizationRulesHandleError handles the ListAuthorizationRules error response. +func (client *HybridConnectionsClient) listAuthorizationRulesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByNamespace - Lists the hybrid connection within the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) ListByNamespace(resourceGroupName string, namespaceName string, options *HybridConnectionsListByNamespaceOptions) *HybridConnectionsListByNamespacePager { + return &HybridConnectionsListByNamespacePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByNamespaceCreateRequest(ctx, resourceGroupName, namespaceName, options) + }, + advancer: func(ctx context.Context, resp HybridConnectionsListByNamespaceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.HybridConnectionListResult.NextLink) + }, + } +} + +// listByNamespaceCreateRequest creates the ListByNamespace request. +func (client *HybridConnectionsClient) listByNamespaceCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *HybridConnectionsListByNamespaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByNamespaceHandleResponse handles the ListByNamespace response. +func (client *HybridConnectionsClient) listByNamespaceHandleResponse(resp *http.Response) (HybridConnectionsListByNamespaceResponse, error) { + result := HybridConnectionsListByNamespaceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.HybridConnectionListResult); err != nil { + return HybridConnectionsListByNamespaceResponse{}, err + } + return result, nil +} + +// listByNamespaceHandleError handles the ListByNamespace error response. +func (client *HybridConnectionsClient) listByNamespaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListKeys - Primary and secondary connection strings to the hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsListKeysOptions) (HybridConnectionsListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, options) + if err != nil { + return HybridConnectionsListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *HybridConnectionsClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, options *HybridConnectionsListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *HybridConnectionsClient) listKeysHandleResponse(resp *http.Response) (HybridConnectionsListKeysResponse, error) { + result := HybridConnectionsListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return HybridConnectionsListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *HybridConnectionsClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// RegenerateKeys - Regenerates the primary or secondary connection strings to the hybrid connection. +// If the operation fails it returns the *ErrorResponse error type. +func (client *HybridConnectionsClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *HybridConnectionsRegenerateKeysOptions) (HybridConnectionsRegenerateKeysResponse, error) { + req, err := client.regenerateKeysCreateRequest(ctx, resourceGroupName, namespaceName, hybridConnectionName, authorizationRuleName, parameters, options) + if err != nil { + return HybridConnectionsRegenerateKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return HybridConnectionsRegenerateKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return HybridConnectionsRegenerateKeysResponse{}, client.regenerateKeysHandleError(resp) + } + return client.regenerateKeysHandleResponse(resp) +} + +// regenerateKeysCreateRequest creates the RegenerateKeys request. +func (client *HybridConnectionsClient) regenerateKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, hybridConnectionName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *HybridConnectionsRegenerateKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/hybridConnections/{hybridConnectionName}/authorizationRules/{authorizationRuleName}/regenerateKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if hybridConnectionName == "" { + return nil, errors.New("parameter hybridConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{hybridConnectionName}", url.PathEscape(hybridConnectionName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeysHandleResponse handles the RegenerateKeys response. +func (client *HybridConnectionsClient) regenerateKeysHandleResponse(resp *http.Response) (HybridConnectionsRegenerateKeysResponse, error) { + result := HybridConnectionsRegenerateKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return HybridConnectionsRegenerateKeysResponse{}, err + } + return result, nil +} + +// regenerateKeysHandleError handles the RegenerateKeys error response. +func (client *HybridConnectionsClient) regenerateKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_models.go b/sdk/resourcemanager/relay/armrelay/zz_generated_models.go new file mode 100644 index 000000000000..c03d73147dad --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_models.go @@ -0,0 +1,765 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AccessKeys - Namespace/Relay Connection String +type AccessKeys struct { + // A string that describes the authorization rule. + KeyName *string `json:"keyName,omitempty"` + + // Primary connection string of the created namespace authorization rule. + PrimaryConnectionString *string `json:"primaryConnectionString,omitempty"` + + // A base64-encoded 256-bit primary key for signing and validating the SAS token. + PrimaryKey *string `json:"primaryKey,omitempty"` + + // Secondary connection string of the created namespace authorization rule. + SecondaryConnectionString *string `json:"secondaryConnectionString,omitempty"` + + // A base64-encoded 256-bit secondary key for signing and validating the SAS token. + SecondaryKey *string `json:"secondaryKey,omitempty"` +} + +// AuthorizationRule - Description of a namespace authorization rule. +type AuthorizationRule struct { + Resource + // REQUIRED; Authorization rule properties. + Properties *AuthorizationRuleProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationRule. +func (a AuthorizationRule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// AuthorizationRuleListResult - The response from the list namespace operation. +type AuthorizationRuleListResult struct { + // Link to the next set of results. Not empty if value contains incomplete list of authorization rules. + NextLink *string `json:"nextLink,omitempty"` + + // Result of the list authorization rules operation. + Value []*AuthorizationRule `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationRuleListResult. +func (a AuthorizationRuleListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AuthorizationRuleProperties - Authorization rule properties. +type AuthorizationRuleProperties struct { + // REQUIRED; The rights associated with the rule. + Rights []*AccessRights `json:"rights,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AuthorizationRuleProperties. +func (a AuthorizationRuleProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "rights", a.Rights) + return json.Marshal(objectMap) +} + +// CheckNameAvailability - Description of the check name availability request properties. +type CheckNameAvailability struct { + // REQUIRED; The namespace name to check for availability. The namespace name can contain only letters, numbers, and hyphens. The namespace must start with + // a letter, and it must end with a letter or number. + Name *string `json:"name,omitempty"` +} + +// CheckNameAvailabilityResult - Description of the check name availability request properties. +type CheckNameAvailabilityResult struct { + // Value indicating namespace is available. Returns true if the namespace is available; otherwise, false. + NameAvailable *bool `json:"nameAvailable,omitempty"` + + // The reason for unavailability of a namespace. + Reason *UnavailableReason `json:"reason,omitempty"` + + // READ-ONLY; The detailed info regarding the reason associated with the namespace. + Message *string `json:"message,omitempty" azure:"ro"` +} + +// ErrorResponse - Error reponse indicates Relay service is not able to process the incoming request. The reason is provided in the error message. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // Error code. + Code *string `json:"code,omitempty"` + + // Error message indicating why the operation failed. + Message *string `json:"message,omitempty"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// HybridConnection - Description of hybrid connection resource. +type HybridConnection struct { + Resource + // Properties of the HybridConnection. + Properties *HybridConnectionProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type HybridConnection. +func (h HybridConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + h.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", h.Properties) + return json.Marshal(objectMap) +} + +// HybridConnectionListResult - The response of the list hybrid connection operation. +type HybridConnectionListResult struct { + // Link to the next set of results. Not empty if value contains incomplete list hybrid connection operation. + NextLink *string `json:"nextLink,omitempty"` + + // Result of the list hybrid connections. + Value []*HybridConnection `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type HybridConnectionListResult. +func (h HybridConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", h.NextLink) + populate(objectMap, "value", h.Value) + return json.Marshal(objectMap) +} + +// HybridConnectionProperties - Properties of the HybridConnection. +type HybridConnectionProperties struct { + // Returns true if client authorization is needed for this hybrid connection; otherwise, false. + RequiresClientAuthorization *bool `json:"requiresClientAuthorization,omitempty"` + + // The usermetadata is a placeholder to store user-defined string data for the hybrid connection endpoint. For example, it can be used to store descriptive + // data, such as a list of teams and their contact + // information. Also, user-defined configuration settings can be stored. + UserMetadata *string `json:"userMetadata,omitempty"` + + // READ-ONLY; The time the hybrid connection was created. + CreatedAt *time.Time `json:"createdAt,omitempty" azure:"ro"` + + // READ-ONLY; The number of listeners for this hybrid connection. Note that min : 1 and max:25 are supported. + ListenerCount *int32 `json:"listenerCount,omitempty" azure:"ro"` + + // READ-ONLY; The time the namespace was updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type HybridConnectionProperties. +func (h HybridConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(h.CreatedAt)) + populate(objectMap, "listenerCount", h.ListenerCount) + populate(objectMap, "requiresClientAuthorization", h.RequiresClientAuthorization) + populate(objectMap, "updatedAt", (*timeRFC3339)(h.UpdatedAt)) + populate(objectMap, "userMetadata", h.UserMetadata) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HybridConnectionProperties. +func (h *HybridConnectionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + h.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "listenerCount": + err = unpopulate(val, &h.ListenerCount) + delete(rawMsg, key) + case "requiresClientAuthorization": + err = unpopulate(val, &h.RequiresClientAuthorization) + delete(rawMsg, key) + case "updatedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + h.UpdatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "userMetadata": + err = unpopulate(val, &h.UserMetadata) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// HybridConnectionsCreateOrUpdateAuthorizationRuleOptions contains the optional parameters for the HybridConnections.CreateOrUpdateAuthorizationRule method. +type HybridConnectionsCreateOrUpdateAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsCreateOrUpdateOptions contains the optional parameters for the HybridConnections.CreateOrUpdate method. +type HybridConnectionsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsDeleteAuthorizationRuleOptions contains the optional parameters for the HybridConnections.DeleteAuthorizationRule method. +type HybridConnectionsDeleteAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsDeleteOptions contains the optional parameters for the HybridConnections.Delete method. +type HybridConnectionsDeleteOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsGetAuthorizationRuleOptions contains the optional parameters for the HybridConnections.GetAuthorizationRule method. +type HybridConnectionsGetAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsGetOptions contains the optional parameters for the HybridConnections.Get method. +type HybridConnectionsGetOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsListAuthorizationRulesOptions contains the optional parameters for the HybridConnections.ListAuthorizationRules method. +type HybridConnectionsListAuthorizationRulesOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsListByNamespaceOptions contains the optional parameters for the HybridConnections.ListByNamespace method. +type HybridConnectionsListByNamespaceOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsListKeysOptions contains the optional parameters for the HybridConnections.ListKeys method. +type HybridConnectionsListKeysOptions struct { + // placeholder for future optional parameters +} + +// HybridConnectionsRegenerateKeysOptions contains the optional parameters for the HybridConnections.RegenerateKeys method. +type HybridConnectionsRegenerateKeysOptions struct { + // placeholder for future optional parameters +} + +// NamespacesBeginCreateOrUpdateOptions contains the optional parameters for the Namespaces.BeginCreateOrUpdate method. +type NamespacesBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// NamespacesBeginDeleteOptions contains the optional parameters for the Namespaces.BeginDelete method. +type NamespacesBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// NamespacesCheckNameAvailabilityOptions contains the optional parameters for the Namespaces.CheckNameAvailability method. +type NamespacesCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// NamespacesCreateOrUpdateAuthorizationRuleOptions contains the optional parameters for the Namespaces.CreateOrUpdateAuthorizationRule method. +type NamespacesCreateOrUpdateAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesDeleteAuthorizationRuleOptions contains the optional parameters for the Namespaces.DeleteAuthorizationRule method. +type NamespacesDeleteAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesGetAuthorizationRuleOptions contains the optional parameters for the Namespaces.GetAuthorizationRule method. +type NamespacesGetAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// NamespacesGetOptions contains the optional parameters for the Namespaces.Get method. +type NamespacesGetOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListAuthorizationRulesOptions contains the optional parameters for the Namespaces.ListAuthorizationRules method. +type NamespacesListAuthorizationRulesOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListByResourceGroupOptions contains the optional parameters for the Namespaces.ListByResourceGroup method. +type NamespacesListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListKeysOptions contains the optional parameters for the Namespaces.ListKeys method. +type NamespacesListKeysOptions struct { + // placeholder for future optional parameters +} + +// NamespacesListOptions contains the optional parameters for the Namespaces.List method. +type NamespacesListOptions struct { + // placeholder for future optional parameters +} + +// NamespacesRegenerateKeysOptions contains the optional parameters for the Namespaces.RegenerateKeys method. +type NamespacesRegenerateKeysOptions struct { + // placeholder for future optional parameters +} + +// NamespacesUpdateOptions contains the optional parameters for the Namespaces.Update method. +type NamespacesUpdateOptions struct { + // placeholder for future optional parameters +} + +// Operation - A Relay REST API operation. +type Operation struct { + // The object that represents the operation. + Display *OperationDisplay `json:"display,omitempty"` + + // READ-ONLY; Operation name: {provider}/{resource}/{operation} + Name *string `json:"name,omitempty" azure:"ro"` +} + +// OperationDisplay - The object that represents the operation. +type OperationDisplay struct { + // READ-ONLY; Operation type: Read, write, delete, etc. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; Service provider: Relay. + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; Resource on which the operation is performed: Invoice, etc. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - Result of the request to list Relay operations. It contains a list of operations and a URL link to get the next set of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; List of Relay operations supported by resource provider. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// RegenerateAccessKeyParameters - Parameters supplied to the regenerate authorization rule operation, specifies which key neeeds to be reset. +type RegenerateAccessKeyParameters struct { + // REQUIRED; The access key to regenerate. + KeyType *KeyType `json:"keyType,omitempty"` + + // Optional. If the key value is provided, this is set to key type, or autogenerated key value set for key type. + Key *string `json:"key,omitempty"` +} + +// RelayNamespace - Description of a namespace resource. +type RelayNamespace struct { + TrackedResource + // Description of Relay namespace + Properties *RelayNamespaceProperties `json:"properties,omitempty"` + + // SKU of the namespace. + SKU *SKU `json:"sku,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RelayNamespace. +func (r RelayNamespace) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + return json.Marshal(objectMap) +} + +// RelayNamespaceListResult - The response from the list namespace operation. +type RelayNamespaceListResult struct { + // Link to the next set of results. Not empty if value contains incomplete list of namespaces. + NextLink *string `json:"nextLink,omitempty"` + + // Result of the list namespace operation. + Value []*RelayNamespace `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RelayNamespaceListResult. +func (r RelayNamespaceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", r.NextLink) + populate(objectMap, "value", r.Value) + return json.Marshal(objectMap) +} + +// RelayNamespaceProperties - Properties of the namespace. +type RelayNamespaceProperties struct { + // READ-ONLY; The time the namespace was created. + CreatedAt *time.Time `json:"createdAt,omitempty" azure:"ro"` + + // READ-ONLY; Identifier for Azure Insights metrics. + MetricID *string `json:"metricId,omitempty" azure:"ro"` + + // READ-ONLY + ProvisioningState *ProvisioningStateEnum `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; Endpoint you can use to perform Service Bus operations. + ServiceBusEndpoint *string `json:"serviceBusEndpoint,omitempty" azure:"ro"` + + // READ-ONLY; The time the namespace was updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type RelayNamespaceProperties. +func (r RelayNamespaceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(r.CreatedAt)) + populate(objectMap, "metricId", r.MetricID) + populate(objectMap, "provisioningState", r.ProvisioningState) + populate(objectMap, "serviceBusEndpoint", r.ServiceBusEndpoint) + populate(objectMap, "updatedAt", (*timeRFC3339)(r.UpdatedAt)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RelayNamespaceProperties. +func (r *RelayNamespaceProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + r.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "metricId": + err = unpopulate(val, &r.MetricID) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &r.ProvisioningState) + delete(rawMsg, key) + case "serviceBusEndpoint": + err = unpopulate(val, &r.ServiceBusEndpoint) + delete(rawMsg, key) + case "updatedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + r.UpdatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// RelayUpdateParameters - Description of a namespace resource. +type RelayUpdateParameters struct { + ResourceNamespacePatch + // Description of Relay namespace. + Properties *RelayNamespaceProperties `json:"properties,omitempty"` + + // SKU of the namespace. + SKU *SKU `json:"sku,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RelayUpdateParameters. +func (r RelayUpdateParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.ResourceNamespacePatch.marshalInternal(objectMap) + populate(objectMap, "properties", r.Properties) + populate(objectMap, "sku", r.SKU) + return json.Marshal(objectMap) +} + +// Resource - The resource definition. +type Resource struct { + // READ-ONLY; Resource ID. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +// ResourceNamespacePatch - Definition of resource. +type ResourceNamespacePatch struct { + Resource + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ResourceNamespacePatch. +func (r ResourceNamespacePatch) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r ResourceNamespacePatch) marshalInternal(objectMap map[string]interface{}) { + r.Resource.marshalInternal(objectMap) + populate(objectMap, "tags", r.Tags) +} + +// SKU of the namespace. +type SKU struct { + // REQUIRED; Name of this SKU. + Name *string `json:"name,omitempty"` + + // The tier of this SKU. + Tier *string `json:"tier,omitempty"` +} + +// TrackedResource - Definition of resource. +type TrackedResource struct { + Resource + // REQUIRED; Resource location. + Location *string `json:"location,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (t TrackedResource) marshalInternal(objectMap map[string]interface{}) { + t.Resource.marshalInternal(objectMap) + populate(objectMap, "location", t.Location) + populate(objectMap, "tags", t.Tags) +} + +// WCFRelaysCreateOrUpdateAuthorizationRuleOptions contains the optional parameters for the WCFRelays.CreateOrUpdateAuthorizationRule method. +type WCFRelaysCreateOrUpdateAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysCreateOrUpdateOptions contains the optional parameters for the WCFRelays.CreateOrUpdate method. +type WCFRelaysCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysDeleteAuthorizationRuleOptions contains the optional parameters for the WCFRelays.DeleteAuthorizationRule method. +type WCFRelaysDeleteAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysDeleteOptions contains the optional parameters for the WCFRelays.Delete method. +type WCFRelaysDeleteOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysGetAuthorizationRuleOptions contains the optional parameters for the WCFRelays.GetAuthorizationRule method. +type WCFRelaysGetAuthorizationRuleOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysGetOptions contains the optional parameters for the WCFRelays.Get method. +type WCFRelaysGetOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysListAuthorizationRulesOptions contains the optional parameters for the WCFRelays.ListAuthorizationRules method. +type WCFRelaysListAuthorizationRulesOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysListByNamespaceOptions contains the optional parameters for the WCFRelays.ListByNamespace method. +type WCFRelaysListByNamespaceOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysListKeysOptions contains the optional parameters for the WCFRelays.ListKeys method. +type WCFRelaysListKeysOptions struct { + // placeholder for future optional parameters +} + +// WCFRelaysRegenerateKeysOptions contains the optional parameters for the WCFRelays.RegenerateKeys method. +type WCFRelaysRegenerateKeysOptions struct { + // placeholder for future optional parameters +} + +// WcfRelay - Description of the WCF relay resource. +type WcfRelay struct { + Resource + // Properties of the WCF relay. + Properties *WcfRelayProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type WcfRelay. +func (w WcfRelay) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + w.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", w.Properties) + return json.Marshal(objectMap) +} + +// WcfRelayProperties - Properties of the WCF relay. +type WcfRelayProperties struct { + // WCF relay type. + RelayType *Relaytype `json:"relayType,omitempty"` + + // Returns true if client authorization is needed for this relay; otherwise, false. + RequiresClientAuthorization *bool `json:"requiresClientAuthorization,omitempty"` + + // Returns true if transport security is needed for this relay; otherwise, false. + RequiresTransportSecurity *bool `json:"requiresTransportSecurity,omitempty"` + + // The usermetadata is a placeholder to store user-defined string data for the WCF Relay endpoint. For example, it can be used to store descriptive data, + // such as list of teams and their contact + // information. Also, user-defined configuration settings can be stored. + UserMetadata *string `json:"userMetadata,omitempty"` + + // READ-ONLY; The time the WCF relay was created. + CreatedAt *time.Time `json:"createdAt,omitempty" azure:"ro"` + + // READ-ONLY; Returns true if the relay is dynamic; otherwise, false. + IsDynamic *bool `json:"isDynamic,omitempty" azure:"ro"` + + // READ-ONLY; The number of listeners for this relay. Note that min :1 and max:25 are supported. + ListenerCount *int32 `json:"listenerCount,omitempty" azure:"ro"` + + // READ-ONLY; The time the namespace was updated. + UpdatedAt *time.Time `json:"updatedAt,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type WcfRelayProperties. +func (w WcfRelayProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdAt", (*timeRFC3339)(w.CreatedAt)) + populate(objectMap, "isDynamic", w.IsDynamic) + populate(objectMap, "listenerCount", w.ListenerCount) + populate(objectMap, "relayType", w.RelayType) + populate(objectMap, "requiresClientAuthorization", w.RequiresClientAuthorization) + populate(objectMap, "requiresTransportSecurity", w.RequiresTransportSecurity) + populate(objectMap, "updatedAt", (*timeRFC3339)(w.UpdatedAt)) + populate(objectMap, "userMetadata", w.UserMetadata) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type WcfRelayProperties. +func (w *WcfRelayProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "createdAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + w.CreatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "isDynamic": + err = unpopulate(val, &w.IsDynamic) + delete(rawMsg, key) + case "listenerCount": + err = unpopulate(val, &w.ListenerCount) + delete(rawMsg, key) + case "relayType": + err = unpopulate(val, &w.RelayType) + delete(rawMsg, key) + case "requiresClientAuthorization": + err = unpopulate(val, &w.RequiresClientAuthorization) + delete(rawMsg, key) + case "requiresTransportSecurity": + err = unpopulate(val, &w.RequiresTransportSecurity) + delete(rawMsg, key) + case "updatedAt": + var aux timeRFC3339 + err = unpopulate(val, &aux) + w.UpdatedAt = (*time.Time)(&aux) + delete(rawMsg, key) + case "userMetadata": + err = unpopulate(val, &w.UserMetadata) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// WcfRelaysListResult - The response of the list WCF relay operation. +type WcfRelaysListResult struct { + // Link to the next set of results. Not empty if value contains incomplete list of WCF relays. + NextLink *string `json:"nextLink,omitempty"` + + // Result of the list WCF relay operation. + Value []*WcfRelay `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type WcfRelaysListResult. +func (w WcfRelaysListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", w.NextLink) + populate(objectMap, "value", w.Value) + return json.Marshal(objectMap) +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_namespaces_client.go b/sdk/resourcemanager/relay/armrelay/zz_generated_namespaces_client.go new file mode 100644 index 000000000000..486e770852b1 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_namespaces_client.go @@ -0,0 +1,885 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// NamespacesClient contains the methods for the Namespaces group. +// Don't use this type directly, use NewNamespacesClient() instead. +type NamespacesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewNamespacesClient creates a new instance of NamespacesClient with the specified values. +func NewNamespacesClient(con *arm.Connection, subscriptionID string) *NamespacesClient { + return &NamespacesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckNameAvailability - Check the specified namespace name availability. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) CheckNameAvailability(ctx context.Context, parameters CheckNameAvailability, options *NamespacesCheckNameAvailabilityOptions) (NamespacesCheckNameAvailabilityResponse, error) { + req, err := client.checkNameAvailabilityCreateRequest(ctx, parameters, options) + if err != nil { + return NamespacesCheckNameAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesCheckNameAvailabilityResponse{}, client.checkNameAvailabilityHandleError(resp) + } + return client.checkNameAvailabilityHandleResponse(resp) +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *NamespacesClient) checkNameAvailabilityCreateRequest(ctx context.Context, parameters CheckNameAvailability, options *NamespacesCheckNameAvailabilityOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *NamespacesClient) checkNameAvailabilityHandleResponse(resp *http.Response) (NamespacesCheckNameAvailabilityResponse, error) { + result := NamespacesCheckNameAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityResult); err != nil { + return NamespacesCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// checkNameAvailabilityHandleError handles the CheckNameAvailability error response. +func (client *NamespacesClient) checkNameAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginCreateOrUpdate - Create Azure Relay namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, parameters RelayNamespace, options *NamespacesBeginCreateOrUpdateOptions) (NamespacesCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return NamespacesCreateOrUpdatePollerResponse{}, err + } + result := NamespacesCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("NamespacesClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return NamespacesCreateOrUpdatePollerResponse{}, err + } + result.Poller = &NamespacesCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Create Azure Relay namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) createOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, parameters RelayNamespace, options *NamespacesBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *NamespacesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, parameters RelayNamespace, options *NamespacesBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *NamespacesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// CreateOrUpdateAuthorizationRule - Creates or updates an authorization rule for a namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters AuthorizationRule, options *NamespacesCreateOrUpdateAuthorizationRuleOptions) (NamespacesCreateOrUpdateAuthorizationRuleResponse, error) { + req, err := client.createOrUpdateAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters, options) + if err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, client.createOrUpdateAuthorizationRuleHandleError(resp) + } + return client.createOrUpdateAuthorizationRuleHandleResponse(resp) +} + +// createOrUpdateAuthorizationRuleCreateRequest creates the CreateOrUpdateAuthorizationRule request. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters AuthorizationRule, options *NamespacesCreateOrUpdateAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateAuthorizationRuleHandleResponse handles the CreateOrUpdateAuthorizationRule response. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleHandleResponse(resp *http.Response) (NamespacesCreateOrUpdateAuthorizationRuleResponse, error) { + result := NamespacesCreateOrUpdateAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return NamespacesCreateOrUpdateAuthorizationRuleResponse{}, err + } + return result, nil +} + +// createOrUpdateAuthorizationRuleHandleError handles the CreateOrUpdateAuthorizationRule error response. +func (client *NamespacesClient) createOrUpdateAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes an existing namespace. This operation also removes all associated resources under the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) BeginDelete(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (NamespacesDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return NamespacesDeletePollerResponse{}, err + } + result := NamespacesDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("NamespacesClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return NamespacesDeletePollerResponse{}, err + } + result.Poller = &NamespacesDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes an existing namespace. This operation also removes all associated resources under the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) deleteOperation(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *NamespacesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *NamespacesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// DeleteAuthorizationRule - Deletes a namespace authorization rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesDeleteAuthorizationRuleOptions) (NamespacesDeleteAuthorizationRuleResponse, error) { + req, err := client.deleteAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesDeleteAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesDeleteAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return NamespacesDeleteAuthorizationRuleResponse{}, client.deleteAuthorizationRuleHandleError(resp) + } + return NamespacesDeleteAuthorizationRuleResponse{RawResponse: resp}, nil +} + +// deleteAuthorizationRuleCreateRequest creates the DeleteAuthorizationRule request. +func (client *NamespacesClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesDeleteAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteAuthorizationRuleHandleError handles the DeleteAuthorizationRule error response. +func (client *NamespacesClient) deleteAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Returns the description for the specified namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesGetOptions) (NamespacesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, namespaceName, options) + if err != nil { + return NamespacesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *NamespacesClient) getCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *NamespacesClient) getHandleResponse(resp *http.Response) (NamespacesGetResponse, error) { + result := NamespacesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.RelayNamespace); err != nil { + return NamespacesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *NamespacesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetAuthorizationRule - Authorization rule for a namespace by name. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesGetAuthorizationRuleOptions) (NamespacesGetAuthorizationRuleResponse, error) { + req, err := client.getAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesGetAuthorizationRuleResponse{}, client.getAuthorizationRuleHandleError(resp) + } + return client.getAuthorizationRuleHandleResponse(resp) +} + +// getAuthorizationRuleCreateRequest creates the GetAuthorizationRule request. +func (client *NamespacesClient) getAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesGetAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAuthorizationRuleHandleResponse handles the GetAuthorizationRule response. +func (client *NamespacesClient) getAuthorizationRuleHandleResponse(resp *http.Response) (NamespacesGetAuthorizationRuleResponse, error) { + result := NamespacesGetAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return NamespacesGetAuthorizationRuleResponse{}, err + } + return result, nil +} + +// getAuthorizationRuleHandleError handles the GetAuthorizationRule error response. +func (client *NamespacesClient) getAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists all the available namespaces within the subscription regardless of the resourceGroups. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) List(options *NamespacesListOptions) *NamespacesListPager { + return &NamespacesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp NamespacesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.RelayNamespaceListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *NamespacesClient) listCreateRequest(ctx context.Context, options *NamespacesListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Relay/namespaces" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *NamespacesClient) listHandleResponse(resp *http.Response) (NamespacesListResponse, error) { + result := NamespacesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.RelayNamespaceListResult); err != nil { + return NamespacesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *NamespacesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListAuthorizationRules - Authorization rules for a namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) ListAuthorizationRules(resourceGroupName string, namespaceName string, options *NamespacesListAuthorizationRulesOptions) *NamespacesListAuthorizationRulesPager { + return &NamespacesListAuthorizationRulesPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAuthorizationRulesCreateRequest(ctx, resourceGroupName, namespaceName, options) + }, + advancer: func(ctx context.Context, resp NamespacesListAuthorizationRulesResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AuthorizationRuleListResult.NextLink) + }, + } +} + +// listAuthorizationRulesCreateRequest creates the ListAuthorizationRules request. +func (client *NamespacesClient) listAuthorizationRulesCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *NamespacesListAuthorizationRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAuthorizationRulesHandleResponse handles the ListAuthorizationRules response. +func (client *NamespacesClient) listAuthorizationRulesHandleResponse(resp *http.Response) (NamespacesListAuthorizationRulesResponse, error) { + result := NamespacesListAuthorizationRulesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRuleListResult); err != nil { + return NamespacesListAuthorizationRulesResponse{}, err + } + return result, nil +} + +// listAuthorizationRulesHandleError handles the ListAuthorizationRules error response. +func (client *NamespacesClient) listAuthorizationRulesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Lists all the available namespaces within the ResourceGroup. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) ListByResourceGroup(resourceGroupName string, options *NamespacesListByResourceGroupOptions) *NamespacesListByResourceGroupPager { + return &NamespacesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp NamespacesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.RelayNamespaceListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *NamespacesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *NamespacesListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *NamespacesClient) listByResourceGroupHandleResponse(resp *http.Response) (NamespacesListByResourceGroupResponse, error) { + result := NamespacesListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.RelayNamespaceListResult); err != nil { + return NamespacesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *NamespacesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListKeys - Primary and secondary connection strings to the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesListKeysOptions) (NamespacesListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, options) + if err != nil { + return NamespacesListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *NamespacesClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, options *NamespacesListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *NamespacesClient) listKeysHandleResponse(resp *http.Response) (NamespacesListKeysResponse, error) { + result := NamespacesListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return NamespacesListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *NamespacesClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// RegenerateKeys - Regenerates the primary or secondary connection strings to the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *NamespacesRegenerateKeysOptions) (NamespacesRegenerateKeysResponse, error) { + req, err := client.regenerateKeysCreateRequest(ctx, resourceGroupName, namespaceName, authorizationRuleName, parameters, options) + if err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return NamespacesRegenerateKeysResponse{}, client.regenerateKeysHandleError(resp) + } + return client.regenerateKeysHandleResponse(resp) +} + +// regenerateKeysCreateRequest creates the RegenerateKeys request. +func (client *NamespacesClient) regenerateKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *NamespacesRegenerateKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/authorizationRules/{authorizationRuleName}/regenerateKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeysHandleResponse handles the RegenerateKeys response. +func (client *NamespacesClient) regenerateKeysHandleResponse(resp *http.Response) (NamespacesRegenerateKeysResponse, error) { + result := NamespacesRegenerateKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return NamespacesRegenerateKeysResponse{}, err + } + return result, nil +} + +// regenerateKeysHandleError handles the RegenerateKeys error response. +func (client *NamespacesClient) regenerateKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Creates or updates a namespace. Once created, this namespace's resource manifest is immutable. This operation is idempotent. +// If the operation fails it returns the *ErrorResponse error type. +func (client *NamespacesClient) Update(ctx context.Context, resourceGroupName string, namespaceName string, parameters RelayUpdateParameters, options *NamespacesUpdateOptions) (NamespacesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, namespaceName, parameters, options) + if err != nil { + return NamespacesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return NamespacesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return NamespacesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *NamespacesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, parameters RelayUpdateParameters, options *NamespacesUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// updateHandleResponse handles the Update response. +func (client *NamespacesClient) updateHandleResponse(resp *http.Response) (NamespacesUpdateResponse, error) { + result := NamespacesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.RelayNamespace); err != nil { + return NamespacesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *NamespacesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_operations_client.go b/sdk/resourcemanager/relay/armrelay/zz_generated_operations_client.go new file mode 100644 index 000000000000..52e80e8895c3 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all available Relay REST API operations. +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Relay/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_pagers.go b/sdk/resourcemanager/relay/armrelay/zz_generated_pagers.go new file mode 100644 index 000000000000..4aa502153073 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_pagers.go @@ -0,0 +1,450 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// HybridConnectionsListAuthorizationRulesPager provides operations for iterating over paged responses. +type HybridConnectionsListAuthorizationRulesPager struct { + client *HybridConnectionsClient + current HybridConnectionsListAuthorizationRulesResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, HybridConnectionsListAuthorizationRulesResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *HybridConnectionsListAuthorizationRulesPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *HybridConnectionsListAuthorizationRulesPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AuthorizationRuleListResult.NextLink == nil || len(*p.current.AuthorizationRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAuthorizationRulesHandleError(resp) + return false + } + result, err := p.client.listAuthorizationRulesHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current HybridConnectionsListAuthorizationRulesResponse page. +func (p *HybridConnectionsListAuthorizationRulesPager) PageResponse() HybridConnectionsListAuthorizationRulesResponse { + return p.current +} + +// HybridConnectionsListByNamespacePager provides operations for iterating over paged responses. +type HybridConnectionsListByNamespacePager struct { + client *HybridConnectionsClient + current HybridConnectionsListByNamespaceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, HybridConnectionsListByNamespaceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *HybridConnectionsListByNamespacePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *HybridConnectionsListByNamespacePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.HybridConnectionListResult.NextLink == nil || len(*p.current.HybridConnectionListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByNamespaceHandleError(resp) + return false + } + result, err := p.client.listByNamespaceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current HybridConnectionsListByNamespaceResponse page. +func (p *HybridConnectionsListByNamespacePager) PageResponse() HybridConnectionsListByNamespaceResponse { + return p.current +} + +// NamespacesListAuthorizationRulesPager provides operations for iterating over paged responses. +type NamespacesListAuthorizationRulesPager struct { + client *NamespacesClient + current NamespacesListAuthorizationRulesResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListAuthorizationRulesResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListAuthorizationRulesPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListAuthorizationRulesPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AuthorizationRuleListResult.NextLink == nil || len(*p.current.AuthorizationRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAuthorizationRulesHandleError(resp) + return false + } + result, err := p.client.listAuthorizationRulesHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListAuthorizationRulesResponse page. +func (p *NamespacesListAuthorizationRulesPager) PageResponse() NamespacesListAuthorizationRulesResponse { + return p.current +} + +// NamespacesListByResourceGroupPager provides operations for iterating over paged responses. +type NamespacesListByResourceGroupPager struct { + client *NamespacesClient + current NamespacesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.RelayNamespaceListResult.NextLink == nil || len(*p.current.RelayNamespaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListByResourceGroupResponse page. +func (p *NamespacesListByResourceGroupPager) PageResponse() NamespacesListByResourceGroupResponse { + return p.current +} + +// NamespacesListPager provides operations for iterating over paged responses. +type NamespacesListPager struct { + client *NamespacesClient + current NamespacesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, NamespacesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *NamespacesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *NamespacesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.RelayNamespaceListResult.NextLink == nil || len(*p.current.RelayNamespaceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current NamespacesListResponse page. +func (p *NamespacesListPager) PageResponse() NamespacesListResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} + +// WCFRelaysListAuthorizationRulesPager provides operations for iterating over paged responses. +type WCFRelaysListAuthorizationRulesPager struct { + client *WCFRelaysClient + current WCFRelaysListAuthorizationRulesResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, WCFRelaysListAuthorizationRulesResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *WCFRelaysListAuthorizationRulesPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *WCFRelaysListAuthorizationRulesPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AuthorizationRuleListResult.NextLink == nil || len(*p.current.AuthorizationRuleListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listAuthorizationRulesHandleError(resp) + return false + } + result, err := p.client.listAuthorizationRulesHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current WCFRelaysListAuthorizationRulesResponse page. +func (p *WCFRelaysListAuthorizationRulesPager) PageResponse() WCFRelaysListAuthorizationRulesResponse { + return p.current +} + +// WCFRelaysListByNamespacePager provides operations for iterating over paged responses. +type WCFRelaysListByNamespacePager struct { + client *WCFRelaysClient + current WCFRelaysListByNamespaceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, WCFRelaysListByNamespaceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *WCFRelaysListByNamespacePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *WCFRelaysListByNamespacePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.WcfRelaysListResult.NextLink == nil || len(*p.current.WcfRelaysListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByNamespaceHandleError(resp) + return false + } + result, err := p.client.listByNamespaceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current WCFRelaysListByNamespaceResponse page. +func (p *WCFRelaysListByNamespacePager) PageResponse() WCFRelaysListByNamespaceResponse { + return p.current +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_pollers.go b/sdk/resourcemanager/relay/armrelay/zz_generated_pollers.go new file mode 100644 index 000000000000..01cf5def6e74 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_pollers.go @@ -0,0 +1,102 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// NamespacesCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type NamespacesCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *NamespacesCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *NamespacesCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final NamespacesCreateOrUpdateResponse will be returned. +func (p *NamespacesCreateOrUpdatePoller) FinalResponse(ctx context.Context) (NamespacesCreateOrUpdateResponse, error) { + respType := NamespacesCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.RelayNamespace) + if err != nil { + return NamespacesCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *NamespacesCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// NamespacesDeletePoller provides polling facilities until the operation reaches a terminal state. +type NamespacesDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *NamespacesDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *NamespacesDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final NamespacesDeleteResponse will be returned. +func (p *NamespacesDeletePoller) FinalResponse(ctx context.Context) (NamespacesDeleteResponse, error) { + respType := NamespacesDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return NamespacesDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *NamespacesDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_response_types.go b/sdk/resourcemanager/relay/armrelay/zz_generated_response_types.go new file mode 100644 index 000000000000..c9342a41cce7 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_response_types.go @@ -0,0 +1,465 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// HybridConnectionsCreateOrUpdateAuthorizationRuleResponse contains the response from method HybridConnections.CreateOrUpdateAuthorizationRule. +type HybridConnectionsCreateOrUpdateAuthorizationRuleResponse struct { + HybridConnectionsCreateOrUpdateAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsCreateOrUpdateAuthorizationRuleResult contains the result from method HybridConnections.CreateOrUpdateAuthorizationRule. +type HybridConnectionsCreateOrUpdateAuthorizationRuleResult struct { + AuthorizationRule +} + +// HybridConnectionsCreateOrUpdateResponse contains the response from method HybridConnections.CreateOrUpdate. +type HybridConnectionsCreateOrUpdateResponse struct { + HybridConnectionsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsCreateOrUpdateResult contains the result from method HybridConnections.CreateOrUpdate. +type HybridConnectionsCreateOrUpdateResult struct { + HybridConnection +} + +// HybridConnectionsDeleteAuthorizationRuleResponse contains the response from method HybridConnections.DeleteAuthorizationRule. +type HybridConnectionsDeleteAuthorizationRuleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsDeleteResponse contains the response from method HybridConnections.Delete. +type HybridConnectionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsGetAuthorizationRuleResponse contains the response from method HybridConnections.GetAuthorizationRule. +type HybridConnectionsGetAuthorizationRuleResponse struct { + HybridConnectionsGetAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsGetAuthorizationRuleResult contains the result from method HybridConnections.GetAuthorizationRule. +type HybridConnectionsGetAuthorizationRuleResult struct { + AuthorizationRule +} + +// HybridConnectionsGetResponse contains the response from method HybridConnections.Get. +type HybridConnectionsGetResponse struct { + HybridConnectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsGetResult contains the result from method HybridConnections.Get. +type HybridConnectionsGetResult struct { + HybridConnection +} + +// HybridConnectionsListAuthorizationRulesResponse contains the response from method HybridConnections.ListAuthorizationRules. +type HybridConnectionsListAuthorizationRulesResponse struct { + HybridConnectionsListAuthorizationRulesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsListAuthorizationRulesResult contains the result from method HybridConnections.ListAuthorizationRules. +type HybridConnectionsListAuthorizationRulesResult struct { + AuthorizationRuleListResult +} + +// HybridConnectionsListByNamespaceResponse contains the response from method HybridConnections.ListByNamespace. +type HybridConnectionsListByNamespaceResponse struct { + HybridConnectionsListByNamespaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsListByNamespaceResult contains the result from method HybridConnections.ListByNamespace. +type HybridConnectionsListByNamespaceResult struct { + HybridConnectionListResult +} + +// HybridConnectionsListKeysResponse contains the response from method HybridConnections.ListKeys. +type HybridConnectionsListKeysResponse struct { + HybridConnectionsListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsListKeysResult contains the result from method HybridConnections.ListKeys. +type HybridConnectionsListKeysResult struct { + AccessKeys +} + +// HybridConnectionsRegenerateKeysResponse contains the response from method HybridConnections.RegenerateKeys. +type HybridConnectionsRegenerateKeysResponse struct { + HybridConnectionsRegenerateKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// HybridConnectionsRegenerateKeysResult contains the result from method HybridConnections.RegenerateKeys. +type HybridConnectionsRegenerateKeysResult struct { + AccessKeys +} + +// NamespacesCheckNameAvailabilityResponse contains the response from method Namespaces.CheckNameAvailability. +type NamespacesCheckNameAvailabilityResponse struct { + NamespacesCheckNameAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCheckNameAvailabilityResult contains the result from method Namespaces.CheckNameAvailability. +type NamespacesCheckNameAvailabilityResult struct { + CheckNameAvailabilityResult +} + +// NamespacesCreateOrUpdateAuthorizationRuleResponse contains the response from method Namespaces.CreateOrUpdateAuthorizationRule. +type NamespacesCreateOrUpdateAuthorizationRuleResponse struct { + NamespacesCreateOrUpdateAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCreateOrUpdateAuthorizationRuleResult contains the result from method Namespaces.CreateOrUpdateAuthorizationRule. +type NamespacesCreateOrUpdateAuthorizationRuleResult struct { + AuthorizationRule +} + +// NamespacesCreateOrUpdatePollerResponse contains the response from method Namespaces.CreateOrUpdate. +type NamespacesCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *NamespacesCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l NamespacesCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (NamespacesCreateOrUpdateResponse, error) { + respType := NamespacesCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.RelayNamespace) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a NamespacesCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *NamespacesCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *NamespacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("NamespacesClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &NamespacesCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// NamespacesCreateOrUpdateResponse contains the response from method Namespaces.CreateOrUpdate. +type NamespacesCreateOrUpdateResponse struct { + NamespacesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesCreateOrUpdateResult contains the result from method Namespaces.CreateOrUpdate. +type NamespacesCreateOrUpdateResult struct { + RelayNamespace +} + +// NamespacesDeleteAuthorizationRuleResponse contains the response from method Namespaces.DeleteAuthorizationRule. +type NamespacesDeleteAuthorizationRuleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesDeletePollerResponse contains the response from method Namespaces.Delete. +type NamespacesDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *NamespacesDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l NamespacesDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (NamespacesDeleteResponse, error) { + respType := NamespacesDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a NamespacesDeletePollerResponse from the provided client and resume token. +func (l *NamespacesDeletePollerResponse) Resume(ctx context.Context, client *NamespacesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("NamespacesClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &NamespacesDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// NamespacesDeleteResponse contains the response from method Namespaces.Delete. +type NamespacesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetAuthorizationRuleResponse contains the response from method Namespaces.GetAuthorizationRule. +type NamespacesGetAuthorizationRuleResponse struct { + NamespacesGetAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetAuthorizationRuleResult contains the result from method Namespaces.GetAuthorizationRule. +type NamespacesGetAuthorizationRuleResult struct { + AuthorizationRule +} + +// NamespacesGetResponse contains the response from method Namespaces.Get. +type NamespacesGetResponse struct { + NamespacesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesGetResult contains the result from method Namespaces.Get. +type NamespacesGetResult struct { + RelayNamespace +} + +// NamespacesListAuthorizationRulesResponse contains the response from method Namespaces.ListAuthorizationRules. +type NamespacesListAuthorizationRulesResponse struct { + NamespacesListAuthorizationRulesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListAuthorizationRulesResult contains the result from method Namespaces.ListAuthorizationRules. +type NamespacesListAuthorizationRulesResult struct { + AuthorizationRuleListResult +} + +// NamespacesListByResourceGroupResponse contains the response from method Namespaces.ListByResourceGroup. +type NamespacesListByResourceGroupResponse struct { + NamespacesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListByResourceGroupResult contains the result from method Namespaces.ListByResourceGroup. +type NamespacesListByResourceGroupResult struct { + RelayNamespaceListResult +} + +// NamespacesListKeysResponse contains the response from method Namespaces.ListKeys. +type NamespacesListKeysResponse struct { + NamespacesListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListKeysResult contains the result from method Namespaces.ListKeys. +type NamespacesListKeysResult struct { + AccessKeys +} + +// NamespacesListResponse contains the response from method Namespaces.List. +type NamespacesListResponse struct { + NamespacesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesListResult contains the result from method Namespaces.List. +type NamespacesListResult struct { + RelayNamespaceListResult +} + +// NamespacesRegenerateKeysResponse contains the response from method Namespaces.RegenerateKeys. +type NamespacesRegenerateKeysResponse struct { + NamespacesRegenerateKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesRegenerateKeysResult contains the result from method Namespaces.RegenerateKeys. +type NamespacesRegenerateKeysResult struct { + AccessKeys +} + +// NamespacesUpdateResponse contains the response from method Namespaces.Update. +type NamespacesUpdateResponse struct { + NamespacesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// NamespacesUpdateResult contains the result from method Namespaces.Update. +type NamespacesUpdateResult struct { + RelayNamespace +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// WCFRelaysCreateOrUpdateAuthorizationRuleResponse contains the response from method WCFRelays.CreateOrUpdateAuthorizationRule. +type WCFRelaysCreateOrUpdateAuthorizationRuleResponse struct { + WCFRelaysCreateOrUpdateAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysCreateOrUpdateAuthorizationRuleResult contains the result from method WCFRelays.CreateOrUpdateAuthorizationRule. +type WCFRelaysCreateOrUpdateAuthorizationRuleResult struct { + AuthorizationRule +} + +// WCFRelaysCreateOrUpdateResponse contains the response from method WCFRelays.CreateOrUpdate. +type WCFRelaysCreateOrUpdateResponse struct { + WCFRelaysCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysCreateOrUpdateResult contains the result from method WCFRelays.CreateOrUpdate. +type WCFRelaysCreateOrUpdateResult struct { + WcfRelay +} + +// WCFRelaysDeleteAuthorizationRuleResponse contains the response from method WCFRelays.DeleteAuthorizationRule. +type WCFRelaysDeleteAuthorizationRuleResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysDeleteResponse contains the response from method WCFRelays.Delete. +type WCFRelaysDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysGetAuthorizationRuleResponse contains the response from method WCFRelays.GetAuthorizationRule. +type WCFRelaysGetAuthorizationRuleResponse struct { + WCFRelaysGetAuthorizationRuleResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysGetAuthorizationRuleResult contains the result from method WCFRelays.GetAuthorizationRule. +type WCFRelaysGetAuthorizationRuleResult struct { + AuthorizationRule +} + +// WCFRelaysGetResponse contains the response from method WCFRelays.Get. +type WCFRelaysGetResponse struct { + WCFRelaysGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysGetResult contains the result from method WCFRelays.Get. +type WCFRelaysGetResult struct { + WcfRelay +} + +// WCFRelaysListAuthorizationRulesResponse contains the response from method WCFRelays.ListAuthorizationRules. +type WCFRelaysListAuthorizationRulesResponse struct { + WCFRelaysListAuthorizationRulesResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysListAuthorizationRulesResult contains the result from method WCFRelays.ListAuthorizationRules. +type WCFRelaysListAuthorizationRulesResult struct { + AuthorizationRuleListResult +} + +// WCFRelaysListByNamespaceResponse contains the response from method WCFRelays.ListByNamespace. +type WCFRelaysListByNamespaceResponse struct { + WCFRelaysListByNamespaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysListByNamespaceResult contains the result from method WCFRelays.ListByNamespace. +type WCFRelaysListByNamespaceResult struct { + WcfRelaysListResult +} + +// WCFRelaysListKeysResponse contains the response from method WCFRelays.ListKeys. +type WCFRelaysListKeysResponse struct { + WCFRelaysListKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysListKeysResult contains the result from method WCFRelays.ListKeys. +type WCFRelaysListKeysResult struct { + AccessKeys +} + +// WCFRelaysRegenerateKeysResponse contains the response from method WCFRelays.RegenerateKeys. +type WCFRelaysRegenerateKeysResponse struct { + WCFRelaysRegenerateKeysResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// WCFRelaysRegenerateKeysResult contains the result from method WCFRelays.RegenerateKeys. +type WCFRelaysRegenerateKeysResult struct { + AccessKeys +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_time_rfc3339.go b/sdk/resourcemanager/relay/armrelay/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..27842fba2f8c --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/relay/armrelay/zz_generated_wcfrelays_client.go b/sdk/resourcemanager/relay/armrelay/zz_generated_wcfrelays_client.go new file mode 100644 index 000000000000..c7a924f24341 --- /dev/null +++ b/sdk/resourcemanager/relay/armrelay/zz_generated_wcfrelays_client.go @@ -0,0 +1,716 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armrelay + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// WCFRelaysClient contains the methods for the WCFRelays group. +// Don't use this type directly, use NewWCFRelaysClient() instead. +type WCFRelaysClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewWCFRelaysClient creates a new instance of WCFRelaysClient with the specified values. +func NewWCFRelaysClient(con *arm.Connection, subscriptionID string) *WCFRelaysClient { + return &WCFRelaysClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates or updates a WCF relay. This operation is idempotent. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, parameters WcfRelay, options *WCFRelaysCreateOrUpdateOptions) (WCFRelaysCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, namespaceName, relayName, parameters, options) + if err != nil { + return WCFRelaysCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WCFRelaysCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *WCFRelaysClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, parameters WcfRelay, options *WCFRelaysCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *WCFRelaysClient) createOrUpdateHandleResponse(resp *http.Response) (WCFRelaysCreateOrUpdateResponse, error) { + result := WCFRelaysCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.WcfRelay); err != nil { + return WCFRelaysCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *WCFRelaysClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// CreateOrUpdateAuthorizationRule - Creates or updates an authorization rule for a WCF relay. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) CreateOrUpdateAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, parameters AuthorizationRule, options *WCFRelaysCreateOrUpdateAuthorizationRuleOptions) (WCFRelaysCreateOrUpdateAuthorizationRuleResponse, error) { + req, err := client.createOrUpdateAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters, options) + if err != nil { + return WCFRelaysCreateOrUpdateAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysCreateOrUpdateAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WCFRelaysCreateOrUpdateAuthorizationRuleResponse{}, client.createOrUpdateAuthorizationRuleHandleError(resp) + } + return client.createOrUpdateAuthorizationRuleHandleResponse(resp) +} + +// createOrUpdateAuthorizationRuleCreateRequest creates the CreateOrUpdateAuthorizationRule request. +func (client *WCFRelaysClient) createOrUpdateAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, parameters AuthorizationRule, options *WCFRelaysCreateOrUpdateAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// createOrUpdateAuthorizationRuleHandleResponse handles the CreateOrUpdateAuthorizationRule response. +func (client *WCFRelaysClient) createOrUpdateAuthorizationRuleHandleResponse(resp *http.Response) (WCFRelaysCreateOrUpdateAuthorizationRuleResponse, error) { + result := WCFRelaysCreateOrUpdateAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return WCFRelaysCreateOrUpdateAuthorizationRuleResponse{}, err + } + return result, nil +} + +// createOrUpdateAuthorizationRuleHandleError handles the CreateOrUpdateAuthorizationRule error response. +func (client *WCFRelaysClient) createOrUpdateAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a WCF relay. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) Delete(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysDeleteOptions) (WCFRelaysDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, namespaceName, relayName, options) + if err != nil { + return WCFRelaysDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return WCFRelaysDeleteResponse{}, client.deleteHandleError(resp) + } + return WCFRelaysDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *WCFRelaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *WCFRelaysClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// DeleteAuthorizationRule - Deletes a WCF relay authorization rule. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) DeleteAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysDeleteAuthorizationRuleOptions) (WCFRelaysDeleteAuthorizationRuleResponse, error) { + req, err := client.deleteAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, relayName, authorizationRuleName, options) + if err != nil { + return WCFRelaysDeleteAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysDeleteAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return WCFRelaysDeleteAuthorizationRuleResponse{}, client.deleteAuthorizationRuleHandleError(resp) + } + return WCFRelaysDeleteAuthorizationRuleResponse{RawResponse: resp}, nil +} + +// deleteAuthorizationRuleCreateRequest creates the DeleteAuthorizationRule request. +func (client *WCFRelaysClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysDeleteAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteAuthorizationRuleHandleError handles the DeleteAuthorizationRule error response. +func (client *WCFRelaysClient) deleteAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Returns the description for the specified WCF relay. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) Get(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysGetOptions) (WCFRelaysGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, namespaceName, relayName, options) + if err != nil { + return WCFRelaysGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return WCFRelaysGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *WCFRelaysClient) getCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *WCFRelaysClient) getHandleResponse(resp *http.Response) (WCFRelaysGetResponse, error) { + result := WCFRelaysGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.WcfRelay); err != nil { + return WCFRelaysGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *WCFRelaysClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// GetAuthorizationRule - Get authorizationRule for a WCF relay by name. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) GetAuthorizationRule(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysGetAuthorizationRuleOptions) (WCFRelaysGetAuthorizationRuleResponse, error) { + req, err := client.getAuthorizationRuleCreateRequest(ctx, resourceGroupName, namespaceName, relayName, authorizationRuleName, options) + if err != nil { + return WCFRelaysGetAuthorizationRuleResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysGetAuthorizationRuleResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WCFRelaysGetAuthorizationRuleResponse{}, client.getAuthorizationRuleHandleError(resp) + } + return client.getAuthorizationRuleHandleResponse(resp) +} + +// getAuthorizationRuleCreateRequest creates the GetAuthorizationRule request. +func (client *WCFRelaysClient) getAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysGetAuthorizationRuleOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getAuthorizationRuleHandleResponse handles the GetAuthorizationRule response. +func (client *WCFRelaysClient) getAuthorizationRuleHandleResponse(resp *http.Response) (WCFRelaysGetAuthorizationRuleResponse, error) { + result := WCFRelaysGetAuthorizationRuleResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRule); err != nil { + return WCFRelaysGetAuthorizationRuleResponse{}, err + } + return result, nil +} + +// getAuthorizationRuleHandleError handles the GetAuthorizationRule error response. +func (client *WCFRelaysClient) getAuthorizationRuleHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListAuthorizationRules - Authorization rules for a WCF relay. +// If the operation fails it returns a generic error. +func (client *WCFRelaysClient) ListAuthorizationRules(resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysListAuthorizationRulesOptions) *WCFRelaysListAuthorizationRulesPager { + return &WCFRelaysListAuthorizationRulesPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listAuthorizationRulesCreateRequest(ctx, resourceGroupName, namespaceName, relayName, options) + }, + advancer: func(ctx context.Context, resp WCFRelaysListAuthorizationRulesResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AuthorizationRuleListResult.NextLink) + }, + } +} + +// listAuthorizationRulesCreateRequest creates the ListAuthorizationRules request. +func (client *WCFRelaysClient) listAuthorizationRulesCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysListAuthorizationRulesOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listAuthorizationRulesHandleResponse handles the ListAuthorizationRules response. +func (client *WCFRelaysClient) listAuthorizationRulesHandleResponse(resp *http.Response) (WCFRelaysListAuthorizationRulesResponse, error) { + result := WCFRelaysListAuthorizationRulesResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AuthorizationRuleListResult); err != nil { + return WCFRelaysListAuthorizationRulesResponse{}, err + } + return result, nil +} + +// listAuthorizationRulesHandleError handles the ListAuthorizationRules error response. +func (client *WCFRelaysClient) listAuthorizationRulesHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListByNamespace - Lists the WCF relays within the namespace. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) ListByNamespace(resourceGroupName string, namespaceName string, options *WCFRelaysListByNamespaceOptions) *WCFRelaysListByNamespacePager { + return &WCFRelaysListByNamespacePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByNamespaceCreateRequest(ctx, resourceGroupName, namespaceName, options) + }, + advancer: func(ctx context.Context, resp WCFRelaysListByNamespaceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.WcfRelaysListResult.NextLink) + }, + } +} + +// listByNamespaceCreateRequest creates the ListByNamespace request. +func (client *WCFRelaysClient) listByNamespaceCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, options *WCFRelaysListByNamespaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByNamespaceHandleResponse handles the ListByNamespace response. +func (client *WCFRelaysClient) listByNamespaceHandleResponse(resp *http.Response) (WCFRelaysListByNamespaceResponse, error) { + result := WCFRelaysListByNamespaceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.WcfRelaysListResult); err != nil { + return WCFRelaysListByNamespaceResponse{}, err + } + return result, nil +} + +// listByNamespaceHandleError handles the ListByNamespace error response. +func (client *WCFRelaysClient) listByNamespaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListKeys - Primary and secondary connection strings to the WCF relay. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) ListKeys(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysListKeysOptions) (WCFRelaysListKeysResponse, error) { + req, err := client.listKeysCreateRequest(ctx, resourceGroupName, namespaceName, relayName, authorizationRuleName, options) + if err != nil { + return WCFRelaysListKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysListKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WCFRelaysListKeysResponse{}, client.listKeysHandleError(resp) + } + return client.listKeysHandleResponse(resp) +} + +// listKeysCreateRequest creates the ListKeys request. +func (client *WCFRelaysClient) listKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysListKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/listKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listKeysHandleResponse handles the ListKeys response. +func (client *WCFRelaysClient) listKeysHandleResponse(resp *http.Response) (WCFRelaysListKeysResponse, error) { + result := WCFRelaysListKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return WCFRelaysListKeysResponse{}, err + } + return result, nil +} + +// listKeysHandleError handles the ListKeys error response. +func (client *WCFRelaysClient) listKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// RegenerateKeys - Regenerates the primary or secondary connection strings to the WCF relay. +// If the operation fails it returns the *ErrorResponse error type. +func (client *WCFRelaysClient) RegenerateKeys(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *WCFRelaysRegenerateKeysOptions) (WCFRelaysRegenerateKeysResponse, error) { + req, err := client.regenerateKeysCreateRequest(ctx, resourceGroupName, namespaceName, relayName, authorizationRuleName, parameters, options) + if err != nil { + return WCFRelaysRegenerateKeysResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return WCFRelaysRegenerateKeysResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return WCFRelaysRegenerateKeysResponse{}, client.regenerateKeysHandleError(resp) + } + return client.regenerateKeysHandleResponse(resp) +} + +// regenerateKeysCreateRequest creates the RegenerateKeys request. +func (client *WCFRelaysClient) regenerateKeysCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, parameters RegenerateAccessKeyParameters, options *WCFRelaysRegenerateKeysOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}/regenerateKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if namespaceName == "" { + return nil, errors.New("parameter namespaceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{namespaceName}", url.PathEscape(namespaceName)) + if relayName == "" { + return nil, errors.New("parameter relayName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{relayName}", url.PathEscape(relayName)) + if authorizationRuleName == "" { + return nil, errors.New("parameter authorizationRuleName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{authorizationRuleName}", url.PathEscape(authorizationRuleName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, parameters) +} + +// regenerateKeysHandleResponse handles the RegenerateKeys response. +func (client *WCFRelaysClient) regenerateKeysHandleResponse(resp *http.Response) (WCFRelaysRegenerateKeysResponse, error) { + result := WCFRelaysRegenerateKeysResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AccessKeys); err != nil { + return WCFRelaysRegenerateKeysResponse{}, err + } + return result, nil +} + +// regenerateKeysHandleError handles the RegenerateKeys error response. +func (client *WCFRelaysClient) regenerateKeysHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/CHANGELOG.md b/sdk/resourcemanager/resourcehealth/armresourcehealth/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/LICENSE.txt b/sdk/resourcemanager/resourcehealth/armresourcehealth/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/README.md b/sdk/resourcemanager/resourcehealth/armresourcehealth/README.md new file mode 100644 index 000000000000..86c018ee9e4d --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/README.md @@ -0,0 +1,76 @@ +# Azure Resource Health Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcehealth/armresourcehealth)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcehealth/armresourcehealth) + +The `armresourcehealth` module provides operations for working with Azure Resource Health. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/resourcehealth/armresourcehealth) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Resource Health module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcehealth/armresourcehealth +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Resource Health. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Resource Health + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Resource Health modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armresourcehealth.NewAvailabilityStatusesClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Resource Health` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/autorest.md b/sdk/resourcemanager/resourcehealth/armresourcehealth/autorest.md new file mode 100644 index 000000000000..c794d32758ab --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/4aebac1bd77282ae8efe3dd2886e864537d31762/specification/resourcehealth/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/4aebac1bd77282ae8efe3dd2886e864537d31762/specification/resourcehealth/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/build.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/build.go new file mode 100644 index 000000000000..3f5b8a7de2e0 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/resourcehealth/armresourcehealth + +package armresourcehealth diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/ci.yml b/sdk/resourcemanager/resourcehealth/armresourcehealth/ci.yml new file mode 100644 index 000000000000..ffbdaf25a020 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/resourcehealth/armresourcehealth/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/resourcehealth/armresourcehealth/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/resourcehealth/armresourcehealth' diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/go.mod b/sdk/resourcemanager/resourcehealth/armresourcehealth/go.mod new file mode 100644 index 000000000000..0d01c484e8f6 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resourcehealth/armresourcehealth + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.3.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/go.sum b/sdk/resourcemanager/resourcehealth/armresourcehealth/go.sum new file mode 100644 index 000000000000..af10d0f1292e --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible h1:lb9OWePNuJMiibdxg9XvdbiOldR0Yifge37L4LoOxIs= +github.com/Azure/azure-sdk-for-go v58.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/go_mod_tidy_hack.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/go_mod_tidy_hack.go new file mode 100644 index 000000000000..8681f562c371 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armresourcehealth + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_availabilitystatuses_client.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_availabilitystatuses_client.go new file mode 100644 index 000000000000..3b84fa8bb57b --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_availabilitystatuses_client.go @@ -0,0 +1,285 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AvailabilityStatusesClient contains the methods for the AvailabilityStatuses group. +// Don't use this type directly, use NewAvailabilityStatusesClient() instead. +type AvailabilityStatusesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAvailabilityStatusesClient creates a new instance of AvailabilityStatusesClient with the specified values. +func NewAvailabilityStatusesClient(con *arm.Connection, subscriptionID string) *AvailabilityStatusesClient { + return &AvailabilityStatusesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// GetByResource - Gets current availability status for a single resource +// If the operation fails it returns the *ErrorResponse error type. +func (client *AvailabilityStatusesClient) GetByResource(ctx context.Context, resourceURI string, options *AvailabilityStatusesGetByResourceOptions) (AvailabilityStatusesGetByResourceResponse, error) { + req, err := client.getByResourceCreateRequest(ctx, resourceURI, options) + if err != nil { + return AvailabilityStatusesGetByResourceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AvailabilityStatusesGetByResourceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AvailabilityStatusesGetByResourceResponse{}, client.getByResourceHandleError(resp) + } + return client.getByResourceHandleResponse(resp) +} + +// getByResourceCreateRequest creates the GetByResource request. +func (client *AvailabilityStatusesClient) getByResourceCreateRequest(ctx context.Context, resourceURI string, options *AvailabilityStatusesGetByResourceOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses/current" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getByResourceHandleResponse handles the GetByResource response. +func (client *AvailabilityStatusesClient) getByResourceHandleResponse(resp *http.Response) (AvailabilityStatusesGetByResourceResponse, error) { + result := AvailabilityStatusesGetByResourceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatus); err != nil { + return AvailabilityStatusesGetByResourceResponse{}, err + } + return result, nil +} + +// getByResourceHandleError handles the GetByResource error response. +func (client *AvailabilityStatusesClient) getByResourceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists all historical availability transitions and impacting events for a single resource. Use the nextLink property in the response to get the +// next page of availability status +// If the operation fails it returns the *ErrorResponse error type. +func (client *AvailabilityStatusesClient) List(resourceURI string, options *AvailabilityStatusesListOptions) *AvailabilityStatusesListPager { + return &AvailabilityStatusesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, + advancer: func(ctx context.Context, resp AvailabilityStatusesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilityStatusListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *AvailabilityStatusesClient) listCreateRequest(ctx context.Context, resourceURI string, options *AvailabilityStatusesListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ResourceHealth/availabilityStatuses" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *AvailabilityStatusesClient) listHandleResponse(resp *http.Response) (AvailabilityStatusesListResponse, error) { + result := AvailabilityStatusesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatusListResult); err != nil { + return AvailabilityStatusesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *AvailabilityStatusesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Lists the current availability status for all the resources in the resource group. Use the nextLink property in the response to +// get the next page of availability statuses. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AvailabilityStatusesClient) ListByResourceGroup(resourceGroupName string, options *AvailabilityStatusesListByResourceGroupOptions) *AvailabilityStatusesListByResourceGroupPager { + return &AvailabilityStatusesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp AvailabilityStatusesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilityStatusListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *AvailabilityStatusesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *AvailabilityStatusesListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ResourceHealth/availabilityStatuses" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *AvailabilityStatusesClient) listByResourceGroupHandleResponse(resp *http.Response) (AvailabilityStatusesListByResourceGroupResponse, error) { + result := AvailabilityStatusesListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatusListResult); err != nil { + return AvailabilityStatusesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *AvailabilityStatusesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscriptionID - Lists the current availability status for all the resources in the subscription. Use the nextLink property in the response to +// get the next page of availability statuses. +// If the operation fails it returns the *ErrorResponse error type. +func (client *AvailabilityStatusesClient) ListBySubscriptionID(options *AvailabilityStatusesListBySubscriptionIDOptions) *AvailabilityStatusesListBySubscriptionIDPager { + return &AvailabilityStatusesListBySubscriptionIDPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionIDCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp AvailabilityStatusesListBySubscriptionIDResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilityStatusListResult.NextLink) + }, + } +} + +// listBySubscriptionIDCreateRequest creates the ListBySubscriptionID request. +func (client *AvailabilityStatusesClient) listBySubscriptionIDCreateRequest(ctx context.Context, options *AvailabilityStatusesListBySubscriptionIDOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.ResourceHealth/availabilityStatuses" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionIDHandleResponse handles the ListBySubscriptionID response. +func (client *AvailabilityStatusesClient) listBySubscriptionIDHandleResponse(resp *http.Response) (AvailabilityStatusesListBySubscriptionIDResponse, error) { + result := AvailabilityStatusesListBySubscriptionIDResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatusListResult); err != nil { + return AvailabilityStatusesListBySubscriptionIDResponse{}, err + } + return result, nil +} + +// listBySubscriptionIDHandleError handles the ListBySubscriptionID error response. +func (client *AvailabilityStatusesClient) listBySubscriptionIDHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childavailabilitystatuses_client.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childavailabilitystatuses_client.go new file mode 100644 index 000000000000..8c4ac18570e8 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childavailabilitystatuses_client.go @@ -0,0 +1,157 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ChildAvailabilityStatusesClient contains the methods for the ChildAvailabilityStatuses group. +// Don't use this type directly, use NewChildAvailabilityStatusesClient() instead. +type ChildAvailabilityStatusesClient struct { + ep string + pl runtime.Pipeline +} + +// NewChildAvailabilityStatusesClient creates a new instance of ChildAvailabilityStatusesClient with the specified values. +func NewChildAvailabilityStatusesClient(con *arm.Connection) *ChildAvailabilityStatusesClient { + return &ChildAvailabilityStatusesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// GetByResource - Gets current availability status for a single resource +// If the operation fails it returns the *ErrorResponse error type. +func (client *ChildAvailabilityStatusesClient) GetByResource(ctx context.Context, resourceURI string, options *ChildAvailabilityStatusesGetByResourceOptions) (ChildAvailabilityStatusesGetByResourceResponse, error) { + req, err := client.getByResourceCreateRequest(ctx, resourceURI, options) + if err != nil { + return ChildAvailabilityStatusesGetByResourceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ChildAvailabilityStatusesGetByResourceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ChildAvailabilityStatusesGetByResourceResponse{}, client.getByResourceHandleError(resp) + } + return client.getByResourceHandleResponse(resp) +} + +// getByResourceCreateRequest creates the GetByResource request. +func (client *ChildAvailabilityStatusesClient) getByResourceCreateRequest(ctx context.Context, resourceURI string, options *ChildAvailabilityStatusesGetByResourceOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ResourceHealth/childAvailabilityStatuses/current" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getByResourceHandleResponse handles the GetByResource response. +func (client *ChildAvailabilityStatusesClient) getByResourceHandleResponse(resp *http.Response) (ChildAvailabilityStatusesGetByResourceResponse, error) { + result := ChildAvailabilityStatusesGetByResourceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatus); err != nil { + return ChildAvailabilityStatusesGetByResourceResponse{}, err + } + return result, nil +} + +// getByResourceHandleError handles the GetByResource error response. +func (client *ChildAvailabilityStatusesClient) getByResourceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists the historical availability statuses for a single child resource. Use the nextLink property in the response to get the next page of availability +// status +// If the operation fails it returns the *ErrorResponse error type. +func (client *ChildAvailabilityStatusesClient) List(resourceURI string, options *ChildAvailabilityStatusesListOptions) *ChildAvailabilityStatusesListPager { + return &ChildAvailabilityStatusesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, + advancer: func(ctx context.Context, resp ChildAvailabilityStatusesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilityStatusListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *ChildAvailabilityStatusesClient) listCreateRequest(ctx context.Context, resourceURI string, options *ChildAvailabilityStatusesListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ResourceHealth/childAvailabilityStatuses" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ChildAvailabilityStatusesClient) listHandleResponse(resp *http.Response) (ChildAvailabilityStatusesListResponse, error) { + result := ChildAvailabilityStatusesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatusListResult); err != nil { + return ChildAvailabilityStatusesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *ChildAvailabilityStatusesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childresources_client.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childresources_client.go new file mode 100644 index 000000000000..6d5836be0596 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_childresources_client.go @@ -0,0 +1,94 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "errors" + "fmt" + "net/http" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ChildResourcesClient contains the methods for the ChildResources group. +// Don't use this type directly, use NewChildResourcesClient() instead. +type ChildResourcesClient struct { + ep string + pl runtime.Pipeline +} + +// NewChildResourcesClient creates a new instance of ChildResourcesClient with the specified values. +func NewChildResourcesClient(con *arm.Connection) *ChildResourcesClient { + return &ChildResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists the all the children and its current health status for a parent resource. Use the nextLink property in the response to get the next page +// of children current health +// If the operation fails it returns the *ErrorResponse error type. +func (client *ChildResourcesClient) List(resourceURI string, options *ChildResourcesListOptions) *ChildResourcesListPager { + return &ChildResourcesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceURI, options) + }, + advancer: func(ctx context.Context, resp ChildResourcesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.AvailabilityStatusListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *ChildResourcesClient) listCreateRequest(ctx context.Context, resourceURI string, options *ChildResourcesListOptions) (*policy.Request, error) { + urlPath := "/{resourceUri}/providers/Microsoft.ResourceHealth/childResources" + if resourceURI == "" { + return nil, errors.New("parameter resourceURI cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceUri}", resourceURI) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *ChildResourcesClient) listHandleResponse(resp *http.Response) (ChildResourcesListResponse, error) { + result := ChildResourcesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AvailabilityStatusListResult); err != nil { + return ChildResourcesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *ChildResourcesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_constants.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_constants.go new file mode 100644 index 000000000000..bd690f2e5add --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_constants.go @@ -0,0 +1,122 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +const ( + module = "armresourcehealth" + version = "v0.1.1" +) + +// AvailabilityStateValues - Availability status of the resource. When it is null, this availabilityStatus object represents an availability impacting event +type AvailabilityStateValues string + +const ( + AvailabilityStateValuesAvailable AvailabilityStateValues = "Available" + AvailabilityStateValuesUnavailable AvailabilityStateValues = "Unavailable" + AvailabilityStateValuesUnknown AvailabilityStateValues = "Unknown" +) + +// PossibleAvailabilityStateValuesValues returns the possible values for the AvailabilityStateValues const type. +func PossibleAvailabilityStateValuesValues() []AvailabilityStateValues { + return []AvailabilityStateValues{ + AvailabilityStateValuesAvailable, + AvailabilityStateValuesUnavailable, + AvailabilityStateValuesUnknown, + } +} + +// ToPtr returns a *AvailabilityStateValues pointing to the current value. +func (c AvailabilityStateValues) ToPtr() *AvailabilityStateValues { + return &c +} + +type Enum0 string + +const ( + Enum0Default Enum0 = "default" +) + +// PossibleEnum0Values returns the possible values for the Enum0 const type. +func PossibleEnum0Values() []Enum0 { + return []Enum0{ + Enum0Default, + } +} + +// ToPtr returns a *Enum0 pointing to the current value. +func (c Enum0) ToPtr() *Enum0 { + return &c +} + +// ReasonChronicityTypes - Chronicity of the availability transition. +type ReasonChronicityTypes string + +const ( + ReasonChronicityTypesTransient ReasonChronicityTypes = "Transient" + ReasonChronicityTypesPersistent ReasonChronicityTypes = "Persistent" +) + +// PossibleReasonChronicityTypesValues returns the possible values for the ReasonChronicityTypes const type. +func PossibleReasonChronicityTypesValues() []ReasonChronicityTypes { + return []ReasonChronicityTypes{ + ReasonChronicityTypesTransient, + ReasonChronicityTypesPersistent, + } +} + +// ToPtr returns a *ReasonChronicityTypes pointing to the current value. +func (c ReasonChronicityTypes) ToPtr() *ReasonChronicityTypes { + return &c +} + +// SeverityValues - The severity level of this active event. +type SeverityValues string + +const ( + SeverityValuesError SeverityValues = "Error" + SeverityValuesInformation SeverityValues = "Information" + SeverityValuesWarning SeverityValues = "Warning" +) + +// PossibleSeverityValuesValues returns the possible values for the SeverityValues const type. +func PossibleSeverityValuesValues() []SeverityValues { + return []SeverityValues{ + SeverityValuesError, + SeverityValuesInformation, + SeverityValuesWarning, + } +} + +// ToPtr returns a *SeverityValues pointing to the current value. +func (c SeverityValues) ToPtr() *SeverityValues { + return &c +} + +// StageValues - The stage of this active event. +type StageValues string + +const ( + StageValuesActive StageValues = "Active" + StageValuesArchived StageValues = "Archived" + StageValuesResolve StageValues = "Resolve" +) + +// PossibleStageValuesValues returns the possible values for the StageValues const type. +func PossibleStageValuesValues() []StageValues { + return []StageValues{ + StageValuesActive, + StageValuesArchived, + StageValuesResolve, + } +} + +// ToPtr returns a *StageValues pointing to the current value. +func (c StageValues) ToPtr() *StageValues { + return &c +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_emergingissues_client.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_emergingissues_client.go new file mode 100644 index 000000000000..e9777422c68a --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_emergingissues_client.go @@ -0,0 +1,141 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// EmergingIssuesClient contains the methods for the EmergingIssues group. +// Don't use this type directly, use NewEmergingIssuesClient() instead. +type EmergingIssuesClient struct { + ep string + pl runtime.Pipeline +} + +// NewEmergingIssuesClient creates a new instance of EmergingIssuesClient with the specified values. +func NewEmergingIssuesClient(con *arm.Connection) *EmergingIssuesClient { + return &EmergingIssuesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// Get - Gets Azure services' emerging issues. +// If the operation fails it returns the *ErrorResponse error type. +func (client *EmergingIssuesClient) Get(ctx context.Context, issueName Enum0, options *EmergingIssuesGetOptions) (EmergingIssuesGetResponse, error) { + req, err := client.getCreateRequest(ctx, issueName, options) + if err != nil { + return EmergingIssuesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return EmergingIssuesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return EmergingIssuesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *EmergingIssuesClient) getCreateRequest(ctx context.Context, issueName Enum0, options *EmergingIssuesGetOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ResourceHealth/emergingIssues/{issueName}" + if issueName == "" { + return nil, errors.New("parameter issueName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{issueName}", url.PathEscape(string(issueName))) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *EmergingIssuesClient) getHandleResponse(resp *http.Response) (EmergingIssuesGetResponse, error) { + result := EmergingIssuesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.EmergingIssuesGetResult); err != nil { + return EmergingIssuesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *EmergingIssuesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists Azure services' emerging issues. +// If the operation fails it returns the *ErrorResponse error type. +func (client *EmergingIssuesClient) List(options *EmergingIssuesListOptions) *EmergingIssuesListPager { + return &EmergingIssuesListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp EmergingIssuesListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.EmergingIssueListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *EmergingIssuesClient) listCreateRequest(ctx context.Context, options *EmergingIssuesListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ResourceHealth/emergingIssues" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *EmergingIssuesClient) listHandleResponse(resp *http.Response) (EmergingIssuesListResponse, error) { + result := EmergingIssuesListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.EmergingIssueListResult); err != nil { + return EmergingIssuesListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *EmergingIssuesClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_models.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_models.go new file mode 100644 index 000000000000..20766eeadbe3 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_models.go @@ -0,0 +1,769 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AvailabilityStatus - availabilityStatus of a resource. +type AvailabilityStatus struct { + // Azure Resource Manager Identity for the availabilityStatuses resource. + ID *string `json:"id,omitempty"` + + // Azure Resource Manager geo location of the resource. + Location *string `json:"location,omitempty"` + + // current. + Name *string `json:"name,omitempty"` + + // Properties of availability state. + Properties *AvailabilityStatusProperties `json:"properties,omitempty"` + + // Microsoft.ResourceHealth/AvailabilityStatuses. + Type *string `json:"type,omitempty"` +} + +// AvailabilityStatusListResult - The List availabilityStatus operation response. +type AvailabilityStatusListResult struct { + // REQUIRED; The list of availabilityStatuses. + Value []*AvailabilityStatus `json:"value,omitempty"` + + // The URI to fetch the next page of availabilityStatuses. Call ListNext() with this URI to fetch the next page of availabilityStatuses. + NextLink *string `json:"nextLink,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AvailabilityStatusListResult. +func (a AvailabilityStatusListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", a.NextLink) + populate(objectMap, "value", a.Value) + return json.Marshal(objectMap) +} + +// AvailabilityStatusProperties - Properties of availability state. +type AvailabilityStatusProperties struct { + // Availability status of the resource. When it is null, this availabilityStatus object represents an availability impacting event + AvailabilityState *AvailabilityStateValues `json:"availabilityState,omitempty"` + + // Details of the availability status. + DetailedStatus *string `json:"detailedStatus,omitempty"` + + // In case of an availability impacting event, it describes the category of a PlatformInitiated health impacting event. Examples are Planned, Unplanned + // etc. + HealthEventCategory *string `json:"healthEventCategory,omitempty"` + + // In case of an availability impacting event, it describes where the health impacting event was originated. Examples are PlatformInitiated, UserInitiated + // etc. + HealthEventCause *string `json:"healthEventCause,omitempty"` + + // It is a unique Id that identifies the event + HealthEventID *string `json:"healthEventId,omitempty"` + + // In case of an availability impacting event, it describes when the health impacting event was originated. Examples are Lifecycle, Downtime, Fault Analysis + // etc. + HealthEventType *string `json:"healthEventType,omitempty"` + + // Timestamp for when last change in health status occurred. + OccuredTime *time.Time `json:"occuredTime,omitempty"` + + // Chronicity of the availability transition. + ReasonChronicity *ReasonChronicityTypes `json:"reasonChronicity,omitempty"` + + // When the resource's availabilityState is Unavailable, it describes where the health impacting event was originated. Examples are planned, unplanned, + // user initiated or an outage etc. + ReasonType *string `json:"reasonType,omitempty"` + + // An annotation describing a change in the availabilityState to Available from Unavailable with a reasonType of type Unplanned + RecentlyResolvedState *AvailabilityStatusPropertiesRecentlyResolvedState `json:"recentlyResolvedState,omitempty"` + + // Lists actions the user can take based on the current availabilityState of the resource. + RecommendedActions []*RecommendedAction `json:"recommendedActions,omitempty"` + + // Timestamp for when the health was last checked. + ReportedTime *time.Time `json:"reportedTime,omitempty"` + + // When the resource's availabilityState is Unavailable and the reasonType is not User Initiated, it provides the date and time for when the issue is expected + // to be resolved. + ResolutionETA *time.Time `json:"resolutionETA,omitempty"` + + // When the resource's availabilityState is Unavailable, it provides the Timestamp for when the health impacting event was received. + RootCauseAttributionTime *time.Time `json:"rootCauseAttributionTime,omitempty"` + + // Lists the service impacting events that may be affecting the health of the resource. + ServiceImpactingEvents []*ServiceImpactingEvent `json:"serviceImpactingEvents,omitempty"` + + // Summary description of the availability status. + Summary *string `json:"summary,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AvailabilityStatusProperties. +func (a AvailabilityStatusProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "availabilityState", a.AvailabilityState) + populate(objectMap, "detailedStatus", a.DetailedStatus) + populate(objectMap, "healthEventCategory", a.HealthEventCategory) + populate(objectMap, "healthEventCause", a.HealthEventCause) + populate(objectMap, "healthEventId", a.HealthEventID) + populate(objectMap, "healthEventType", a.HealthEventType) + populate(objectMap, "occuredTime", (*timeRFC3339)(a.OccuredTime)) + populate(objectMap, "reasonChronicity", a.ReasonChronicity) + populate(objectMap, "reasonType", a.ReasonType) + populate(objectMap, "recentlyResolvedState", a.RecentlyResolvedState) + populate(objectMap, "recommendedActions", a.RecommendedActions) + populate(objectMap, "reportedTime", (*timeRFC3339)(a.ReportedTime)) + populate(objectMap, "resolutionETA", (*timeRFC3339)(a.ResolutionETA)) + populate(objectMap, "rootCauseAttributionTime", (*timeRFC3339)(a.RootCauseAttributionTime)) + populate(objectMap, "serviceImpactingEvents", a.ServiceImpactingEvents) + populate(objectMap, "summary", a.Summary) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailabilityStatusProperties. +func (a *AvailabilityStatusProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "availabilityState": + err = unpopulate(val, &a.AvailabilityState) + delete(rawMsg, key) + case "detailedStatus": + err = unpopulate(val, &a.DetailedStatus) + delete(rawMsg, key) + case "healthEventCategory": + err = unpopulate(val, &a.HealthEventCategory) + delete(rawMsg, key) + case "healthEventCause": + err = unpopulate(val, &a.HealthEventCause) + delete(rawMsg, key) + case "healthEventId": + err = unpopulate(val, &a.HealthEventID) + delete(rawMsg, key) + case "healthEventType": + err = unpopulate(val, &a.HealthEventType) + delete(rawMsg, key) + case "occuredTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.OccuredTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "reasonChronicity": + err = unpopulate(val, &a.ReasonChronicity) + delete(rawMsg, key) + case "reasonType": + err = unpopulate(val, &a.ReasonType) + delete(rawMsg, key) + case "recentlyResolvedState": + err = unpopulate(val, &a.RecentlyResolvedState) + delete(rawMsg, key) + case "recommendedActions": + err = unpopulate(val, &a.RecommendedActions) + delete(rawMsg, key) + case "reportedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.ReportedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "resolutionETA": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.ResolutionETA = (*time.Time)(&aux) + delete(rawMsg, key) + case "rootCauseAttributionTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.RootCauseAttributionTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "serviceImpactingEvents": + err = unpopulate(val, &a.ServiceImpactingEvents) + delete(rawMsg, key) + case "summary": + err = unpopulate(val, &a.Summary) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AvailabilityStatusPropertiesRecentlyResolvedState - An annotation describing a change in the availabilityState to Available from Unavailable with a reasonType +// of type Unplanned +type AvailabilityStatusPropertiesRecentlyResolvedState struct { + // Timestamp when the availabilityState changes to Available. + ResolvedTime *time.Time `json:"resolvedTime,omitempty"` + + // Brief description of cause of the resource becoming unavailable. + UnavailabilitySummary *string `json:"unavailabilitySummary,omitempty"` + + // Timestamp for when the availabilityState changed to Unavailable + UnavailableOccurredTime *time.Time `json:"unavailableOccurredTime,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AvailabilityStatusPropertiesRecentlyResolvedState. +func (a AvailabilityStatusPropertiesRecentlyResolvedState) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "resolvedTime", (*timeRFC3339)(a.ResolvedTime)) + populate(objectMap, "unavailabilitySummary", a.UnavailabilitySummary) + populate(objectMap, "unavailableOccurredTime", (*timeRFC3339)(a.UnavailableOccurredTime)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvailabilityStatusPropertiesRecentlyResolvedState. +func (a *AvailabilityStatusPropertiesRecentlyResolvedState) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "resolvedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.ResolvedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "unavailabilitySummary": + err = unpopulate(val, &a.UnavailabilitySummary) + delete(rawMsg, key) + case "unavailableOccurredTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + a.UnavailableOccurredTime = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// AvailabilityStatusesGetByResourceOptions contains the optional parameters for the AvailabilityStatuses.GetByResource method. +type AvailabilityStatusesGetByResourceOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// AvailabilityStatusesListByResourceGroupOptions contains the optional parameters for the AvailabilityStatuses.ListByResourceGroup method. +type AvailabilityStatusesListByResourceGroupOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// AvailabilityStatusesListBySubscriptionIDOptions contains the optional parameters for the AvailabilityStatuses.ListBySubscriptionID method. +type AvailabilityStatusesListBySubscriptionIDOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// AvailabilityStatusesListOptions contains the optional parameters for the AvailabilityStatuses.List method. +type AvailabilityStatusesListOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// ChildAvailabilityStatusesGetByResourceOptions contains the optional parameters for the ChildAvailabilityStatuses.GetByResource method. +type ChildAvailabilityStatusesGetByResourceOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// ChildAvailabilityStatusesListOptions contains the optional parameters for the ChildAvailabilityStatuses.List method. +type ChildAvailabilityStatusesListOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// ChildResourcesListOptions contains the optional parameters for the ChildResources.List method. +type ChildResourcesListOptions struct { + // Setting $expand=recommendedactions in url query expands the recommendedactions in the response. + Expand *string + // The filter to apply on the operation. For more information please see https://docs.microsoft.com/en-us/rest/api/apimanagement/apis?redirectedfrom=MSDN + Filter *string +} + +// EmergingIssue - On-going emerging issue from azure status. +type EmergingIssue struct { + // Timestamp for when last time refreshed for ongoing emerging issue. + RefreshTimestamp *time.Time `json:"refreshTimestamp,omitempty"` + + // The list of emerging issues of active event type. + StatusActiveEvents []*StatusActiveEvent `json:"statusActiveEvents,omitempty"` + + // The list of emerging issues of banner type. + StatusBanners []*StatusBanner `json:"statusBanners,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EmergingIssue. +func (e EmergingIssue) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "refreshTimestamp", (*timeRFC3339)(e.RefreshTimestamp)) + populate(objectMap, "statusActiveEvents", e.StatusActiveEvents) + populate(objectMap, "statusBanners", e.StatusBanners) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EmergingIssue. +func (e *EmergingIssue) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "refreshTimestamp": + var aux timeRFC3339 + err = unpopulate(val, &aux) + e.RefreshTimestamp = (*time.Time)(&aux) + delete(rawMsg, key) + case "statusActiveEvents": + err = unpopulate(val, &e.StatusActiveEvents) + delete(rawMsg, key) + case "statusBanners": + err = unpopulate(val, &e.StatusBanners) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// EmergingIssueImpact - Object of the emerging issue impact on services and regions. +type EmergingIssueImpact struct { + // The impacted service id. + ID *string `json:"id,omitempty"` + + // The impacted service name. + Name *string `json:"name,omitempty"` + + // The list of impacted regions for corresponding emerging issues. + Regions []*ImpactedRegion `json:"regions,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EmergingIssueImpact. +func (e EmergingIssueImpact) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", e.ID) + populate(objectMap, "name", e.Name) + populate(objectMap, "regions", e.Regions) + return json.Marshal(objectMap) +} + +// EmergingIssueListResult - The list of emerging issues. +type EmergingIssueListResult struct { + // The link used to get the next page of emerging issues. + NextLink *string `json:"nextLink,omitempty"` + + // The list of emerging issues. + Value []*EmergingIssuesGetResult `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EmergingIssueListResult. +func (e EmergingIssueListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", e.NextLink) + populate(objectMap, "value", e.Value) + return json.Marshal(objectMap) +} + +// EmergingIssuesGetOptions contains the optional parameters for the EmergingIssues.Get method. +type EmergingIssuesGetOptions struct { + // placeholder for future optional parameters +} + +// EmergingIssuesGetResult - The Get EmergingIssues operation response. +type EmergingIssuesGetResult struct { + Resource + // The emerging issue entity properties. + Properties *EmergingIssue `json:"properties,omitempty"` +} + +// EmergingIssuesListOptions contains the optional parameters for the EmergingIssues.List method. +type EmergingIssuesListOptions struct { + // placeholder for future optional parameters +} + +// ErrorResponse - Error details. +// Implements the error and azcore.HTTPResponse interfaces. +type ErrorResponse struct { + raw string + // READ-ONLY; The error code. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; The error details. + Details *string `json:"details,omitempty" azure:"ro"` + + // READ-ONLY; The error message. + Message *string `json:"message,omitempty" azure:"ro"` +} + +// Error implements the error interface for type ErrorResponse. +// The contents of the error text are not contractual and subject to change. +func (e ErrorResponse) Error() string { + return e.raw +} + +// ImpactedRegion - Object of impacted region. +type ImpactedRegion struct { + // The impacted region id. + ID *string `json:"id,omitempty"` + + // The impacted region name. + Name *string `json:"name,omitempty"` +} + +// Operation available in the resourcehealth resource provider. +type Operation struct { + // Properties of the operation. + Display *OperationDisplay `json:"display,omitempty"` + + // Name of the operation. + Name *string `json:"name,omitempty"` +} + +// OperationDisplay - Properties of the operation. +type OperationDisplay struct { + // Description of the operation. + Description *string `json:"description,omitempty"` + + // Operation name. + Operation *string `json:"operation,omitempty"` + + // Provider name. + Provider *string `json:"provider,omitempty"` + + // Resource name. + Resource *string `json:"resource,omitempty"` +} + +// OperationListResult - Lists the operations response. +type OperationListResult struct { + // REQUIRED; List of operations available in the resourcehealth resource provider. + Value []*Operation `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// RecommendedAction - Lists actions the user can take based on the current availabilityState of the resource. +type RecommendedAction struct { + // Recommended action. + Action *string `json:"action,omitempty"` + + // Link to the action + ActionURL *string `json:"actionUrl,omitempty"` + + // Substring of action, it describes which text should host the action url. + ActionURLText *string `json:"actionUrlText,omitempty"` +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ServiceImpactingEvent - Lists the service impacting events that may be affecting the health of the resource. +type ServiceImpactingEvent struct { + // Correlation id for the event + CorrelationID *string `json:"correlationId,omitempty"` + + // Timestamp for when the event started. + EventStartTime *time.Time `json:"eventStartTime,omitempty"` + + // Timestamp for when event was submitted/detected. + EventStatusLastModifiedTime *time.Time `json:"eventStatusLastModifiedTime,omitempty"` + + // Properties of the service impacting event. + IncidentProperties *ServiceImpactingEventIncidentProperties `json:"incidentProperties,omitempty"` + + // Status of the service impacting event. + Status *ServiceImpactingEventStatus `json:"status,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceImpactingEvent. +func (s ServiceImpactingEvent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "correlationId", s.CorrelationID) + populate(objectMap, "eventStartTime", (*timeRFC3339)(s.EventStartTime)) + populate(objectMap, "eventStatusLastModifiedTime", (*timeRFC3339)(s.EventStatusLastModifiedTime)) + populate(objectMap, "incidentProperties", s.IncidentProperties) + populate(objectMap, "status", s.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceImpactingEvent. +func (s *ServiceImpactingEvent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "correlationId": + err = unpopulate(val, &s.CorrelationID) + delete(rawMsg, key) + case "eventStartTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.EventStartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "eventStatusLastModifiedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.EventStatusLastModifiedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "incidentProperties": + err = unpopulate(val, &s.IncidentProperties) + delete(rawMsg, key) + case "status": + err = unpopulate(val, &s.Status) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ServiceImpactingEventIncidentProperties - Properties of the service impacting event. +type ServiceImpactingEventIncidentProperties struct { + // Type of Event. + IncidentType *string `json:"incidentType,omitempty"` + + // Region impacted by the event. + Region *string `json:"region,omitempty"` + + // Service impacted by the event. + Service *string `json:"service,omitempty"` + + // Title of the incident. + Title *string `json:"title,omitempty"` +} + +// ServiceImpactingEventStatus - Status of the service impacting event. +type ServiceImpactingEventStatus struct { + // Current status of the event + Value *string `json:"value,omitempty"` +} + +// StatusActiveEvent - Active event type of emerging issue. +type StatusActiveEvent struct { + // The cloud type of this active event. + Cloud *string `json:"cloud,omitempty"` + + // The details of active event. + Description *string `json:"description,omitempty"` + + // The list of emerging issues impacts. + Impacts []*EmergingIssueImpact `json:"impacts,omitempty"` + + // The last time modified on this banner. + LastModifiedTime *time.Time `json:"lastModifiedTime,omitempty"` + + // The boolean value of this active event if published or not. + Published *bool `json:"published,omitempty"` + + // The severity level of this active event. + Severity *SeverityValues `json:"severity,omitempty"` + + // The stage of this active event. + Stage *StageValues `json:"stage,omitempty"` + + // The impact start time on this active event. + StartTime *time.Time `json:"startTime,omitempty"` + + // The active event title. + Title *string `json:"title,omitempty"` + + // The tracking id of this active event. + TrackingID *string `json:"trackingId,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StatusActiveEvent. +func (s StatusActiveEvent) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "cloud", s.Cloud) + populate(objectMap, "description", s.Description) + populate(objectMap, "impacts", s.Impacts) + populate(objectMap, "lastModifiedTime", (*timeRFC3339)(s.LastModifiedTime)) + populate(objectMap, "published", s.Published) + populate(objectMap, "severity", s.Severity) + populate(objectMap, "stage", s.Stage) + populate(objectMap, "startTime", (*timeRFC3339)(s.StartTime)) + populate(objectMap, "title", s.Title) + populate(objectMap, "trackingId", s.TrackingID) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StatusActiveEvent. +func (s *StatusActiveEvent) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "cloud": + err = unpopulate(val, &s.Cloud) + delete(rawMsg, key) + case "description": + err = unpopulate(val, &s.Description) + delete(rawMsg, key) + case "impacts": + err = unpopulate(val, &s.Impacts) + delete(rawMsg, key) + case "lastModifiedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "published": + err = unpopulate(val, &s.Published) + delete(rawMsg, key) + case "severity": + err = unpopulate(val, &s.Severity) + delete(rawMsg, key) + case "stage": + err = unpopulate(val, &s.Stage) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "title": + err = unpopulate(val, &s.Title) + delete(rawMsg, key) + case "trackingId": + err = unpopulate(val, &s.TrackingID) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StatusBanner - Banner type of emerging issue. +type StatusBanner struct { + // The cloud type of this banner. + Cloud *string `json:"cloud,omitempty"` + + // The last time modified on this banner. + LastModifiedTime *time.Time `json:"lastModifiedTime,omitempty"` + + // The details of banner. + Message *string `json:"message,omitempty"` + + // The banner title. + Title *string `json:"title,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StatusBanner. +func (s StatusBanner) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "cloud", s.Cloud) + populate(objectMap, "lastModifiedTime", (*timeRFC3339)(s.LastModifiedTime)) + populate(objectMap, "message", s.Message) + populate(objectMap, "title", s.Title) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StatusBanner. +func (s *StatusBanner) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "cloud": + err = unpopulate(val, &s.Cloud) + delete(rawMsg, key) + case "lastModifiedTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastModifiedTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "message": + err = unpopulate(val, &s.Message) + delete(rawMsg, key) + case "title": + err = unpopulate(val, &s.Title) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_operations_client.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_operations_client.go new file mode 100644 index 000000000000..dbee200bf524 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_operations_client.go @@ -0,0 +1,84 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists available operations for the resourcehealth resource provider +// If the operation fails it returns the *ErrorResponse error type. +func (client *OperationsClient) List(ctx context.Context, options *OperationsListOptions) (OperationsListResponse, error) { + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OperationsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OperationsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.ResourceHealth/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-07-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := ErrorResponse{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_pagers.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_pagers.go new file mode 100644 index 000000000000..6be3c50497ca --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_pagers.go @@ -0,0 +1,342 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AvailabilityStatusesListByResourceGroupPager provides operations for iterating over paged responses. +type AvailabilityStatusesListByResourceGroupPager struct { + client *AvailabilityStatusesClient + current AvailabilityStatusesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AvailabilityStatusesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AvailabilityStatusesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AvailabilityStatusesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AvailabilityStatusListResult.NextLink == nil || len(*p.current.AvailabilityStatusListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AvailabilityStatusesListByResourceGroupResponse page. +func (p *AvailabilityStatusesListByResourceGroupPager) PageResponse() AvailabilityStatusesListByResourceGroupResponse { + return p.current +} + +// AvailabilityStatusesListBySubscriptionIDPager provides operations for iterating over paged responses. +type AvailabilityStatusesListBySubscriptionIDPager struct { + client *AvailabilityStatusesClient + current AvailabilityStatusesListBySubscriptionIDResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AvailabilityStatusesListBySubscriptionIDResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AvailabilityStatusesListBySubscriptionIDPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AvailabilityStatusesListBySubscriptionIDPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AvailabilityStatusListResult.NextLink == nil || len(*p.current.AvailabilityStatusListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionIDHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionIDHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AvailabilityStatusesListBySubscriptionIDResponse page. +func (p *AvailabilityStatusesListBySubscriptionIDPager) PageResponse() AvailabilityStatusesListBySubscriptionIDResponse { + return p.current +} + +// AvailabilityStatusesListPager provides operations for iterating over paged responses. +type AvailabilityStatusesListPager struct { + client *AvailabilityStatusesClient + current AvailabilityStatusesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, AvailabilityStatusesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *AvailabilityStatusesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *AvailabilityStatusesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AvailabilityStatusListResult.NextLink == nil || len(*p.current.AvailabilityStatusListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current AvailabilityStatusesListResponse page. +func (p *AvailabilityStatusesListPager) PageResponse() AvailabilityStatusesListResponse { + return p.current +} + +// ChildAvailabilityStatusesListPager provides operations for iterating over paged responses. +type ChildAvailabilityStatusesListPager struct { + client *ChildAvailabilityStatusesClient + current ChildAvailabilityStatusesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ChildAvailabilityStatusesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ChildAvailabilityStatusesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ChildAvailabilityStatusesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AvailabilityStatusListResult.NextLink == nil || len(*p.current.AvailabilityStatusListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ChildAvailabilityStatusesListResponse page. +func (p *ChildAvailabilityStatusesListPager) PageResponse() ChildAvailabilityStatusesListResponse { + return p.current +} + +// ChildResourcesListPager provides operations for iterating over paged responses. +type ChildResourcesListPager struct { + client *ChildResourcesClient + current ChildResourcesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ChildResourcesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ChildResourcesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ChildResourcesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.AvailabilityStatusListResult.NextLink == nil || len(*p.current.AvailabilityStatusListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ChildResourcesListResponse page. +func (p *ChildResourcesListPager) PageResponse() ChildResourcesListResponse { + return p.current +} + +// EmergingIssuesListPager provides operations for iterating over paged responses. +type EmergingIssuesListPager struct { + client *EmergingIssuesClient + current EmergingIssuesListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, EmergingIssuesListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *EmergingIssuesListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *EmergingIssuesListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.EmergingIssueListResult.NextLink == nil || len(*p.current.EmergingIssueListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current EmergingIssuesListResponse page. +func (p *EmergingIssuesListPager) PageResponse() EmergingIssuesListResponse { + return p.current +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_response_types.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_response_types.go new file mode 100644 index 000000000000..f387c5361975 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_response_types.go @@ -0,0 +1,131 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import "net/http" + +// AvailabilityStatusesGetByResourceResponse contains the response from method AvailabilityStatuses.GetByResource. +type AvailabilityStatusesGetByResourceResponse struct { + AvailabilityStatusesGetByResourceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AvailabilityStatusesGetByResourceResult contains the result from method AvailabilityStatuses.GetByResource. +type AvailabilityStatusesGetByResourceResult struct { + AvailabilityStatus +} + +// AvailabilityStatusesListByResourceGroupResponse contains the response from method AvailabilityStatuses.ListByResourceGroup. +type AvailabilityStatusesListByResourceGroupResponse struct { + AvailabilityStatusesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AvailabilityStatusesListByResourceGroupResult contains the result from method AvailabilityStatuses.ListByResourceGroup. +type AvailabilityStatusesListByResourceGroupResult struct { + AvailabilityStatusListResult +} + +// AvailabilityStatusesListBySubscriptionIDResponse contains the response from method AvailabilityStatuses.ListBySubscriptionID. +type AvailabilityStatusesListBySubscriptionIDResponse struct { + AvailabilityStatusesListBySubscriptionIDResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AvailabilityStatusesListBySubscriptionIDResult contains the result from method AvailabilityStatuses.ListBySubscriptionID. +type AvailabilityStatusesListBySubscriptionIDResult struct { + AvailabilityStatusListResult +} + +// AvailabilityStatusesListResponse contains the response from method AvailabilityStatuses.List. +type AvailabilityStatusesListResponse struct { + AvailabilityStatusesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AvailabilityStatusesListResult contains the result from method AvailabilityStatuses.List. +type AvailabilityStatusesListResult struct { + AvailabilityStatusListResult +} + +// ChildAvailabilityStatusesGetByResourceResponse contains the response from method ChildAvailabilityStatuses.GetByResource. +type ChildAvailabilityStatusesGetByResourceResponse struct { + ChildAvailabilityStatusesGetByResourceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ChildAvailabilityStatusesGetByResourceResult contains the result from method ChildAvailabilityStatuses.GetByResource. +type ChildAvailabilityStatusesGetByResourceResult struct { + AvailabilityStatus +} + +// ChildAvailabilityStatusesListResponse contains the response from method ChildAvailabilityStatuses.List. +type ChildAvailabilityStatusesListResponse struct { + ChildAvailabilityStatusesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ChildAvailabilityStatusesListResult contains the result from method ChildAvailabilityStatuses.List. +type ChildAvailabilityStatusesListResult struct { + AvailabilityStatusListResult +} + +// ChildResourcesListResponse contains the response from method ChildResources.List. +type ChildResourcesListResponse struct { + ChildResourcesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ChildResourcesListResult contains the result from method ChildResources.List. +type ChildResourcesListResult struct { + AvailabilityStatusListResult +} + +// EmergingIssuesGetResponse contains the response from method EmergingIssues.Get. +type EmergingIssuesGetResponse struct { + EmergingIssuesGetResultEnvelope + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// EmergingIssuesGetResultEnvelope contains the result from method EmergingIssues.Get. +type EmergingIssuesGetResultEnvelope struct { + EmergingIssuesGetResult +} + +// EmergingIssuesListResponse contains the response from method EmergingIssues.List. +type EmergingIssuesListResponse struct { + EmergingIssuesListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// EmergingIssuesListResult contains the result from method EmergingIssues.List. +type EmergingIssuesListResult struct { + EmergingIssueListResult +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} diff --git a/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_time_rfc3339.go b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..935a5d0bcb49 --- /dev/null +++ b/sdk/resourcemanager/resourcehealth/armresourcehealth/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armresourcehealth + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/CHANGELOG.md b/sdk/resourcemanager/scheduler/armscheduler/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/scheduler/armscheduler/LICENSE.txt b/sdk/resourcemanager/scheduler/armscheduler/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/scheduler/armscheduler/README.md b/sdk/resourcemanager/scheduler/armscheduler/README.md new file mode 100644 index 000000000000..faffae7cd5a4 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/README.md @@ -0,0 +1,76 @@ +# Azure Scheduler Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/scheduler/armscheduler)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/scheduler/armscheduler) + +The `armscheduler` module provides operations for working with Azure Scheduler. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/scheduler/armscheduler) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Scheduler module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/scheduler/armscheduler +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Scheduler. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Scheduler + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Scheduler modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armscheduler.NewJobCollectionsClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Scheduler` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/scheduler/armscheduler/autorest.md b/sdk/resourcemanager/scheduler/armscheduler/autorest.md new file mode 100644 index 000000000000..56b016db82cb --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/scheduler/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/scheduler/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/scheduler/armscheduler/build.go b/sdk/resourcemanager/scheduler/armscheduler/build.go new file mode 100644 index 000000000000..9dc40495ea33 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/scheduler/armscheduler + +package armscheduler diff --git a/sdk/resourcemanager/scheduler/armscheduler/ci.yml b/sdk/resourcemanager/scheduler/armscheduler/ci.yml new file mode 100644 index 000000000000..3b5e9596fa77 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/scheduler/armscheduler/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/scheduler/armscheduler/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/scheduler/armscheduler' diff --git a/sdk/resourcemanager/scheduler/armscheduler/go.mod b/sdk/resourcemanager/scheduler/armscheduler/go.mod new file mode 100644 index 000000000000..12696170eaf6 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/scheduler/armscheduler + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/scheduler/armscheduler/go.sum b/sdk/resourcemanager/scheduler/armscheduler/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/scheduler/armscheduler/go_mod_tidy_hack.go b/sdk/resourcemanager/scheduler/armscheduler/go_mod_tidy_hack.go new file mode 100644 index 000000000000..4cfe3183febf --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armscheduler + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_constants.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_constants.go new file mode 100644 index 000000000000..1c23d84df41d --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_constants.go @@ -0,0 +1,338 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +const ( + module = "armscheduler" + version = "v0.1.1" +) + +type DayOfWeek string + +const ( + DayOfWeekSunday DayOfWeek = "Sunday" + DayOfWeekMonday DayOfWeek = "Monday" + DayOfWeekTuesday DayOfWeek = "Tuesday" + DayOfWeekWednesday DayOfWeek = "Wednesday" + DayOfWeekThursday DayOfWeek = "Thursday" + DayOfWeekFriday DayOfWeek = "Friday" + DayOfWeekSaturday DayOfWeek = "Saturday" +) + +// PossibleDayOfWeekValues returns the possible values for the DayOfWeek const type. +func PossibleDayOfWeekValues() []DayOfWeek { + return []DayOfWeek{ + DayOfWeekSunday, + DayOfWeekMonday, + DayOfWeekTuesday, + DayOfWeekWednesday, + DayOfWeekThursday, + DayOfWeekFriday, + DayOfWeekSaturday, + } +} + +// ToPtr returns a *DayOfWeek pointing to the current value. +func (c DayOfWeek) ToPtr() *DayOfWeek { + return &c +} + +// HTTPAuthenticationType - Gets or sets the HTTP authentication type. +type HTTPAuthenticationType string + +const ( + HTTPAuthenticationTypeNotSpecified HTTPAuthenticationType = "NotSpecified" + HTTPAuthenticationTypeClientCertificate HTTPAuthenticationType = "ClientCertificate" + HTTPAuthenticationTypeActiveDirectoryOAuth HTTPAuthenticationType = "ActiveDirectoryOAuth" + HTTPAuthenticationTypeBasic HTTPAuthenticationType = "Basic" +) + +// PossibleHTTPAuthenticationTypeValues returns the possible values for the HTTPAuthenticationType const type. +func PossibleHTTPAuthenticationTypeValues() []HTTPAuthenticationType { + return []HTTPAuthenticationType{ + HTTPAuthenticationTypeNotSpecified, + HTTPAuthenticationTypeClientCertificate, + HTTPAuthenticationTypeActiveDirectoryOAuth, + HTTPAuthenticationTypeBasic, + } +} + +// ToPtr returns a *HTTPAuthenticationType pointing to the current value. +func (c HTTPAuthenticationType) ToPtr() *HTTPAuthenticationType { + return &c +} + +// JobActionType - Gets or sets the job action type. +type JobActionType string + +const ( + JobActionTypeHTTP JobActionType = "Http" + JobActionTypeHTTPS JobActionType = "Https" + JobActionTypeStorageQueue JobActionType = "StorageQueue" + JobActionTypeServiceBusQueue JobActionType = "ServiceBusQueue" + JobActionTypeServiceBusTopic JobActionType = "ServiceBusTopic" +) + +// PossibleJobActionTypeValues returns the possible values for the JobActionType const type. +func PossibleJobActionTypeValues() []JobActionType { + return []JobActionType{ + JobActionTypeHTTP, + JobActionTypeHTTPS, + JobActionTypeStorageQueue, + JobActionTypeServiceBusQueue, + JobActionTypeServiceBusTopic, + } +} + +// ToPtr returns a *JobActionType pointing to the current value. +func (c JobActionType) ToPtr() *JobActionType { + return &c +} + +// JobCollectionState - Gets or sets the state. +type JobCollectionState string + +const ( + JobCollectionStateEnabled JobCollectionState = "Enabled" + JobCollectionStateDisabled JobCollectionState = "Disabled" + JobCollectionStateSuspended JobCollectionState = "Suspended" + JobCollectionStateDeleted JobCollectionState = "Deleted" +) + +// PossibleJobCollectionStateValues returns the possible values for the JobCollectionState const type. +func PossibleJobCollectionStateValues() []JobCollectionState { + return []JobCollectionState{ + JobCollectionStateEnabled, + JobCollectionStateDisabled, + JobCollectionStateSuspended, + JobCollectionStateDeleted, + } +} + +// ToPtr returns a *JobCollectionState pointing to the current value. +func (c JobCollectionState) ToPtr() *JobCollectionState { + return &c +} + +// JobExecutionStatus - Gets the job execution status. +type JobExecutionStatus string + +const ( + JobExecutionStatusCompleted JobExecutionStatus = "Completed" + JobExecutionStatusFailed JobExecutionStatus = "Failed" + JobExecutionStatusPostponed JobExecutionStatus = "Postponed" +) + +// PossibleJobExecutionStatusValues returns the possible values for the JobExecutionStatus const type. +func PossibleJobExecutionStatusValues() []JobExecutionStatus { + return []JobExecutionStatus{ + JobExecutionStatusCompleted, + JobExecutionStatusFailed, + JobExecutionStatusPostponed, + } +} + +// ToPtr returns a *JobExecutionStatus pointing to the current value. +func (c JobExecutionStatus) ToPtr() *JobExecutionStatus { + return &c +} + +// JobHistoryActionName - Gets the job history action name. +type JobHistoryActionName string + +const ( + JobHistoryActionNameMainAction JobHistoryActionName = "MainAction" + JobHistoryActionNameErrorAction JobHistoryActionName = "ErrorAction" +) + +// PossibleJobHistoryActionNameValues returns the possible values for the JobHistoryActionName const type. +func PossibleJobHistoryActionNameValues() []JobHistoryActionName { + return []JobHistoryActionName{ + JobHistoryActionNameMainAction, + JobHistoryActionNameErrorAction, + } +} + +// ToPtr returns a *JobHistoryActionName pointing to the current value. +func (c JobHistoryActionName) ToPtr() *JobHistoryActionName { + return &c +} + +// JobScheduleDay - Gets or sets the day. Must be one of monday, tuesday, wednesday, thursday, friday, saturday, sunday. +type JobScheduleDay string + +const ( + JobScheduleDayMonday JobScheduleDay = "Monday" + JobScheduleDayTuesday JobScheduleDay = "Tuesday" + JobScheduleDayWednesday JobScheduleDay = "Wednesday" + JobScheduleDayThursday JobScheduleDay = "Thursday" + JobScheduleDayFriday JobScheduleDay = "Friday" + JobScheduleDaySaturday JobScheduleDay = "Saturday" + JobScheduleDaySunday JobScheduleDay = "Sunday" +) + +// PossibleJobScheduleDayValues returns the possible values for the JobScheduleDay const type. +func PossibleJobScheduleDayValues() []JobScheduleDay { + return []JobScheduleDay{ + JobScheduleDayMonday, + JobScheduleDayTuesday, + JobScheduleDayWednesday, + JobScheduleDayThursday, + JobScheduleDayFriday, + JobScheduleDaySaturday, + JobScheduleDaySunday, + } +} + +// ToPtr returns a *JobScheduleDay pointing to the current value. +func (c JobScheduleDay) ToPtr() *JobScheduleDay { + return &c +} + +// JobState - Gets or set the job state. +type JobState string + +const ( + JobStateEnabled JobState = "Enabled" + JobStateDisabled JobState = "Disabled" + JobStateFaulted JobState = "Faulted" + JobStateCompleted JobState = "Completed" +) + +// PossibleJobStateValues returns the possible values for the JobState const type. +func PossibleJobStateValues() []JobState { + return []JobState{ + JobStateEnabled, + JobStateDisabled, + JobStateFaulted, + JobStateCompleted, + } +} + +// ToPtr returns a *JobState pointing to the current value. +func (c JobState) ToPtr() *JobState { + return &c +} + +// RecurrenceFrequency - Gets or sets the frequency of recurrence (second, minute, hour, day, week, month). +type RecurrenceFrequency string + +const ( + RecurrenceFrequencyMinute RecurrenceFrequency = "Minute" + RecurrenceFrequencyHour RecurrenceFrequency = "Hour" + RecurrenceFrequencyDay RecurrenceFrequency = "Day" + RecurrenceFrequencyWeek RecurrenceFrequency = "Week" + RecurrenceFrequencyMonth RecurrenceFrequency = "Month" +) + +// PossibleRecurrenceFrequencyValues returns the possible values for the RecurrenceFrequency const type. +func PossibleRecurrenceFrequencyValues() []RecurrenceFrequency { + return []RecurrenceFrequency{ + RecurrenceFrequencyMinute, + RecurrenceFrequencyHour, + RecurrenceFrequencyDay, + RecurrenceFrequencyWeek, + RecurrenceFrequencyMonth, + } +} + +// ToPtr returns a *RecurrenceFrequency pointing to the current value. +func (c RecurrenceFrequency) ToPtr() *RecurrenceFrequency { + return &c +} + +// RetryType - Gets or sets the retry strategy to be used. +type RetryType string + +const ( + RetryTypeNone RetryType = "None" + RetryTypeFixed RetryType = "Fixed" +) + +// PossibleRetryTypeValues returns the possible values for the RetryType const type. +func PossibleRetryTypeValues() []RetryType { + return []RetryType{ + RetryTypeNone, + RetryTypeFixed, + } +} + +// ToPtr returns a *RetryType pointing to the current value. +func (c RetryType) ToPtr() *RetryType { + return &c +} + +// SKUDefinition - Gets or set the SKU. +type SKUDefinition string + +const ( + SKUDefinitionStandard SKUDefinition = "Standard" + SKUDefinitionFree SKUDefinition = "Free" + SKUDefinitionP10Premium SKUDefinition = "P10Premium" + SKUDefinitionP20Premium SKUDefinition = "P20Premium" +) + +// PossibleSKUDefinitionValues returns the possible values for the SKUDefinition const type. +func PossibleSKUDefinitionValues() []SKUDefinition { + return []SKUDefinition{ + SKUDefinitionStandard, + SKUDefinitionFree, + SKUDefinitionP10Premium, + SKUDefinitionP20Premium, + } +} + +// ToPtr returns a *SKUDefinition pointing to the current value. +func (c SKUDefinition) ToPtr() *SKUDefinition { + return &c +} + +// ServiceBusAuthenticationType - Gets or sets the authentication type. +type ServiceBusAuthenticationType string + +const ( + ServiceBusAuthenticationTypeNotSpecified ServiceBusAuthenticationType = "NotSpecified" + ServiceBusAuthenticationTypeSharedAccessKey ServiceBusAuthenticationType = "SharedAccessKey" +) + +// PossibleServiceBusAuthenticationTypeValues returns the possible values for the ServiceBusAuthenticationType const type. +func PossibleServiceBusAuthenticationTypeValues() []ServiceBusAuthenticationType { + return []ServiceBusAuthenticationType{ + ServiceBusAuthenticationTypeNotSpecified, + ServiceBusAuthenticationTypeSharedAccessKey, + } +} + +// ToPtr returns a *ServiceBusAuthenticationType pointing to the current value. +func (c ServiceBusAuthenticationType) ToPtr() *ServiceBusAuthenticationType { + return &c +} + +// ServiceBusTransportType - Gets or sets the transport type. +type ServiceBusTransportType string + +const ( + ServiceBusTransportTypeNotSpecified ServiceBusTransportType = "NotSpecified" + ServiceBusTransportTypeNetMessaging ServiceBusTransportType = "NetMessaging" + ServiceBusTransportTypeAMQP ServiceBusTransportType = "AMQP" +) + +// PossibleServiceBusTransportTypeValues returns the possible values for the ServiceBusTransportType const type. +func PossibleServiceBusTransportTypeValues() []ServiceBusTransportType { + return []ServiceBusTransportType{ + ServiceBusTransportTypeNotSpecified, + ServiceBusTransportTypeNetMessaging, + ServiceBusTransportTypeAMQP, + } +} + +// ToPtr returns a *ServiceBusTransportType pointing to the current value. +func (c ServiceBusTransportType) ToPtr() *ServiceBusTransportType { + return &c +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobcollections_client.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobcollections_client.go new file mode 100644 index 000000000000..298ea82dd6a7 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobcollections_client.go @@ -0,0 +1,559 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "context" + "errors" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// JobCollectionsClient contains the methods for the JobCollections group. +// Don't use this type directly, use NewJobCollectionsClient() instead. +type JobCollectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewJobCollectionsClient creates a new instance of JobCollectionsClient with the specified values. +func NewJobCollectionsClient(con *arm.Connection, subscriptionID string) *JobCollectionsClient { + return &JobCollectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Provisions a new job collection or updates an existing job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition, options *JobCollectionsCreateOrUpdateOptions) (JobCollectionsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, jobCollectionName, jobCollection, options) + if err != nil { + return JobCollectionsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobCollectionsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return JobCollectionsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *JobCollectionsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition, options *JobCollectionsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, runtime.MarshalAsJSON(req, jobCollection) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *JobCollectionsClient) createOrUpdateHandleResponse(resp *http.Response) (JobCollectionsCreateOrUpdateResponse, error) { + result := JobCollectionsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollectionDefinition); err != nil { + return JobCollectionsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *JobCollectionsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// BeginDelete - Deletes a job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) BeginDelete(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDeleteOptions) (JobCollectionsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return JobCollectionsDeletePollerResponse{}, err + } + result := JobCollectionsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("JobCollectionsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return JobCollectionsDeletePollerResponse{}, err + } + result.Poller = &JobCollectionsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) deleteOperation(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *JobCollectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *JobCollectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// BeginDisable - Disables all of the jobs in the job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) BeginDisable(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDisableOptions) (JobCollectionsDisablePollerResponse, error) { + resp, err := client.disable(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return JobCollectionsDisablePollerResponse{}, err + } + result := JobCollectionsDisablePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("JobCollectionsClient.Disable", "", resp, client.pl, client.disableHandleError) + if err != nil { + return JobCollectionsDisablePollerResponse{}, err + } + result.Poller = &JobCollectionsDisablePoller{ + pt: pt, + } + return result, nil +} + +// Disable - Disables all of the jobs in the job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) disable(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDisableOptions) (*http.Response, error) { + req, err := client.disableCreateRequest(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.disableHandleError(resp) + } + return resp, nil +} + +// disableCreateRequest creates the Disable request. +func (client *JobCollectionsClient) disableCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginDisableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/disable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// disableHandleError handles the Disable error response. +func (client *JobCollectionsClient) disableHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// BeginEnable - Enables all of the jobs in the job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) BeginEnable(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginEnableOptions) (JobCollectionsEnablePollerResponse, error) { + resp, err := client.enable(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return JobCollectionsEnablePollerResponse{}, err + } + result := JobCollectionsEnablePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("JobCollectionsClient.Enable", "", resp, client.pl, client.enableHandleError) + if err != nil { + return JobCollectionsEnablePollerResponse{}, err + } + result.Poller = &JobCollectionsEnablePoller{ + pt: pt, + } + return result, nil +} + +// Enable - Enables all of the jobs in the job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) enable(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginEnableOptions) (*http.Response, error) { + req, err := client.enableCreateRequest(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.enableHandleError(resp) + } + return resp, nil +} + +// enableCreateRequest creates the Enable request. +func (client *JobCollectionsClient) enableCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsBeginEnableOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/enable" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// enableHandleError handles the Enable error response. +func (client *JobCollectionsClient) enableHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Get - Gets a job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) Get(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsGetOptions) (JobCollectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobCollectionName, options) + if err != nil { + return JobCollectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobCollectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobCollectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *JobCollectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobCollectionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *JobCollectionsClient) getHandleResponse(resp *http.Response) (JobCollectionsGetResponse, error) { + result := JobCollectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollectionDefinition); err != nil { + return JobCollectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *JobCollectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListByResourceGroup - Gets all job collections under specified resource group. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) ListByResourceGroup(resourceGroupName string, options *JobCollectionsListByResourceGroupOptions) *JobCollectionsListByResourceGroupPager { + return &JobCollectionsListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp JobCollectionsListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.JobCollectionListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *JobCollectionsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *JobCollectionsListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *JobCollectionsClient) listByResourceGroupHandleResponse(resp *http.Response) (JobCollectionsListByResourceGroupResponse, error) { + result := JobCollectionsListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollectionListResult); err != nil { + return JobCollectionsListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *JobCollectionsClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListBySubscription - Gets all job collections under specified subscription. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) ListBySubscription(options *JobCollectionsListBySubscriptionOptions) *JobCollectionsListBySubscriptionPager { + return &JobCollectionsListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp JobCollectionsListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.JobCollectionListResult.NextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *JobCollectionsClient) listBySubscriptionCreateRequest(ctx context.Context, options *JobCollectionsListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Scheduler/jobCollections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *JobCollectionsClient) listBySubscriptionHandleResponse(resp *http.Response) (JobCollectionsListBySubscriptionResponse, error) { + result := JobCollectionsListBySubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollectionListResult); err != nil { + return JobCollectionsListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *JobCollectionsClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Patch - Patches an existing job collection. +// If the operation fails it returns a generic error. +func (client *JobCollectionsClient) Patch(ctx context.Context, resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition, options *JobCollectionsPatchOptions) (JobCollectionsPatchResponse, error) { + req, err := client.patchCreateRequest(ctx, resourceGroupName, jobCollectionName, jobCollection, options) + if err != nil { + return JobCollectionsPatchResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobCollectionsPatchResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobCollectionsPatchResponse{}, client.patchHandleError(resp) + } + return client.patchHandleResponse(resp) +} + +// patchCreateRequest creates the Patch request. +func (client *JobCollectionsClient) patchCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobCollection JobCollectionDefinition, options *JobCollectionsPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, runtime.MarshalAsJSON(req, jobCollection) +} + +// patchHandleResponse handles the Patch response. +func (client *JobCollectionsClient) patchHandleResponse(resp *http.Response) (JobCollectionsPatchResponse, error) { + result := JobCollectionsPatchResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobCollectionDefinition); err != nil { + return JobCollectionsPatchResponse{}, err + } + return result, nil +} + +// patchHandleError handles the Patch error response. +func (client *JobCollectionsClient) patchHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobs_client.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobs_client.go new file mode 100644 index 000000000000..b891fa1593b1 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_jobs_client.go @@ -0,0 +1,499 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "context" + "errors" + "net/http" + "net/url" + "strconv" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// JobsClient contains the methods for the Jobs group. +// Don't use this type directly, use NewJobsClient() instead. +type JobsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewJobsClient creates a new instance of JobsClient with the specified values. +func NewJobsClient(con *arm.Connection, subscriptionID string) *JobsClient { + return &JobsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Provisions a new job or updates an existing job. +// If the operation fails it returns a generic error. +func (client *JobsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition, options *JobsCreateOrUpdateOptions) (JobsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, job, options) + if err != nil { + return JobsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return JobsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *JobsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition, options *JobsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, runtime.MarshalAsJSON(req, job) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *JobsClient) createOrUpdateHandleResponse(resp *http.Response) (JobsCreateOrUpdateResponse, error) { + result := JobsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobDefinition); err != nil { + return JobsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *JobsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Delete - Deletes a job. +// If the operation fails it returns a generic error. +func (client *JobsClient) Delete(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsDeleteOptions) (JobsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, options) + if err != nil { + return JobsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsDeleteResponse{}, client.deleteHandleError(resp) + } + return JobsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *JobsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *JobsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Get - Gets a job. +// If the operation fails it returns a generic error. +func (client *JobsClient) Get(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsGetOptions) (JobsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, options) + if err != nil { + return JobsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *JobsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *JobsClient) getHandleResponse(resp *http.Response) (JobsGetResponse, error) { + result := JobsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobDefinition); err != nil { + return JobsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *JobsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// List - Lists all jobs under the specified job collection. +// If the operation fails it returns a generic error. +func (client *JobsClient) List(resourceGroupName string, jobCollectionName string, options *JobsListOptions) *JobsListPager { + return &JobsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, resourceGroupName, jobCollectionName, options) + }, + advancer: func(ctx context.Context, resp JobsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.JobListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *JobsClient) listCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, options *JobsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *JobsClient) listHandleResponse(resp *http.Response) (JobsListResponse, error) { + result := JobsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobListResult); err != nil { + return JobsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *JobsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// ListJobHistory - Lists job history. +// If the operation fails it returns a generic error. +func (client *JobsClient) ListJobHistory(resourceGroupName string, jobCollectionName string, jobName string, options *JobsListJobHistoryOptions) *JobsListJobHistoryPager { + return &JobsListJobHistoryPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listJobHistoryCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, options) + }, + advancer: func(ctx context.Context, resp JobsListJobHistoryResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.JobHistoryListResult.NextLink) + }, + } +} + +// listJobHistoryCreateRequest creates the ListJobHistory request. +func (client *JobsClient) listJobHistoryCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsListJobHistoryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}/history" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + if options != nil && options.Top != nil { + reqQP.Set("$top", strconv.FormatInt(int64(*options.Top), 10)) + } + if options != nil && options.Skip != nil { + reqQP.Set("$skip", strconv.FormatInt(int64(*options.Skip), 10)) + } + if options != nil && options.Filter != nil { + reqQP.Set("$filter", *options.Filter) + } + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, nil +} + +// listJobHistoryHandleResponse handles the ListJobHistory response. +func (client *JobsClient) listJobHistoryHandleResponse(resp *http.Response) (JobsListJobHistoryResponse, error) { + result := JobsListJobHistoryResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobHistoryListResult); err != nil { + return JobsListJobHistoryResponse{}, err + } + return result, nil +} + +// listJobHistoryHandleError handles the ListJobHistory error response. +func (client *JobsClient) listJobHistoryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Patch - Patches an existing job. +// If the operation fails it returns a generic error. +func (client *JobsClient) Patch(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition, options *JobsPatchOptions) (JobsPatchResponse, error) { + req, err := client.patchCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, job, options) + if err != nil { + return JobsPatchResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsPatchResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsPatchResponse{}, client.patchHandleError(resp) + } + return client.patchHandleResponse(resp) +} + +// patchCreateRequest creates the Patch request. +func (client *JobsClient) patchCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, job JobDefinition, options *JobsPatchOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json, text/json") + return req, runtime.MarshalAsJSON(req, job) +} + +// patchHandleResponse handles the Patch response. +func (client *JobsClient) patchHandleResponse(resp *http.Response) (JobsPatchResponse, error) { + result := JobsPatchResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.JobDefinition); err != nil { + return JobsPatchResponse{}, err + } + return result, nil +} + +// patchHandleError handles the Patch error response. +func (client *JobsClient) patchHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} + +// Run - Runs a job. +// If the operation fails it returns a generic error. +func (client *JobsClient) Run(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsRunOptions) (JobsRunResponse, error) { + req, err := client.runCreateRequest(ctx, resourceGroupName, jobCollectionName, jobName, options) + if err != nil { + return JobsRunResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return JobsRunResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return JobsRunResponse{}, client.runHandleError(resp) + } + return JobsRunResponse{RawResponse: resp}, nil +} + +// runCreateRequest creates the Run request. +func (client *JobsClient) runCreateRequest(ctx context.Context, resourceGroupName string, jobCollectionName string, jobName string, options *JobsRunOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Scheduler/jobCollections/{jobCollectionName}/jobs/{jobName}/run" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobCollectionName == "" { + return nil, errors.New("parameter jobCollectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobCollectionName}", url.PathEscape(jobCollectionName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2016-03-01") + req.Raw().URL.RawQuery = reqQP.Encode() + return req, nil +} + +// runHandleError handles the Run error response. +func (client *JobsClient) runHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + if len(body) == 0 { + return runtime.NewResponseError(errors.New(resp.Status), resp) + } + return runtime.NewResponseError(errors.New(string(body)), resp) +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_models.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_models.go new file mode 100644 index 000000000000..611b482b2427 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_models.go @@ -0,0 +1,1127 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +type BasicAuthentication struct { + HTTPAuthentication + // Gets or sets the password, return value will always be empty. + Password *string `json:"password,omitempty"` + + // Gets or sets the username. + Username *string `json:"username,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BasicAuthentication. +func (b BasicAuthentication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.HTTPAuthentication.marshalInternal(objectMap, HTTPAuthenticationTypeBasic) + populate(objectMap, "password", b.Password) + populate(objectMap, "username", b.Username) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BasicAuthentication. +func (b *BasicAuthentication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "password": + err = unpopulate(val, &b.Password) + delete(rawMsg, key) + case "username": + err = unpopulate(val, &b.Username) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := b.HTTPAuthentication.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type ClientCertAuthentication struct { + HTTPAuthentication + // Gets or sets the certificate expiration date. + CertificateExpirationDate *time.Time `json:"certificateExpirationDate,omitempty"` + + // Gets or sets the certificate subject name. + CertificateSubjectName *string `json:"certificateSubjectName,omitempty"` + + // Gets or sets the certificate thumbprint. + CertificateThumbprint *string `json:"certificateThumbprint,omitempty"` + + // Gets or sets the certificate password, return value will always be empty. + Password *string `json:"password,omitempty"` + + // Gets or sets the pfx certificate. Accepts certification in base64 encoding, return value will always be empty. + Pfx *string `json:"pfx,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ClientCertAuthentication. +func (c ClientCertAuthentication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.HTTPAuthentication.marshalInternal(objectMap, HTTPAuthenticationTypeClientCertificate) + populate(objectMap, "certificateExpirationDate", (*timeRFC3339)(c.CertificateExpirationDate)) + populate(objectMap, "certificateSubjectName", c.CertificateSubjectName) + populate(objectMap, "certificateThumbprint", c.CertificateThumbprint) + populate(objectMap, "password", c.Password) + populate(objectMap, "pfx", c.Pfx) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClientCertAuthentication. +func (c *ClientCertAuthentication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "certificateExpirationDate": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.CertificateExpirationDate = (*time.Time)(&aux) + delete(rawMsg, key) + case "certificateSubjectName": + err = unpopulate(val, &c.CertificateSubjectName) + delete(rawMsg, key) + case "certificateThumbprint": + err = unpopulate(val, &c.CertificateThumbprint) + delete(rawMsg, key) + case "password": + err = unpopulate(val, &c.Password) + delete(rawMsg, key) + case "pfx": + err = unpopulate(val, &c.Pfx) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.HTTPAuthentication.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// HTTPAuthenticationClassification provides polymorphic access to related types. +// Call the interface's GetHTTPAuthentication() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *BasicAuthentication, *ClientCertAuthentication, *HTTPAuthentication, *OAuthAuthentication +type HTTPAuthenticationClassification interface { + // GetHTTPAuthentication returns the HTTPAuthentication content of the underlying type. + GetHTTPAuthentication() *HTTPAuthentication +} + +type HTTPAuthentication struct { + // REQUIRED; Gets or sets the HTTP authentication type. + Type *HTTPAuthenticationType `json:"type,omitempty"` +} + +// GetHTTPAuthentication implements the HTTPAuthenticationClassification interface for type HTTPAuthentication. +func (h *HTTPAuthentication) GetHTTPAuthentication() *HTTPAuthentication { return h } + +// UnmarshalJSON implements the json.Unmarshaller interface for type HTTPAuthentication. +func (h *HTTPAuthentication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return h.unmarshalInternal(rawMsg) +} + +func (h HTTPAuthentication) marshalInternal(objectMap map[string]interface{}, discValue HTTPAuthenticationType) { + h.Type = &discValue + objectMap["type"] = h.Type +} + +func (h *HTTPAuthentication) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &h.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type HTTPRequest struct { + // Gets or sets the authentication method of the request. + Authentication HTTPAuthenticationClassification `json:"authentication,omitempty"` + + // Gets or sets the request body. + Body *string `json:"body,omitempty"` + + // Gets or sets the headers. + Headers map[string]*string `json:"headers,omitempty"` + + // Gets or sets the method of the request. + Method *string `json:"method,omitempty"` + + // Gets or sets the URI of the request. + URI *string `json:"uri,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type HTTPRequest. +func (h HTTPRequest) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "authentication", h.Authentication) + populate(objectMap, "body", h.Body) + populate(objectMap, "headers", h.Headers) + populate(objectMap, "method", h.Method) + populate(objectMap, "uri", h.URI) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type HTTPRequest. +func (h *HTTPRequest) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "authentication": + h.Authentication, err = unmarshalHTTPAuthenticationClassification(val) + delete(rawMsg, key) + case "body": + err = unpopulate(val, &h.Body) + delete(rawMsg, key) + case "headers": + err = unpopulate(val, &h.Headers) + delete(rawMsg, key) + case "method": + err = unpopulate(val, &h.Method) + delete(rawMsg, key) + case "uri": + err = unpopulate(val, &h.URI) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type JobAction struct { + // Gets or sets the error action. + ErrorAction *JobErrorAction `json:"errorAction,omitempty"` + + // Gets or sets the storage queue message. + QueueMessage *StorageQueueMessage `json:"queueMessage,omitempty"` + + // Gets or sets the http requests. + Request *HTTPRequest `json:"request,omitempty"` + + // Gets or sets the retry policy. + RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` + + // Gets or sets the service bus queue message. + ServiceBusQueueMessage *ServiceBusQueueMessage `json:"serviceBusQueueMessage,omitempty"` + + // Gets or sets the service bus topic message. + ServiceBusTopicMessage *ServiceBusTopicMessage `json:"serviceBusTopicMessage,omitempty"` + + // Gets or sets the job action type. + Type *JobActionType `json:"type,omitempty"` +} + +type JobCollectionDefinition struct { + // Gets or sets the storage account location. + Location *string `json:"location,omitempty"` + + // Gets or sets the job collection resource name. + Name *string `json:"name,omitempty"` + + // Gets or sets the job collection properties. + Properties *JobCollectionProperties `json:"properties,omitempty"` + + // Gets or sets the tags. + Tags map[string]*string `json:"tags,omitempty"` + + // READ-ONLY; Gets the job collection resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job collection resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobCollectionDefinition. +func (j JobCollectionDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", j.ID) + populate(objectMap, "location", j.Location) + populate(objectMap, "name", j.Name) + populate(objectMap, "properties", j.Properties) + populate(objectMap, "tags", j.Tags) + populate(objectMap, "type", j.Type) + return json.Marshal(objectMap) +} + +type JobCollectionListResult struct { + // Gets or sets the URL to get the next set of job collections. + NextLink *string `json:"nextLink,omitempty"` + + // READ-ONLY; Gets the job collections. + Value []*JobCollectionDefinition `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobCollectionListResult. +func (j JobCollectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +type JobCollectionProperties struct { + // Gets or sets the job collection quota. + Quota *JobCollectionQuota `json:"quota,omitempty"` + + // Gets or sets the SKU. + SKU *SKU `json:"sku,omitempty"` + + // Gets or sets the state. + State *JobCollectionState `json:"state,omitempty"` +} + +type JobCollectionQuota struct { + // Gets or set the maximum job count. + MaxJobCount *int32 `json:"maxJobCount,omitempty"` + + // Gets or sets the maximum job occurrence. + MaxJobOccurrence *int32 `json:"maxJobOccurrence,omitempty"` + + // Gets or set the maximum recurrence. + MaxRecurrence *JobMaxRecurrence `json:"maxRecurrence,omitempty"` +} + +// JobCollectionsBeginDeleteOptions contains the optional parameters for the JobCollections.BeginDelete method. +type JobCollectionsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsBeginDisableOptions contains the optional parameters for the JobCollections.BeginDisable method. +type JobCollectionsBeginDisableOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsBeginEnableOptions contains the optional parameters for the JobCollections.BeginEnable method. +type JobCollectionsBeginEnableOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsCreateOrUpdateOptions contains the optional parameters for the JobCollections.CreateOrUpdate method. +type JobCollectionsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsGetOptions contains the optional parameters for the JobCollections.Get method. +type JobCollectionsGetOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsListByResourceGroupOptions contains the optional parameters for the JobCollections.ListByResourceGroup method. +type JobCollectionsListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsListBySubscriptionOptions contains the optional parameters for the JobCollections.ListBySubscription method. +type JobCollectionsListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// JobCollectionsPatchOptions contains the optional parameters for the JobCollections.Patch method. +type JobCollectionsPatchOptions struct { + // placeholder for future optional parameters +} + +type JobDefinition struct { + // Gets or sets the job properties. + Properties *JobProperties `json:"properties,omitempty"` + + // READ-ONLY; Gets the job resource identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job resource name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobDefinition. +func (j JobDefinition) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "id", j.ID) + populate(objectMap, "name", j.Name) + populate(objectMap, "properties", j.Properties) + populate(objectMap, "type", j.Type) + return json.Marshal(objectMap) +} + +type JobErrorAction struct { + // Gets or sets the storage queue message. + QueueMessage *StorageQueueMessage `json:"queueMessage,omitempty"` + + // Gets or sets the http requests. + Request *HTTPRequest `json:"request,omitempty"` + + // Gets or sets the retry policy. + RetryPolicy *RetryPolicy `json:"retryPolicy,omitempty"` + + // Gets or sets the service bus queue message. + ServiceBusQueueMessage *ServiceBusQueueMessage `json:"serviceBusQueueMessage,omitempty"` + + // Gets or sets the service bus topic message. + ServiceBusTopicMessage *ServiceBusTopicMessage `json:"serviceBusTopicMessage,omitempty"` + + // Gets or sets the job error action type. + Type *JobActionType `json:"type,omitempty"` +} + +type JobHistoryDefinition struct { + // READ-ONLY; Gets the job history identifier. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job history name. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Gets or sets the job history properties. + Properties *JobHistoryDefinitionProperties `json:"properties,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job history resource type. + Type *string `json:"type,omitempty" azure:"ro"` +} + +type JobHistoryDefinitionProperties struct { + // READ-ONLY; Gets the job history action name. + ActionName *JobHistoryActionName `json:"actionName,omitempty" azure:"ro"` + + // READ-ONLY; Gets the end time for this job. + EndTime *time.Time `json:"endTime,omitempty" azure:"ro"` + + // READ-ONLY; Gets the expected execution time for this job. + ExpectedExecutionTime *time.Time `json:"expectedExecutionTime,omitempty" azure:"ro"` + + // READ-ONLY; Gets the message for the job history. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; Gets the repeat count for the job. + RepeatCount *int32 `json:"repeatCount,omitempty" azure:"ro"` + + // READ-ONLY; Gets the retry count for job. + RetryCount *int32 `json:"retryCount,omitempty" azure:"ro"` + + // READ-ONLY; Gets the start time for this job. + StartTime *time.Time `json:"startTime,omitempty" azure:"ro"` + + // READ-ONLY; Gets the job history status. + Status *JobExecutionStatus `json:"status,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobHistoryDefinitionProperties. +func (j JobHistoryDefinitionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "actionName", j.ActionName) + populate(objectMap, "endTime", (*timeRFC3339)(j.EndTime)) + populate(objectMap, "expectedExecutionTime", (*timeRFC3339)(j.ExpectedExecutionTime)) + populate(objectMap, "message", j.Message) + populate(objectMap, "repeatCount", j.RepeatCount) + populate(objectMap, "retryCount", j.RetryCount) + populate(objectMap, "startTime", (*timeRFC3339)(j.StartTime)) + populate(objectMap, "status", j.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobHistoryDefinitionProperties. +func (j *JobHistoryDefinitionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "actionName": + err = unpopulate(val, &j.ActionName) + delete(rawMsg, key) + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "expectedExecutionTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.ExpectedExecutionTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "message": + err = unpopulate(val, &j.Message) + delete(rawMsg, key) + case "repeatCount": + err = unpopulate(val, &j.RepeatCount) + delete(rawMsg, key) + case "retryCount": + err = unpopulate(val, &j.RetryCount) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "status": + err = unpopulate(val, &j.Status) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type JobHistoryFilter struct { + // Gets or sets the job execution status. + Status *JobExecutionStatus `json:"status,omitempty"` +} + +type JobHistoryListResult struct { + // Gets or sets the URL to get the next set of job histories. + NextLink *string `json:"nextLink,omitempty"` + + // Gets or sets the job histories under job. + Value []*JobHistoryDefinition `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobHistoryListResult. +func (j JobHistoryListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +type JobListResult struct { + // Gets or sets the URL to get the next set of jobs. + NextLink *string `json:"nextLink,omitempty"` + + // Gets or sets all jobs under job collection. + Value []*JobDefinition `json:"value,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobListResult. +func (j JobListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", j.NextLink) + populate(objectMap, "value", j.Value) + return json.Marshal(objectMap) +} + +type JobMaxRecurrence struct { + // Gets or sets the frequency of recurrence (second, minute, hour, day, week, month). + Frequency *RecurrenceFrequency `json:"frequency,omitempty"` + + // Gets or sets the interval between retries. + Interval *int32 `json:"interval,omitempty"` +} + +type JobProperties struct { + // Gets or sets the job action. + Action *JobAction `json:"action,omitempty"` + + // Gets or sets the job recurrence. + Recurrence *JobRecurrence `json:"recurrence,omitempty"` + + // Gets or sets the job start time. + StartTime *time.Time `json:"startTime,omitempty"` + + // Gets or set the job state. + State *JobState `json:"state,omitempty"` + + // READ-ONLY; Gets the job status. + Status *JobStatus `json:"status,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobProperties. +func (j JobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "action", j.Action) + populate(objectMap, "recurrence", j.Recurrence) + populate(objectMap, "startTime", (*timeRFC3339)(j.StartTime)) + populate(objectMap, "state", j.State) + populate(objectMap, "status", j.Status) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobProperties. +func (j *JobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "action": + err = unpopulate(val, &j.Action) + delete(rawMsg, key) + case "recurrence": + err = unpopulate(val, &j.Recurrence) + delete(rawMsg, key) + case "startTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.StartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "state": + err = unpopulate(val, &j.State) + delete(rawMsg, key) + case "status": + err = unpopulate(val, &j.Status) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type JobRecurrence struct { + // Gets or sets the maximum number of times that the job should run. + Count *int32 `json:"count,omitempty"` + + // Gets or sets the time at which the job will complete. + EndTime *time.Time `json:"endTime,omitempty"` + + // Gets or sets the frequency of recurrence (second, minute, hour, day, week, month). + Frequency *RecurrenceFrequency `json:"frequency,omitempty"` + + // Gets or sets the interval between retries. + Interval *int32 `json:"interval,omitempty"` + Schedule *JobRecurrenceSchedule `json:"schedule,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobRecurrence. +func (j JobRecurrence) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "count", j.Count) + populate(objectMap, "endTime", (*timeRFC3339)(j.EndTime)) + populate(objectMap, "frequency", j.Frequency) + populate(objectMap, "interval", j.Interval) + populate(objectMap, "schedule", j.Schedule) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobRecurrence. +func (j *JobRecurrence) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "count": + err = unpopulate(val, &j.Count) + delete(rawMsg, key) + case "endTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.EndTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "frequency": + err = unpopulate(val, &j.Frequency) + delete(rawMsg, key) + case "interval": + err = unpopulate(val, &j.Interval) + delete(rawMsg, key) + case "schedule": + err = unpopulate(val, &j.Schedule) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type JobRecurrenceSchedule struct { + // Gets or sets the hours of the day that the job should execute at. + Hours []*int32 `json:"hours,omitempty"` + + // Gets or sets the minutes of the hour that the job should execute at. + Minutes []*int32 `json:"minutes,omitempty"` + + // Gets or sets the days of the month that the job should execute on. Must be between 1 and 31. + MonthDays []*int32 `json:"monthDays,omitempty"` + + // Gets or sets the occurrences of days within a month. + MonthlyOccurrences []*JobRecurrenceScheduleMonthlyOccurrence `json:"monthlyOccurrences,omitempty"` + + // Gets or sets the days of the week that the job should execute on. + WeekDays []*DayOfWeek `json:"weekDays,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobRecurrenceSchedule. +func (j JobRecurrenceSchedule) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "hours", j.Hours) + populate(objectMap, "minutes", j.Minutes) + populate(objectMap, "monthDays", j.MonthDays) + populate(objectMap, "monthlyOccurrences", j.MonthlyOccurrences) + populate(objectMap, "weekDays", j.WeekDays) + return json.Marshal(objectMap) +} + +type JobRecurrenceScheduleMonthlyOccurrence struct { + // Gets or sets the day. Must be one of monday, tuesday, wednesday, thursday, friday, saturday, sunday. + Day *JobScheduleDay `json:"day,omitempty"` + + // Gets or sets the occurrence. Must be between -5 and 5. + Occurrence *int32 `json:"Occurrence,omitempty"` +} + +type JobStateFilter struct { + // Gets or sets the job state. + State *JobState `json:"state,omitempty"` +} + +type JobStatus struct { + // READ-ONLY; Gets the number of times this job has executed. + ExecutionCount *int32 `json:"executionCount,omitempty" azure:"ro"` + + // READ-ONLY; Gets the number of times this job has failed. + FailureCount *int32 `json:"failureCount,omitempty" azure:"ro"` + + // READ-ONLY; Gets the number of faulted occurrences (occurrences that were retried and failed as many times as the retry policy states). + FaultedCount *int32 `json:"faultedCount,omitempty" azure:"ro"` + + // READ-ONLY; Gets the time the last occurrence executed in ISO-8601 format. Could be empty if job has not run yet. + LastExecutionTime *time.Time `json:"lastExecutionTime,omitempty" azure:"ro"` + + // READ-ONLY; Gets the time of the next occurrence in ISO-8601 format. Could be empty if the job is completed. + NextExecutionTime *time.Time `json:"nextExecutionTime,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type JobStatus. +func (j JobStatus) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "executionCount", j.ExecutionCount) + populate(objectMap, "failureCount", j.FailureCount) + populate(objectMap, "faultedCount", j.FaultedCount) + populate(objectMap, "lastExecutionTime", (*timeRFC3339)(j.LastExecutionTime)) + populate(objectMap, "nextExecutionTime", (*timeRFC3339)(j.NextExecutionTime)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JobStatus. +func (j *JobStatus) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "executionCount": + err = unpopulate(val, &j.ExecutionCount) + delete(rawMsg, key) + case "failureCount": + err = unpopulate(val, &j.FailureCount) + delete(rawMsg, key) + case "faultedCount": + err = unpopulate(val, &j.FaultedCount) + delete(rawMsg, key) + case "lastExecutionTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.LastExecutionTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "nextExecutionTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + j.NextExecutionTime = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// JobsCreateOrUpdateOptions contains the optional parameters for the Jobs.CreateOrUpdate method. +type JobsCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// JobsDeleteOptions contains the optional parameters for the Jobs.Delete method. +type JobsDeleteOptions struct { + // placeholder for future optional parameters +} + +// JobsGetOptions contains the optional parameters for the Jobs.Get method. +type JobsGetOptions struct { + // placeholder for future optional parameters +} + +// JobsListJobHistoryOptions contains the optional parameters for the Jobs.ListJobHistory method. +type JobsListJobHistoryOptions struct { + // The filter to apply on the job state. + Filter *string + // The (0-based) index of the job history list from which to begin requesting entries. + Skip *int32 + // the number of job history to request, in the of range of [1..100]. + Top *int32 +} + +// JobsListOptions contains the optional parameters for the Jobs.List method. +type JobsListOptions struct { + // The filter to apply on the job state. + Filter *string + // The (0-based) index of the job history list from which to begin requesting entries. + Skip *int32 + // The number of jobs to request, in the of range of [1..100]. + Top *int32 +} + +// JobsPatchOptions contains the optional parameters for the Jobs.Patch method. +type JobsPatchOptions struct { + // placeholder for future optional parameters +} + +// JobsRunOptions contains the optional parameters for the Jobs.Run method. +type JobsRunOptions struct { + // placeholder for future optional parameters +} + +type OAuthAuthentication struct { + HTTPAuthentication + // Gets or sets the audience. + Audience *string `json:"audience,omitempty"` + + // Gets or sets the client identifier. + ClientID *string `json:"clientId,omitempty"` + + // Gets or sets the secret, return value will always be empty. + Secret *string `json:"secret,omitempty"` + + // Gets or sets the tenant. + Tenant *string `json:"tenant,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type OAuthAuthentication. +func (o OAuthAuthentication) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + o.HTTPAuthentication.marshalInternal(objectMap, HTTPAuthenticationTypeActiveDirectoryOAuth) + populate(objectMap, "audience", o.Audience) + populate(objectMap, "clientId", o.ClientID) + populate(objectMap, "secret", o.Secret) + populate(objectMap, "tenant", o.Tenant) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OAuthAuthentication. +func (o *OAuthAuthentication) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "audience": + err = unpopulate(val, &o.Audience) + delete(rawMsg, key) + case "clientId": + err = unpopulate(val, &o.ClientID) + delete(rawMsg, key) + case "secret": + err = unpopulate(val, &o.Secret) + delete(rawMsg, key) + case "tenant": + err = unpopulate(val, &o.Tenant) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := o.HTTPAuthentication.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +type RetryPolicy struct { + // Gets or sets the number of times a retry should be attempted. + RetryCount *int32 `json:"retryCount,omitempty"` + + // Gets or sets the retry interval between retries, specify duration in ISO 8601 format. + RetryInterval *string `json:"retryInterval,omitempty"` + + // Gets or sets the retry strategy to be used. + RetryType *RetryType `json:"retryType,omitempty"` +} + +type SKU struct { + // Gets or set the SKU. + Name *SKUDefinition `json:"name,omitempty"` +} + +type ServiceBusAuthentication struct { + // Gets or sets the SAS key. + SasKey *string `json:"sasKey,omitempty"` + + // Gets or sets the SAS key name. + SasKeyName *string `json:"sasKeyName,omitempty"` + + // Gets or sets the authentication type. + Type *ServiceBusAuthenticationType `json:"type,omitempty"` +} + +type ServiceBusBrokeredMessageProperties struct { + // Gets or sets the content type. + ContentType *string `json:"contentType,omitempty"` + + // Gets or sets the correlation ID. + CorrelationID *string `json:"correlationId,omitempty"` + + // Gets or sets the force persistence. + ForcePersistence *bool `json:"forcePersistence,omitempty"` + + // Gets or sets the label. + Label *string `json:"label,omitempty"` + + // Gets or sets the message ID. + MessageID *string `json:"messageId,omitempty"` + + // Gets or sets the partition key. + PartitionKey *string `json:"partitionKey,omitempty"` + + // Gets or sets the reply to. + ReplyTo *string `json:"replyTo,omitempty"` + + // Gets or sets the reply to session ID. + ReplyToSessionID *string `json:"replyToSessionId,omitempty"` + + // Gets or sets the scheduled enqueue time UTC. + ScheduledEnqueueTimeUTC *time.Time `json:"scheduledEnqueueTimeUtc,omitempty"` + + // Gets or sets the session ID. + SessionID *string `json:"sessionId,omitempty"` + + // Gets or sets the time to live. + TimeToLive *string `json:"timeToLive,omitempty"` + + // Gets or sets the to. + To *string `json:"to,omitempty"` + + // Gets or sets the via partition key. + ViaPartitionKey *string `json:"viaPartitionKey,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusBrokeredMessageProperties. +func (s ServiceBusBrokeredMessageProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "contentType", s.ContentType) + populate(objectMap, "correlationId", s.CorrelationID) + populate(objectMap, "forcePersistence", s.ForcePersistence) + populate(objectMap, "label", s.Label) + populate(objectMap, "messageId", s.MessageID) + populate(objectMap, "partitionKey", s.PartitionKey) + populate(objectMap, "replyTo", s.ReplyTo) + populate(objectMap, "replyToSessionId", s.ReplyToSessionID) + populate(objectMap, "scheduledEnqueueTimeUtc", (*timeRFC3339)(s.ScheduledEnqueueTimeUTC)) + populate(objectMap, "sessionId", s.SessionID) + populate(objectMap, "timeToLive", s.TimeToLive) + populate(objectMap, "to", s.To) + populate(objectMap, "viaPartitionKey", s.ViaPartitionKey) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceBusBrokeredMessageProperties. +func (s *ServiceBusBrokeredMessageProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "contentType": + err = unpopulate(val, &s.ContentType) + delete(rawMsg, key) + case "correlationId": + err = unpopulate(val, &s.CorrelationID) + delete(rawMsg, key) + case "forcePersistence": + err = unpopulate(val, &s.ForcePersistence) + delete(rawMsg, key) + case "label": + err = unpopulate(val, &s.Label) + delete(rawMsg, key) + case "messageId": + err = unpopulate(val, &s.MessageID) + delete(rawMsg, key) + case "partitionKey": + err = unpopulate(val, &s.PartitionKey) + delete(rawMsg, key) + case "replyTo": + err = unpopulate(val, &s.ReplyTo) + delete(rawMsg, key) + case "replyToSessionId": + err = unpopulate(val, &s.ReplyToSessionID) + delete(rawMsg, key) + case "scheduledEnqueueTimeUtc": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.ScheduledEnqueueTimeUTC = (*time.Time)(&aux) + delete(rawMsg, key) + case "sessionId": + err = unpopulate(val, &s.SessionID) + delete(rawMsg, key) + case "timeToLive": + err = unpopulate(val, &s.TimeToLive) + delete(rawMsg, key) + case "to": + err = unpopulate(val, &s.To) + delete(rawMsg, key) + case "viaPartitionKey": + err = unpopulate(val, &s.ViaPartitionKey) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type ServiceBusMessage struct { + // Gets or sets the Service Bus authentication. + Authentication *ServiceBusAuthentication `json:"authentication,omitempty"` + + // Gets or sets the brokered message properties. + BrokeredMessageProperties *ServiceBusBrokeredMessageProperties `json:"brokeredMessageProperties,omitempty"` + + // Gets or sets the custom message properties. + CustomMessageProperties map[string]*string `json:"customMessageProperties,omitempty"` + + // Gets or sets the message. + Message *string `json:"message,omitempty"` + + // Gets or sets the namespace. + Namespace *string `json:"namespace,omitempty"` + + // Gets or sets the transport type. + TransportType *ServiceBusTransportType `json:"transportType,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusMessage. +func (s ServiceBusMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (s ServiceBusMessage) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "authentication", s.Authentication) + populate(objectMap, "brokeredMessageProperties", s.BrokeredMessageProperties) + populate(objectMap, "customMessageProperties", s.CustomMessageProperties) + populate(objectMap, "message", s.Message) + populate(objectMap, "namespace", s.Namespace) + populate(objectMap, "transportType", s.TransportType) +} + +type ServiceBusQueueMessage struct { + ServiceBusMessage + // Gets or sets the queue name. + QueueName *string `json:"queueName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusQueueMessage. +func (s ServiceBusQueueMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ServiceBusMessage.marshalInternal(objectMap) + populate(objectMap, "queueName", s.QueueName) + return json.Marshal(objectMap) +} + +type ServiceBusTopicMessage struct { + ServiceBusMessage + // Gets or sets the topic path. + TopicPath *string `json:"topicPath,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusTopicMessage. +func (s ServiceBusTopicMessage) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ServiceBusMessage.marshalInternal(objectMap) + populate(objectMap, "topicPath", s.TopicPath) + return json.Marshal(objectMap) +} + +type StorageQueueMessage struct { + // Gets or sets the message. + Message *string `json:"message,omitempty"` + + // Gets or sets the queue name. + QueueName *string `json:"queueName,omitempty"` + + // Gets or sets the SAS key. + SasToken *string `json:"sasToken,omitempty"` + + // Gets or sets the storage account name. + StorageAccount *string `json:"storageAccount,omitempty"` +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pagers.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pagers.go new file mode 100644 index 000000000000..26d06fea06aa --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pagers.go @@ -0,0 +1,234 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// JobCollectionsListByResourceGroupPager provides operations for iterating over paged responses. +type JobCollectionsListByResourceGroupPager struct { + client *JobCollectionsClient + current JobCollectionsListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, JobCollectionsListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *JobCollectionsListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *JobCollectionsListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.JobCollectionListResult.NextLink == nil || len(*p.current.JobCollectionListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current JobCollectionsListByResourceGroupResponse page. +func (p *JobCollectionsListByResourceGroupPager) PageResponse() JobCollectionsListByResourceGroupResponse { + return p.current +} + +// JobCollectionsListBySubscriptionPager provides operations for iterating over paged responses. +type JobCollectionsListBySubscriptionPager struct { + client *JobCollectionsClient + current JobCollectionsListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, JobCollectionsListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *JobCollectionsListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *JobCollectionsListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.JobCollectionListResult.NextLink == nil || len(*p.current.JobCollectionListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current JobCollectionsListBySubscriptionResponse page. +func (p *JobCollectionsListBySubscriptionPager) PageResponse() JobCollectionsListBySubscriptionResponse { + return p.current +} + +// JobsListJobHistoryPager provides operations for iterating over paged responses. +type JobsListJobHistoryPager struct { + client *JobsClient + current JobsListJobHistoryResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, JobsListJobHistoryResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *JobsListJobHistoryPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *JobsListJobHistoryPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.JobHistoryListResult.NextLink == nil || len(*p.current.JobHistoryListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listJobHistoryHandleError(resp) + return false + } + result, err := p.client.listJobHistoryHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current JobsListJobHistoryResponse page. +func (p *JobsListJobHistoryPager) PageResponse() JobsListJobHistoryResponse { + return p.current +} + +// JobsListPager provides operations for iterating over paged responses. +type JobsListPager struct { + client *JobsClient + current JobsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, JobsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *JobsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *JobsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.JobListResult.NextLink == nil || len(*p.current.JobListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current JobsListResponse page. +func (p *JobsListPager) PageResponse() JobsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pollers.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pollers.go new file mode 100644 index 000000000000..c309bc6d2385 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_pollers.go @@ -0,0 +1,145 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// JobCollectionsDeletePoller provides polling facilities until the operation reaches a terminal state. +type JobCollectionsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *JobCollectionsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *JobCollectionsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final JobCollectionsDeleteResponse will be returned. +func (p *JobCollectionsDeletePoller) FinalResponse(ctx context.Context) (JobCollectionsDeleteResponse, error) { + respType := JobCollectionsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return JobCollectionsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *JobCollectionsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// JobCollectionsDisablePoller provides polling facilities until the operation reaches a terminal state. +type JobCollectionsDisablePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *JobCollectionsDisablePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *JobCollectionsDisablePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final JobCollectionsDisableResponse will be returned. +func (p *JobCollectionsDisablePoller) FinalResponse(ctx context.Context) (JobCollectionsDisableResponse, error) { + respType := JobCollectionsDisableResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return JobCollectionsDisableResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *JobCollectionsDisablePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// JobCollectionsEnablePoller provides polling facilities until the operation reaches a terminal state. +type JobCollectionsEnablePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *JobCollectionsEnablePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *JobCollectionsEnablePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final JobCollectionsEnableResponse will be returned. +func (p *JobCollectionsEnablePoller) FinalResponse(ctx context.Context) (JobCollectionsEnableResponse, error) { + respType := JobCollectionsEnableResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return JobCollectionsEnableResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *JobCollectionsEnablePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_polymorphic_helpers.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_polymorphic_helpers.go new file mode 100644 index 000000000000..f3c94bd8044f --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_polymorphic_helpers.go @@ -0,0 +1,52 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import "encoding/json" + +func unmarshalHTTPAuthenticationClassification(rawMsg json.RawMessage) (HTTPAuthenticationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b HTTPAuthenticationClassification + switch m["type"] { + case string(HTTPAuthenticationTypeActiveDirectoryOAuth): + b = &OAuthAuthentication{} + case string(HTTPAuthenticationTypeBasic): + b = &BasicAuthentication{} + case string(HTTPAuthenticationTypeClientCertificate): + b = &ClientCertAuthentication{} + default: + b = &HTTPAuthentication{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalHTTPAuthenticationClassificationArray(rawMsg json.RawMessage) ([]HTTPAuthenticationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]HTTPAuthenticationClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalHTTPAuthenticationClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_response_types.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_response_types.go new file mode 100644 index 000000000000..e70272ba2999 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_response_types.go @@ -0,0 +1,281 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// JobCollectionsCreateOrUpdateResponse contains the response from method JobCollections.CreateOrUpdate. +type JobCollectionsCreateOrUpdateResponse struct { + JobCollectionsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsCreateOrUpdateResult contains the result from method JobCollections.CreateOrUpdate. +type JobCollectionsCreateOrUpdateResult struct { + JobCollectionDefinition +} + +// JobCollectionsDeletePollerResponse contains the response from method JobCollections.Delete. +type JobCollectionsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *JobCollectionsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l JobCollectionsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (JobCollectionsDeleteResponse, error) { + respType := JobCollectionsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a JobCollectionsDeletePollerResponse from the provided client and resume token. +func (l *JobCollectionsDeletePollerResponse) Resume(ctx context.Context, client *JobCollectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("JobCollectionsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &JobCollectionsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// JobCollectionsDeleteResponse contains the response from method JobCollections.Delete. +type JobCollectionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsDisablePollerResponse contains the response from method JobCollections.Disable. +type JobCollectionsDisablePollerResponse struct { + // Poller contains an initialized poller. + Poller *JobCollectionsDisablePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l JobCollectionsDisablePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (JobCollectionsDisableResponse, error) { + respType := JobCollectionsDisableResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a JobCollectionsDisablePollerResponse from the provided client and resume token. +func (l *JobCollectionsDisablePollerResponse) Resume(ctx context.Context, client *JobCollectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("JobCollectionsClient.Disable", token, client.pl, client.disableHandleError) + if err != nil { + return err + } + poller := &JobCollectionsDisablePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// JobCollectionsDisableResponse contains the response from method JobCollections.Disable. +type JobCollectionsDisableResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsEnablePollerResponse contains the response from method JobCollections.Enable. +type JobCollectionsEnablePollerResponse struct { + // Poller contains an initialized poller. + Poller *JobCollectionsEnablePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l JobCollectionsEnablePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (JobCollectionsEnableResponse, error) { + respType := JobCollectionsEnableResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a JobCollectionsEnablePollerResponse from the provided client and resume token. +func (l *JobCollectionsEnablePollerResponse) Resume(ctx context.Context, client *JobCollectionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("JobCollectionsClient.Enable", token, client.pl, client.enableHandleError) + if err != nil { + return err + } + poller := &JobCollectionsEnablePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// JobCollectionsEnableResponse contains the response from method JobCollections.Enable. +type JobCollectionsEnableResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsGetResponse contains the response from method JobCollections.Get. +type JobCollectionsGetResponse struct { + JobCollectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsGetResult contains the result from method JobCollections.Get. +type JobCollectionsGetResult struct { + JobCollectionDefinition +} + +// JobCollectionsListByResourceGroupResponse contains the response from method JobCollections.ListByResourceGroup. +type JobCollectionsListByResourceGroupResponse struct { + JobCollectionsListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsListByResourceGroupResult contains the result from method JobCollections.ListByResourceGroup. +type JobCollectionsListByResourceGroupResult struct { + JobCollectionListResult +} + +// JobCollectionsListBySubscriptionResponse contains the response from method JobCollections.ListBySubscription. +type JobCollectionsListBySubscriptionResponse struct { + JobCollectionsListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsListBySubscriptionResult contains the result from method JobCollections.ListBySubscription. +type JobCollectionsListBySubscriptionResult struct { + JobCollectionListResult +} + +// JobCollectionsPatchResponse contains the response from method JobCollections.Patch. +type JobCollectionsPatchResponse struct { + JobCollectionsPatchResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobCollectionsPatchResult contains the result from method JobCollections.Patch. +type JobCollectionsPatchResult struct { + JobCollectionDefinition +} + +// JobsCreateOrUpdateResponse contains the response from method Jobs.CreateOrUpdate. +type JobsCreateOrUpdateResponse struct { + JobsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsCreateOrUpdateResult contains the result from method Jobs.CreateOrUpdate. +type JobsCreateOrUpdateResult struct { + JobDefinition +} + +// JobsDeleteResponse contains the response from method Jobs.Delete. +type JobsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsGetResponse contains the response from method Jobs.Get. +type JobsGetResponse struct { + JobsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsGetResult contains the result from method Jobs.Get. +type JobsGetResult struct { + JobDefinition +} + +// JobsListJobHistoryResponse contains the response from method Jobs.ListJobHistory. +type JobsListJobHistoryResponse struct { + JobsListJobHistoryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsListJobHistoryResult contains the result from method Jobs.ListJobHistory. +type JobsListJobHistoryResult struct { + JobHistoryListResult +} + +// JobsListResponse contains the response from method Jobs.List. +type JobsListResponse struct { + JobsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsListResult contains the result from method Jobs.List. +type JobsListResult struct { + JobListResult +} + +// JobsPatchResponse contains the response from method Jobs.Patch. +type JobsPatchResponse struct { + JobsPatchResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// JobsPatchResult contains the result from method Jobs.Patch. +type JobsPatchResult struct { + JobDefinition +} + +// JobsRunResponse contains the response from method Jobs.Run. +type JobsRunResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} diff --git a/sdk/resourcemanager/scheduler/armscheduler/zz_generated_time_rfc3339.go b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..597cad4bd6e3 --- /dev/null +++ b/sdk/resourcemanager/scheduler/armscheduler/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armscheduler + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/search/armsearch/CHANGELOG.md b/sdk/resourcemanager/search/armsearch/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/search/armsearch/LICENSE.txt b/sdk/resourcemanager/search/armsearch/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/search/armsearch/README.md b/sdk/resourcemanager/search/armsearch/README.md new file mode 100644 index 000000000000..3a95903edff9 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/README.md @@ -0,0 +1,76 @@ +# Azure Search Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/search/armsearch)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/search/armsearch) + +The `armsearch` module provides operations for working with Azure Search. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/search/armsearch) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Search module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/search/armsearch +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Search. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Search + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Search modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armsearch.NewQueryKeysClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Search` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/search/armsearch/autorest.md b/sdk/resourcemanager/search/armsearch/autorest.md new file mode 100644 index 000000000000..1a19077c5e88 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/2a5304178ab7416e40622808dea5b630fb7854d9/specification/search/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/2a5304178ab7416e40622808dea5b630fb7854d9/specification/search/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/search/armsearch/build.go b/sdk/resourcemanager/search/armsearch/build.go new file mode 100644 index 000000000000..2a2f8e6a6d04 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/search/armsearch + +package armsearch diff --git a/sdk/resourcemanager/search/armsearch/ci.yml b/sdk/resourcemanager/search/armsearch/ci.yml new file mode 100644 index 000000000000..135f91939d21 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/search/armsearch/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/search/armsearch/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/search/armsearch' diff --git a/sdk/resourcemanager/search/armsearch/go.mod b/sdk/resourcemanager/search/armsearch/go.mod new file mode 100644 index 000000000000..2f901e2d96aa --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/search/armsearch + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/search/armsearch/go.sum b/sdk/resourcemanager/search/armsearch/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/search/armsearch/go_mod_tidy_hack.go b/sdk/resourcemanager/search/armsearch/go_mod_tidy_hack.go new file mode 100644 index 000000000000..3777112c45cd --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armsearch + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_adminkeys_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_adminkeys_client.go new file mode 100644 index 000000000000..66b25fd95e55 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_adminkeys_client.go @@ -0,0 +1,175 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// AdminKeysClient contains the methods for the AdminKeys group. +// Don't use this type directly, use NewAdminKeysClient() instead. +type AdminKeysClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewAdminKeysClient creates a new instance of AdminKeysClient with the specified values. +func NewAdminKeysClient(con *arm.Connection, subscriptionID string) *AdminKeysClient { + return &AdminKeysClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Get - Gets the primary and secondary admin API keys for the specified Azure Cognitive Search service. +// If the operation fails it returns the *CloudError error type. +func (client *AdminKeysClient) Get(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (AdminKeysGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, searchServiceName, options) + if err != nil { + return AdminKeysGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AdminKeysGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AdminKeysGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *AdminKeysClient) getCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/listAdminKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *AdminKeysClient) getHandleResponse(resp *http.Response) (AdminKeysGetResponse, error) { + result := AdminKeysGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminKeyResult); err != nil { + return AdminKeysGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *AdminKeysClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Regenerate - Regenerates either the primary or secondary admin API key. You can only regenerate one key at a time. +// If the operation fails it returns the *CloudError error type. +func (client *AdminKeysClient) Regenerate(ctx context.Context, resourceGroupName string, searchServiceName string, keyKind AdminKeyKind, options *SearchManagementRequestOptions) (AdminKeysRegenerateResponse, error) { + req, err := client.regenerateCreateRequest(ctx, resourceGroupName, searchServiceName, keyKind, options) + if err != nil { + return AdminKeysRegenerateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return AdminKeysRegenerateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return AdminKeysRegenerateResponse{}, client.regenerateHandleError(resp) + } + return client.regenerateHandleResponse(resp) +} + +// regenerateCreateRequest creates the Regenerate request. +func (client *AdminKeysClient) regenerateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, keyKind AdminKeyKind, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/regenerateAdminKey/{keyKind}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if keyKind == "" { + return nil, errors.New("parameter keyKind cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{keyKind}", url.PathEscape(string(keyKind))) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// regenerateHandleResponse handles the Regenerate response. +func (client *AdminKeysClient) regenerateHandleResponse(resp *http.Response) (AdminKeysRegenerateResponse, error) { + result := AdminKeysRegenerateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.AdminKeyResult); err != nil { + return AdminKeysRegenerateResponse{}, err + } + return result, nil +} + +// regenerateHandleError handles the Regenerate error response. +func (client *AdminKeysClient) regenerateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_constants.go b/sdk/resourcemanager/search/armsearch/zz_generated_constants.go new file mode 100644 index 000000000000..17c3b88ea794 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_constants.go @@ -0,0 +1,328 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +const ( + module = "armsearch" + version = "v0.1.1" +) + +type AdminKeyKind string + +const ( + AdminKeyKindPrimary AdminKeyKind = "primary" + AdminKeyKindSecondary AdminKeyKind = "secondary" +) + +// PossibleAdminKeyKindValues returns the possible values for the AdminKeyKind const type. +func PossibleAdminKeyKindValues() []AdminKeyKind { + return []AdminKeyKind{ + AdminKeyKindPrimary, + AdminKeyKindSecondary, + } +} + +// ToPtr returns a *AdminKeyKind pointing to the current value. +func (c AdminKeyKind) ToPtr() *AdminKeyKind { + return &c +} + +// HostingMode - Applicable only for the standard3 SKU. You can set this property to enable up to 3 high density partitions that allow up to 1000 indexes, +// which is much higher than the maximum indexes allowed for any +// other SKU. For the standard3 SKU, the value is either 'default' or 'highDensity'. For all other SKUs, this value must be 'default'. +type HostingMode string + +const ( + HostingModeDefault HostingMode = "default" + HostingModeHighDensity HostingMode = "highDensity" +) + +// PossibleHostingModeValues returns the possible values for the HostingMode const type. +func PossibleHostingModeValues() []HostingMode { + return []HostingMode{ + HostingModeDefault, + HostingModeHighDensity, + } +} + +// ToPtr returns a *HostingMode pointing to the current value. +func (c HostingMode) ToPtr() *HostingMode { + return &c +} + +// IdentityType - The identity type. +type IdentityType string + +const ( + IdentityTypeNone IdentityType = "None" + IdentityTypeSystemAssigned IdentityType = "SystemAssigned" +) + +// PossibleIdentityTypeValues returns the possible values for the IdentityType const type. +func PossibleIdentityTypeValues() []IdentityType { + return []IdentityType{ + IdentityTypeNone, + IdentityTypeSystemAssigned, + } +} + +// ToPtr returns a *IdentityType pointing to the current value. +func (c IdentityType) ToPtr() *IdentityType { + return &c +} + +// PrivateLinkServiceConnectionStatus - Status of the the private link service connection. Can be Pending, Approved, Rejected, or Disconnected. +type PrivateLinkServiceConnectionStatus string + +const ( + PrivateLinkServiceConnectionStatusPending PrivateLinkServiceConnectionStatus = "Pending" + PrivateLinkServiceConnectionStatusApproved PrivateLinkServiceConnectionStatus = "Approved" + PrivateLinkServiceConnectionStatusRejected PrivateLinkServiceConnectionStatus = "Rejected" + PrivateLinkServiceConnectionStatusDisconnected PrivateLinkServiceConnectionStatus = "Disconnected" +) + +// PossiblePrivateLinkServiceConnectionStatusValues returns the possible values for the PrivateLinkServiceConnectionStatus const type. +func PossiblePrivateLinkServiceConnectionStatusValues() []PrivateLinkServiceConnectionStatus { + return []PrivateLinkServiceConnectionStatus{ + PrivateLinkServiceConnectionStatusPending, + PrivateLinkServiceConnectionStatusApproved, + PrivateLinkServiceConnectionStatusRejected, + PrivateLinkServiceConnectionStatusDisconnected, + } +} + +// ToPtr returns a *PrivateLinkServiceConnectionStatus pointing to the current value. +func (c PrivateLinkServiceConnectionStatus) ToPtr() *PrivateLinkServiceConnectionStatus { + return &c +} + +// ProvisioningState - The state of the last provisioning operation performed on the search service. Provisioning is an intermediate state that occurs while +// service capacity is being established. After capacity is set up, +// provisioningState changes to either 'succeeded' or 'failed'. Client applications can poll provisioning status (the recommended polling interval is from +// 30 seconds to one minute) by using the Get +// Search Service operation to see when an operation is completed. If you are using the free service, this value tends to come back as 'succeeded' directly +// in the call to Create search service. This is +// because the free service uses capacity that is already set up. +type ProvisioningState string + +const ( + ProvisioningStateSucceeded ProvisioningState = "succeeded" + ProvisioningStateProvisioning ProvisioningState = "provisioning" + ProvisioningStateFailed ProvisioningState = "failed" +) + +// PossibleProvisioningStateValues returns the possible values for the ProvisioningState const type. +func PossibleProvisioningStateValues() []ProvisioningState { + return []ProvisioningState{ + ProvisioningStateSucceeded, + ProvisioningStateProvisioning, + ProvisioningStateFailed, + } +} + +// ToPtr returns a *ProvisioningState pointing to the current value. +func (c ProvisioningState) ToPtr() *ProvisioningState { + return &c +} + +// PublicNetworkAccess - This value can be set to 'enabled' to avoid breaking changes on existing customer resources and templates. If set to 'disabled', +// traffic over public interface is not allowed, and private endpoint +// connections would be the exclusive access method. +type PublicNetworkAccess string + +const ( + PublicNetworkAccessEnabled PublicNetworkAccess = "enabled" + PublicNetworkAccessDisabled PublicNetworkAccess = "disabled" +) + +// PossiblePublicNetworkAccessValues returns the possible values for the PublicNetworkAccess const type. +func PossiblePublicNetworkAccessValues() []PublicNetworkAccess { + return []PublicNetworkAccess{ + PublicNetworkAccessEnabled, + PublicNetworkAccessDisabled, + } +} + +// ToPtr returns a *PublicNetworkAccess pointing to the current value. +func (c PublicNetworkAccess) ToPtr() *PublicNetworkAccess { + return &c +} + +// SKUName - The SKU of the search service. Valid values include: 'free': Shared service. 'basic': Dedicated service with up to 3 replicas. 'standard': +// Dedicated service with up to 12 partitions and 12 replicas. +// 'standard2': Similar to standard, but with more capacity per search unit. 'standard3': The largest Standard offering with up to 12 partitions and 12 +// replicas (or up to 3 partitions with more indexes +// if you also set the hostingMode property to 'highDensity'). 'storageoptimizedl1': Supports 1TB per partition, up to 12 partitions. 'storageoptimizedl2': +// Supports 2TB per partition, up to 12 +// partitions.' +type SKUName string + +const ( + SKUNameFree SKUName = "free" + SKUNameBasic SKUName = "basic" + SKUNameStandard SKUName = "standard" + SKUNameStandard2 SKUName = "standard2" + SKUNameStandard3 SKUName = "standard3" + SKUNameStorageOptimizedL1 SKUName = "storage_optimized_l1" + SKUNameStorageOptimizedL2 SKUName = "storage_optimized_l2" +) + +// PossibleSKUNameValues returns the possible values for the SKUName const type. +func PossibleSKUNameValues() []SKUName { + return []SKUName{ + SKUNameFree, + SKUNameBasic, + SKUNameStandard, + SKUNameStandard2, + SKUNameStandard3, + SKUNameStorageOptimizedL1, + SKUNameStorageOptimizedL2, + } +} + +// ToPtr returns a *SKUName pointing to the current value. +func (c SKUName) ToPtr() *SKUName { + return &c +} + +// SearchServiceStatus - The status of the search service. Possible values include: 'running': The search service is running and no provisioning operations +// are underway. 'provisioning': The search service is being provisioned +// or scaled up or down. 'deleting': The search service is being deleted. 'degraded': The search service is degraded. This can occur when the underlying +// search units are not healthy. The search service +// is most likely operational, but performance might be slow and some requests might be dropped. 'disabled': The search service is disabled. In this state, +// the service will reject all API requests. +// 'error': The search service is in an error state. If your service is in the degraded, disabled, or error states, it means the Azure Cognitive Search +// team is actively investigating the underlying +// issue. Dedicated services in these states are still chargeable based on the number of search units provisioned. +type SearchServiceStatus string + +const ( + SearchServiceStatusRunning SearchServiceStatus = "running" + SearchServiceStatusProvisioning SearchServiceStatus = "provisioning" + SearchServiceStatusDeleting SearchServiceStatus = "deleting" + SearchServiceStatusDegraded SearchServiceStatus = "degraded" + SearchServiceStatusDisabled SearchServiceStatus = "disabled" + SearchServiceStatusError SearchServiceStatus = "error" +) + +// PossibleSearchServiceStatusValues returns the possible values for the SearchServiceStatus const type. +func PossibleSearchServiceStatusValues() []SearchServiceStatus { + return []SearchServiceStatus{ + SearchServiceStatusRunning, + SearchServiceStatusProvisioning, + SearchServiceStatusDeleting, + SearchServiceStatusDegraded, + SearchServiceStatusDisabled, + SearchServiceStatusError, + } +} + +// ToPtr returns a *SearchServiceStatus pointing to the current value. +func (c SearchServiceStatus) ToPtr() *SearchServiceStatus { + return &c +} + +// SharedPrivateLinkResourceAsyncOperationResult - The current status of the long running asynchronous shared private link resource operation. +type SharedPrivateLinkResourceAsyncOperationResult string + +const ( + SharedPrivateLinkResourceAsyncOperationResultFailed SharedPrivateLinkResourceAsyncOperationResult = "Failed" + SharedPrivateLinkResourceAsyncOperationResultRunning SharedPrivateLinkResourceAsyncOperationResult = "Running" + SharedPrivateLinkResourceAsyncOperationResultSucceeded SharedPrivateLinkResourceAsyncOperationResult = "Succeeded" +) + +// PossibleSharedPrivateLinkResourceAsyncOperationResultValues returns the possible values for the SharedPrivateLinkResourceAsyncOperationResult const type. +func PossibleSharedPrivateLinkResourceAsyncOperationResultValues() []SharedPrivateLinkResourceAsyncOperationResult { + return []SharedPrivateLinkResourceAsyncOperationResult{ + SharedPrivateLinkResourceAsyncOperationResultFailed, + SharedPrivateLinkResourceAsyncOperationResultRunning, + SharedPrivateLinkResourceAsyncOperationResultSucceeded, + } +} + +// ToPtr returns a *SharedPrivateLinkResourceAsyncOperationResult pointing to the current value. +func (c SharedPrivateLinkResourceAsyncOperationResult) ToPtr() *SharedPrivateLinkResourceAsyncOperationResult { + return &c +} + +// SharedPrivateLinkResourceProvisioningState - The provisioning state of the shared private link resource. Can be Updating, Deleting, Failed, Succeeded +// or Incomplete. +type SharedPrivateLinkResourceProvisioningState string + +const ( + SharedPrivateLinkResourceProvisioningStateUpdating SharedPrivateLinkResourceProvisioningState = "Updating" + SharedPrivateLinkResourceProvisioningStateDeleting SharedPrivateLinkResourceProvisioningState = "Deleting" + SharedPrivateLinkResourceProvisioningStateFailed SharedPrivateLinkResourceProvisioningState = "Failed" + SharedPrivateLinkResourceProvisioningStateSucceeded SharedPrivateLinkResourceProvisioningState = "Succeeded" + SharedPrivateLinkResourceProvisioningStateIncomplete SharedPrivateLinkResourceProvisioningState = "Incomplete" +) + +// PossibleSharedPrivateLinkResourceProvisioningStateValues returns the possible values for the SharedPrivateLinkResourceProvisioningState const type. +func PossibleSharedPrivateLinkResourceProvisioningStateValues() []SharedPrivateLinkResourceProvisioningState { + return []SharedPrivateLinkResourceProvisioningState{ + SharedPrivateLinkResourceProvisioningStateUpdating, + SharedPrivateLinkResourceProvisioningStateDeleting, + SharedPrivateLinkResourceProvisioningStateFailed, + SharedPrivateLinkResourceProvisioningStateSucceeded, + SharedPrivateLinkResourceProvisioningStateIncomplete, + } +} + +// ToPtr returns a *SharedPrivateLinkResourceProvisioningState pointing to the current value. +func (c SharedPrivateLinkResourceProvisioningState) ToPtr() *SharedPrivateLinkResourceProvisioningState { + return &c +} + +// SharedPrivateLinkResourceStatus - Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. +type SharedPrivateLinkResourceStatus string + +const ( + SharedPrivateLinkResourceStatusPending SharedPrivateLinkResourceStatus = "Pending" + SharedPrivateLinkResourceStatusApproved SharedPrivateLinkResourceStatus = "Approved" + SharedPrivateLinkResourceStatusRejected SharedPrivateLinkResourceStatus = "Rejected" + SharedPrivateLinkResourceStatusDisconnected SharedPrivateLinkResourceStatus = "Disconnected" +) + +// PossibleSharedPrivateLinkResourceStatusValues returns the possible values for the SharedPrivateLinkResourceStatus const type. +func PossibleSharedPrivateLinkResourceStatusValues() []SharedPrivateLinkResourceStatus { + return []SharedPrivateLinkResourceStatus{ + SharedPrivateLinkResourceStatusPending, + SharedPrivateLinkResourceStatusApproved, + SharedPrivateLinkResourceStatusRejected, + SharedPrivateLinkResourceStatusDisconnected, + } +} + +// ToPtr returns a *SharedPrivateLinkResourceStatus pointing to the current value. +func (c SharedPrivateLinkResourceStatus) ToPtr() *SharedPrivateLinkResourceStatus { + return &c +} + +// UnavailableNameReason - The reason why the name is not available. 'Invalid' indicates the name provided does not match the naming requirements (incorrect +// length, unsupported characters, etc.). 'AlreadyExists' indicates that +// the name is already in use and is therefore unavailable. +type UnavailableNameReason string + +const ( + UnavailableNameReasonAlreadyExists UnavailableNameReason = "AlreadyExists" + UnavailableNameReasonInvalid UnavailableNameReason = "Invalid" +) + +// PossibleUnavailableNameReasonValues returns the possible values for the UnavailableNameReason const type. +func PossibleUnavailableNameReasonValues() []UnavailableNameReason { + return []UnavailableNameReason{ + UnavailableNameReasonAlreadyExists, + UnavailableNameReasonInvalid, + } +} + +// ToPtr returns a *UnavailableNameReason pointing to the current value. +func (c UnavailableNameReason) ToPtr() *UnavailableNameReason { + return &c +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_models.go b/sdk/resourcemanager/search/armsearch/zz_generated_models.go new file mode 100644 index 000000000000..df832c5f57b7 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_models.go @@ -0,0 +1,722 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "encoding/json" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AdminKeyResult - Response containing the primary and secondary admin API keys for a given Azure Cognitive Search service. +type AdminKeyResult struct { + // READ-ONLY; The primary admin API key of the search service. + PrimaryKey *string `json:"primaryKey,omitempty" azure:"ro"` + + // READ-ONLY; The secondary admin API key of the search service. + SecondaryKey *string `json:"secondaryKey,omitempty" azure:"ro"` +} + +// AdminKeysGetOptions contains the optional parameters for the AdminKeys.Get method. +type AdminKeysGetOptions struct { + // placeholder for future optional parameters +} + +// AdminKeysRegenerateOptions contains the optional parameters for the AdminKeys.Regenerate method. +type AdminKeysRegenerateOptions struct { + // placeholder for future optional parameters +} + +// AsyncOperationResult - The details of a long running asynchronous shared private link resource operation +type AsyncOperationResult struct { + // The current status of the long running asynchronous shared private link resource operation. + Status *SharedPrivateLinkResourceAsyncOperationResult `json:"status,omitempty"` +} + +// CheckNameAvailabilityInput - Input of check name availability API. +type CheckNameAvailabilityInput struct { + // REQUIRED; The search service name to validate. Search service names must only contain lowercase letters, digits or dashes, cannot use dash as the first + // two or last one characters, cannot contain consecutive + // dashes, and must be between 2 and 60 characters in length. + Name *string `json:"name,omitempty"` + + // REQUIRED; The type of the resource whose name is to be validated. This value must always be 'searchServices'. + Type *string `json:"type,omitempty"` +} + +// CheckNameAvailabilityOutput - Output of check name availability API. +type CheckNameAvailabilityOutput struct { + // READ-ONLY; A value indicating whether the name is available. + IsNameAvailable *bool `json:"nameAvailable,omitempty" azure:"ro"` + + // READ-ONLY; A message that explains why the name is invalid and provides resource naming requirements. Available only if 'Invalid' is returned in the + // 'reason' property. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The reason why the name is not available. 'Invalid' indicates the name provided does not match the naming requirements (incorrect length, + // unsupported characters, etc.). 'AlreadyExists' indicates that + // the name is already in use and is therefore unavailable. + Reason *UnavailableNameReason `json:"reason,omitempty" azure:"ro"` +} + +// CloudError - Contains information about an API error. +// Implements the error and azcore.HTTPResponse interfaces. +type CloudError struct { + raw string + // Describes a particular API error with an error code and a message. + InnerError *CloudErrorBody `json:"error,omitempty"` +} + +// Error implements the error interface for type CloudError. +// The contents of the error text are not contractual and subject to change. +func (e CloudError) Error() string { + return e.raw +} + +// CloudErrorBody - Describes a particular API error with an error code and a message. +type CloudErrorBody struct { + // An error code that describes the error condition more precisely than an HTTP status code. Can be used to programmatically handle specific error cases. + Code *string `json:"code,omitempty"` + + // Contains nested errors that are related to this error. + Details []*CloudErrorBody `json:"details,omitempty"` + + // A message that describes the error in detail and provides debugging information. + Message *string `json:"message,omitempty"` + + // The target of the particular error (for example, the name of the property in error). + Target *string `json:"target,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CloudErrorBody. +func (c CloudErrorBody) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", c.Code) + populate(objectMap, "details", c.Details) + populate(objectMap, "message", c.Message) + populate(objectMap, "target", c.Target) + return json.Marshal(objectMap) +} + +// IPRule - The IP restriction rule of the Azure Cognitive Search service. +type IPRule struct { + // Value corresponding to a single IPv4 address (eg., 123.1.2.3) or an IP range in CIDR format (eg., 123.1.2.3/24) to be allowed. + Value *string `json:"value,omitempty"` +} + +// Identity for the resource. +type Identity struct { + // REQUIRED; The identity type. + Type *IdentityType `json:"type,omitempty"` + + // READ-ONLY; The principal ID of resource identity. + PrincipalID *string `json:"principalId,omitempty" azure:"ro"` + + // READ-ONLY; The tenant ID of resource. + TenantID *string `json:"tenantId,omitempty" azure:"ro"` +} + +// ListQueryKeysResult - Response containing the query API keys for a given Azure Cognitive Search service. +type ListQueryKeysResult struct { + // READ-ONLY; Request URL that can be used to query next page of query keys. Returned when the total number of requested query keys exceed maximum page + // size. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The query keys for the Azure Cognitive Search service. + Value []*QueryKey `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ListQueryKeysResult. +func (l ListQueryKeysResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", l.NextLink) + populate(objectMap, "value", l.Value) + return json.Marshal(objectMap) +} + +// NetworkRuleSet - Network specific rules that determine how the Azure Cognitive Search service may be reached. +type NetworkRuleSet struct { + // A list of IP restriction rules that defines the inbound network(s) with allowing access to the search service endpoint. At the meantime, all other public + // IP networks are blocked by the firewall. These + // restriction rules are applied only when the 'publicNetworkAccess' of the search service is 'enabled'; otherwise, traffic over public interface is not + // allowed even with any public IP rules, and private + // endpoint connections would be the exclusive access method. + IPRules []*IPRule `json:"ipRules,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type NetworkRuleSet. +func (n NetworkRuleSet) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "ipRules", n.IPRules) + return json.Marshal(objectMap) +} + +// Operation - Describes a REST API operation. +type Operation struct { + // READ-ONLY; The object that describes the operation. + Display *OperationDisplay `json:"display,omitempty" azure:"ro"` + + // READ-ONLY; The name of the operation. This name is of the form {provider}/{resource}/{operation}. + Name *string `json:"name,omitempty" azure:"ro"` +} + +// OperationDisplay - The object that describes the operation. +type OperationDisplay struct { + // READ-ONLY; The friendly name of the operation. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; The operation type: read, write, delete, listKeys/action, etc. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; The friendly name of the resource provider. + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; The resource type on which the operation is performed. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - The result of the request to list REST API operations. It contains a list of operations and a URL to get the next set of results. +type OperationListResult struct { + // READ-ONLY; The URL to get the next set of operation list results, if any. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The list of operations supported by the resource provider. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnection - Describes an existing Private Endpoint connection to the Azure Cognitive Search service. +type PrivateEndpointConnection struct { + Resource + // Describes the properties of an existing Private Endpoint connection to the Azure Cognitive Search service. + Properties *PrivateEndpointConnectionProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnection. +func (p PrivateEndpointConnection) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionListResult - Response containing a list of Private Endpoint connections. +type PrivateEndpointConnectionListResult struct { + // READ-ONLY; Request URL that can be used to query next page of private endpoint connections. Returned when the total number of requested private endpoint + // connections exceed maximum page size. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The list of Private Endpoint connections. + Value []*PrivateEndpointConnection `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointConnectionListResult. +func (p PrivateEndpointConnectionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateEndpointConnectionProperties - Describes the properties of an existing Private Endpoint connection to the Azure Cognitive Search service. +type PrivateEndpointConnectionProperties struct { + // The private endpoint resource from Microsoft.Network provider. + PrivateEndpoint *PrivateEndpointConnectionPropertiesPrivateEndpoint `json:"privateEndpoint,omitempty"` + + // Describes the current state of an existing Private Link Service connection to the Azure Private Endpoint. + PrivateLinkServiceConnectionState *PrivateEndpointConnectionPropertiesPrivateLinkServiceConnectionState `json:"privateLinkServiceConnectionState,omitempty"` +} + +// PrivateEndpointConnectionPropertiesPrivateEndpoint - The private endpoint resource from Microsoft.Network provider. +type PrivateEndpointConnectionPropertiesPrivateEndpoint struct { + // The resource id of the private endpoint resource from Microsoft.Network provider. + ID *string `json:"id,omitempty"` +} + +// PrivateEndpointConnectionPropertiesPrivateLinkServiceConnectionState - Describes the current state of an existing Private Link Service connection to +// the Azure Private Endpoint. +type PrivateEndpointConnectionPropertiesPrivateLinkServiceConnectionState struct { + // A description of any extra actions that may be required. + ActionsRequired *string `json:"actionsRequired,omitempty"` + + // The description for the private link service connection state. + Description *string `json:"description,omitempty"` + + // Status of the the private link service connection. Can be Pending, Approved, Rejected, or Disconnected. + Status *PrivateLinkServiceConnectionStatus `json:"status,omitempty"` +} + +// PrivateEndpointConnectionsDeleteOptions contains the optional parameters for the PrivateEndpointConnections.Delete method. +type PrivateEndpointConnectionsDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsGetOptions contains the optional parameters for the PrivateEndpointConnections.Get method. +type PrivateEndpointConnectionsGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsListByServiceOptions contains the optional parameters for the PrivateEndpointConnections.ListByService method. +type PrivateEndpointConnectionsListByServiceOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointConnectionsUpdateOptions contains the optional parameters for the PrivateEndpointConnections.Update method. +type PrivateEndpointConnectionsUpdateOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResource - Describes a supported private link resource for the Azure Cognitive Search service. +type PrivateLinkResource struct { + Resource + // READ-ONLY; Describes the properties of a supported private link resource for the Azure Cognitive Search service. + Properties *PrivateLinkResourceProperties `json:"properties,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResource. +func (p PrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateLinkResourceProperties - Describes the properties of a supported private link resource for the Azure Cognitive Search service. For a given API +// version, this represents the 'supported' groupIds when creating a shared private +// link resource. +type PrivateLinkResourceProperties struct { + // READ-ONLY; The group ID of the private link resource. + GroupID *string `json:"groupId,omitempty" azure:"ro"` + + // READ-ONLY; The list of required members of the private link resource. + RequiredMembers []*string `json:"requiredMembers,omitempty" azure:"ro"` + + // READ-ONLY; The list of required DNS zone names of the private link resource. + RequiredZoneNames []*string `json:"requiredZoneNames,omitempty" azure:"ro"` + + // READ-ONLY; The list of resources that are onboarded to private link service, that are supported by Azure Cognitive Search. + ShareablePrivateLinkResourceTypes []*ShareablePrivateLinkResourceType `json:"shareablePrivateLinkResourceTypes,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourceProperties. +func (p PrivateLinkResourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupId", p.GroupID) + populate(objectMap, "requiredMembers", p.RequiredMembers) + populate(objectMap, "requiredZoneNames", p.RequiredZoneNames) + populate(objectMap, "shareablePrivateLinkResourceTypes", p.ShareablePrivateLinkResourceTypes) + return json.Marshal(objectMap) +} + +// PrivateLinkResourcesListSupportedOptions contains the optional parameters for the PrivateLinkResources.ListSupported method. +type PrivateLinkResourcesListSupportedOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkResourcesResult - Response containing a list of supported Private Link Resources. +type PrivateLinkResourcesResult struct { + // READ-ONLY; The list of supported Private Link Resources. + Value []*PrivateLinkResource `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkResourcesResult. +func (p PrivateLinkResourcesResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// QueryKey - Describes an API key for a given Azure Cognitive Search service that has permissions for query operations only. +type QueryKey struct { + // READ-ONLY; The value of the query API key. + Key *string `json:"key,omitempty" azure:"ro"` + + // READ-ONLY; The name of the query API key; may be empty. + Name *string `json:"name,omitempty" azure:"ro"` +} + +// QueryKeysCreateOptions contains the optional parameters for the QueryKeys.Create method. +type QueryKeysCreateOptions struct { + // placeholder for future optional parameters +} + +// QueryKeysDeleteOptions contains the optional parameters for the QueryKeys.Delete method. +type QueryKeysDeleteOptions struct { + // placeholder for future optional parameters +} + +// QueryKeysListBySearchServiceOptions contains the optional parameters for the QueryKeys.ListBySearchService method. +type QueryKeysListBySearchServiceOptions struct { + // placeholder for future optional parameters +} + +// Resource - Common fields that are returned in the response for all Azure Resource Manager resources +type Resource struct { + // READ-ONLY; Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +// SKU - Defines the SKU of an Azure Cognitive Search Service, which determines price tier and capacity limits. +type SKU struct { + // The SKU of the search service. Valid values include: 'free': Shared service. 'basic': Dedicated service with up to 3 replicas. 'standard': Dedicated + // service with up to 12 partitions and 12 replicas. + // 'standard2': Similar to standard, but with more capacity per search unit. 'standard3': The largest Standard offering with up to 12 partitions and 12 + // replicas (or up to 3 partitions with more indexes + // if you also set the hostingMode property to 'highDensity'). 'storageoptimizedl1': Supports 1TB per partition, up to 12 partitions. 'storageoptimizedl2': + // Supports 2TB per partition, up to 12 + // partitions.' + Name *SKUName `json:"name,omitempty"` +} + +// SearchManagementRequestOptions contains a group of parameters for the AdminKeys.Get method. +type SearchManagementRequestOptions struct { + // A client-generated GUID value that identifies this request. If specified, this will be included in response information as a way to track the request. + ClientRequestID *string +} + +// SearchService - Describes an Azure Cognitive Search service and its current state. +type SearchService struct { + TrackedResource + // The identity of the resource. + Identity *Identity `json:"identity,omitempty"` + + // Properties of the search service. + Properties *SearchServiceProperties `json:"properties,omitempty"` + + // The SKU of the Search Service, which determines price tier and capacity limits. This property is required when creating a new Search Service. + SKU *SKU `json:"sku,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SearchService. +func (s SearchService) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "identity", s.Identity) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + return json.Marshal(objectMap) +} + +// SearchServiceListResult - Response containing a list of Azure Cognitive Search services. +type SearchServiceListResult struct { + // READ-ONLY; Request URL that can be used to query next page of search services. Returned when the total number of requested search services exceed maximum + // page size. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; The list of search services. + Value []*SearchService `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SearchServiceListResult. +func (s SearchServiceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// SearchServiceProperties - Properties of the search service. +type SearchServiceProperties struct { + // Applicable only for the standard3 SKU. You can set this property to enable up to 3 high density partitions that allow up to 1000 indexes, which is much + // higher than the maximum indexes allowed for any + // other SKU. For the standard3 SKU, the value is either 'default' or 'highDensity'. For all other SKUs, this value must be 'default'. + HostingMode *HostingMode `json:"hostingMode,omitempty"` + + // Network specific rules that determine how the Azure Cognitive Search service may be reached. + NetworkRuleSet *NetworkRuleSet `json:"networkRuleSet,omitempty"` + + // The number of partitions in the search service; if specified, it can be 1, 2, 3, 4, 6, or 12. Values greater than 1 are only valid for standard SKUs. + // For 'standard3' services with hostingMode set to + // 'highDensity', the allowed values are between 1 and 3. + PartitionCount *int32 `json:"partitionCount,omitempty"` + + // This value can be set to 'enabled' to avoid breaking changes on existing customer resources and templates. If set to 'disabled', traffic over public + // interface is not allowed, and private endpoint + // connections would be the exclusive access method. + PublicNetworkAccess *PublicNetworkAccess `json:"publicNetworkAccess,omitempty"` + + // The number of replicas in the search service. If specified, it must be a value between 1 and 12 inclusive for standard SKUs or between 1 and 3 inclusive + // for basic SKU. + ReplicaCount *int32 `json:"replicaCount,omitempty"` + + // READ-ONLY; The list of private endpoint connections to the Azure Cognitive Search service. + PrivateEndpointConnections []*PrivateEndpointConnection `json:"privateEndpointConnections,omitempty" azure:"ro"` + + // READ-ONLY; The state of the last provisioning operation performed on the search service. Provisioning is an intermediate state that occurs while service + // capacity is being established. After capacity is set up, + // provisioningState changes to either 'succeeded' or 'failed'. Client applications can poll provisioning status (the recommended polling interval is from + // 30 seconds to one minute) by using the Get + // Search Service operation to see when an operation is completed. If you are using the free service, this value tends to come back as 'succeeded' directly + // in the call to Create search service. This is + // because the free service uses capacity that is already set up. + ProvisioningState *ProvisioningState `json:"provisioningState,omitempty" azure:"ro"` + + // READ-ONLY; The list of shared private link resources managed by the Azure Cognitive Search service. + SharedPrivateLinkResources []*SharedPrivateLinkResource `json:"sharedPrivateLinkResources,omitempty" azure:"ro"` + + // READ-ONLY; The status of the search service. Possible values include: 'running': The search service is running and no provisioning operations are underway. + // 'provisioning': The search service is being provisioned + // or scaled up or down. 'deleting': The search service is being deleted. 'degraded': The search service is degraded. This can occur when the underlying + // search units are not healthy. The search service + // is most likely operational, but performance might be slow and some requests might be dropped. 'disabled': The search service is disabled. In this state, + // the service will reject all API requests. + // 'error': The search service is in an error state. If your service is in the degraded, disabled, or error states, it means the Azure Cognitive Search + // team is actively investigating the underlying + // issue. Dedicated services in these states are still chargeable based on the number of search units provisioned. + Status *SearchServiceStatus `json:"status,omitempty" azure:"ro"` + + // READ-ONLY; The details of the search service status. + StatusDetails *string `json:"statusDetails,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SearchServiceProperties. +func (s SearchServiceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "hostingMode", s.HostingMode) + populate(objectMap, "networkRuleSet", s.NetworkRuleSet) + populate(objectMap, "partitionCount", s.PartitionCount) + populate(objectMap, "privateEndpointConnections", s.PrivateEndpointConnections) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "publicNetworkAccess", s.PublicNetworkAccess) + populate(objectMap, "replicaCount", s.ReplicaCount) + populate(objectMap, "sharedPrivateLinkResources", s.SharedPrivateLinkResources) + populate(objectMap, "status", s.Status) + populate(objectMap, "statusDetails", s.StatusDetails) + return json.Marshal(objectMap) +} + +// SearchServiceUpdate - The parameters used to update an Azure Cognitive Search service. +type SearchServiceUpdate struct { + Resource + // The identity of the resource. + Identity *Identity `json:"identity,omitempty"` + + // The geographic location of the resource. This must be one of the supported and registered Azure Geo Regions (for example, West US, East US, Southeast + // Asia, and so forth). This property is required + // when creating a new resource. + Location *string `json:"location,omitempty"` + + // Properties of the search service. + Properties *SearchServiceProperties `json:"properties,omitempty"` + + // The SKU of the Search Service, which determines price tier and capacity limits. This property is required when creating a new Search Service. + SKU *SKU `json:"sku,omitempty"` + + // Tags to help categorize the resource in the Azure portal. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SearchServiceUpdate. +func (s SearchServiceUpdate) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Resource.marshalInternal(objectMap) + populate(objectMap, "identity", s.Identity) + populate(objectMap, "location", s.Location) + populate(objectMap, "properties", s.Properties) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "tags", s.Tags) + return json.Marshal(objectMap) +} + +// ServicesBeginCreateOrUpdateOptions contains the optional parameters for the Services.BeginCreateOrUpdate method. +type ServicesBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// ServicesCheckNameAvailabilityOptions contains the optional parameters for the Services.CheckNameAvailability method. +type ServicesCheckNameAvailabilityOptions struct { + // placeholder for future optional parameters +} + +// ServicesDeleteOptions contains the optional parameters for the Services.Delete method. +type ServicesDeleteOptions struct { + // placeholder for future optional parameters +} + +// ServicesGetOptions contains the optional parameters for the Services.Get method. +type ServicesGetOptions struct { + // placeholder for future optional parameters +} + +// ServicesListByResourceGroupOptions contains the optional parameters for the Services.ListByResourceGroup method. +type ServicesListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ServicesListBySubscriptionOptions contains the optional parameters for the Services.ListBySubscription method. +type ServicesListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ServicesUpdateOptions contains the optional parameters for the Services.Update method. +type ServicesUpdateOptions struct { + // placeholder for future optional parameters +} + +// ShareablePrivateLinkResourceProperties - Describes the properties of a resource type that has been onboarded to private link service, supported by Azure +// Cognitive Search. +type ShareablePrivateLinkResourceProperties struct { + // READ-ONLY; The description of the resource type that has been onboarded to private link service, supported by Azure Cognitive Search. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; The resource provider group id for the resource that has been onboarded to private link service, supported by Azure Cognitive Search. + GroupID *string `json:"groupId,omitempty" azure:"ro"` + + // READ-ONLY; The resource provider type for the resource that has been onboarded to private link service, supported by Azure Cognitive Search. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// ShareablePrivateLinkResourceType - Describes an resource type that has been onboarded to private link service, supported by Azure Cognitive Search. +type ShareablePrivateLinkResourceType struct { + // READ-ONLY; The name of the resource type that has been onboarded to private link service, supported by Azure Cognitive Search. + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; Describes the properties of a resource type that has been onboarded to private link service, supported by Azure Cognitive Search. + Properties *ShareablePrivateLinkResourceProperties `json:"properties,omitempty" azure:"ro"` +} + +// SharedPrivateLinkResource - Describes a Shared Private Link Resource managed by the Azure Cognitive Search service. +type SharedPrivateLinkResource struct { + Resource + // Describes the properties of a Shared Private Link Resource managed by the Azure Cognitive Search service. + Properties *SharedPrivateLinkResourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type SharedPrivateLinkResource. +func (s SharedPrivateLinkResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.Resource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// SharedPrivateLinkResourceListResult - Response containing a list of Shared Private Link Resources. +type SharedPrivateLinkResourceListResult struct { + // The URL to get the next set of shared private link resources, if there are any. + NextLink *string `json:"nextLink,omitempty"` + + // READ-ONLY; The list of Shared Private Link Resources. + Value []*SharedPrivateLinkResource `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SharedPrivateLinkResourceListResult. +func (s SharedPrivateLinkResourceListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// SharedPrivateLinkResourceProperties - Describes the properties of an existing Shared Private Link Resource managed by the Azure Cognitive Search service. +type SharedPrivateLinkResourceProperties struct { + // The group id from the provider of resource the shared private link resource is for. + GroupID *string `json:"groupId,omitempty"` + + // The resource id of the resource the shared private link resource is for. + PrivateLinkResourceID *string `json:"privateLinkResourceId,omitempty"` + + // The provisioning state of the shared private link resource. Can be Updating, Deleting, Failed, Succeeded or Incomplete. + ProvisioningState *SharedPrivateLinkResourceProvisioningState `json:"provisioningState,omitempty"` + + // The request message for requesting approval of the shared private link resource. + RequestMessage *string `json:"requestMessage,omitempty"` + + // Optional. Can be used to specify the Azure Resource Manager location of the resource to which a shared private link is to be created. This is only required + // for those resources whose DNS configuration + // are regional (such as Azure Kubernetes Service). + ResourceRegion *string `json:"resourceRegion,omitempty"` + + // Status of the shared private link resource. Can be Pending, Approved, Rejected or Disconnected. + Status *SharedPrivateLinkResourceStatus `json:"status,omitempty"` +} + +// SharedPrivateLinkResourcesBeginCreateOrUpdateOptions contains the optional parameters for the SharedPrivateLinkResources.BeginCreateOrUpdate method. +type SharedPrivateLinkResourcesBeginCreateOrUpdateOptions struct { + // placeholder for future optional parameters +} + +// SharedPrivateLinkResourcesBeginDeleteOptions contains the optional parameters for the SharedPrivateLinkResources.BeginDelete method. +type SharedPrivateLinkResourcesBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// SharedPrivateLinkResourcesGetOptions contains the optional parameters for the SharedPrivateLinkResources.Get method. +type SharedPrivateLinkResourcesGetOptions struct { + // placeholder for future optional parameters +} + +// SharedPrivateLinkResourcesListByServiceOptions contains the optional parameters for the SharedPrivateLinkResources.ListByService method. +type SharedPrivateLinkResourcesListByServiceOptions struct { + // placeholder for future optional parameters +} + +// TrackedResource - The resource model definition for an Azure Resource Manager tracked top level resource which has 'tags' and a 'location' +type TrackedResource struct { + Resource + // REQUIRED; The geo-location where the resource lives + Location *string `json:"location,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (t TrackedResource) marshalInternal(objectMap map[string]interface{}) { + t.Resource.marshalInternal(objectMap) + populate(objectMap, "location", t.Location) + populate(objectMap, "tags", t.Tags) +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_operations_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_operations_client.go new file mode 100644 index 000000000000..09e8454c38d5 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_operations_client.go @@ -0,0 +1,84 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available REST API operations of the Microsoft.Search provider. +// If the operation fails it returns the *CloudError error type. +func (client *OperationsClient) List(ctx context.Context, options *OperationsListOptions) (OperationsListResponse, error) { + req, err := client.listCreateRequest(ctx, options) + if err != nil { + return OperationsListResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OperationsListResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OperationsListResponse{}, client.listHandleError(resp) + } + return client.listHandleResponse(resp) +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.Search/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_pagers.go b/sdk/resourcemanager/search/armsearch/zz_generated_pagers.go new file mode 100644 index 000000000000..833f0fcbbc74 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_pagers.go @@ -0,0 +1,288 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointConnectionsListByServicePager provides operations for iterating over paged responses. +type PrivateEndpointConnectionsListByServicePager struct { + client *PrivateEndpointConnectionsClient + current PrivateEndpointConnectionsListByServiceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, PrivateEndpointConnectionsListByServiceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *PrivateEndpointConnectionsListByServicePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *PrivateEndpointConnectionsListByServicePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.PrivateEndpointConnectionListResult.NextLink == nil || len(*p.current.PrivateEndpointConnectionListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByServiceHandleError(resp) + return false + } + result, err := p.client.listByServiceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current PrivateEndpointConnectionsListByServiceResponse page. +func (p *PrivateEndpointConnectionsListByServicePager) PageResponse() PrivateEndpointConnectionsListByServiceResponse { + return p.current +} + +// QueryKeysListBySearchServicePager provides operations for iterating over paged responses. +type QueryKeysListBySearchServicePager struct { + client *QueryKeysClient + current QueryKeysListBySearchServiceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, QueryKeysListBySearchServiceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *QueryKeysListBySearchServicePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *QueryKeysListBySearchServicePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ListQueryKeysResult.NextLink == nil || len(*p.current.ListQueryKeysResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySearchServiceHandleError(resp) + return false + } + result, err := p.client.listBySearchServiceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current QueryKeysListBySearchServiceResponse page. +func (p *QueryKeysListBySearchServicePager) PageResponse() QueryKeysListBySearchServiceResponse { + return p.current +} + +// ServicesListByResourceGroupPager provides operations for iterating over paged responses. +type ServicesListByResourceGroupPager struct { + client *ServicesClient + current ServicesListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ServicesListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ServicesListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ServicesListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SearchServiceListResult.NextLink == nil || len(*p.current.SearchServiceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ServicesListByResourceGroupResponse page. +func (p *ServicesListByResourceGroupPager) PageResponse() ServicesListByResourceGroupResponse { + return p.current +} + +// ServicesListBySubscriptionPager provides operations for iterating over paged responses. +type ServicesListBySubscriptionPager struct { + client *ServicesClient + current ServicesListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ServicesListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ServicesListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ServicesListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SearchServiceListResult.NextLink == nil || len(*p.current.SearchServiceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ServicesListBySubscriptionResponse page. +func (p *ServicesListBySubscriptionPager) PageResponse() ServicesListBySubscriptionResponse { + return p.current +} + +// SharedPrivateLinkResourcesListByServicePager provides operations for iterating over paged responses. +type SharedPrivateLinkResourcesListByServicePager struct { + client *SharedPrivateLinkResourcesClient + current SharedPrivateLinkResourcesListByServiceResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, SharedPrivateLinkResourcesListByServiceResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *SharedPrivateLinkResourcesListByServicePager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *SharedPrivateLinkResourcesListByServicePager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.SharedPrivateLinkResourceListResult.NextLink == nil || len(*p.current.SharedPrivateLinkResourceListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByServiceHandleError(resp) + return false + } + result, err := p.client.listByServiceHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current SharedPrivateLinkResourcesListByServiceResponse page. +func (p *SharedPrivateLinkResourcesListByServicePager) PageResponse() SharedPrivateLinkResourcesListByServiceResponse { + return p.current +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_pollers.go b/sdk/resourcemanager/search/armsearch/zz_generated_pollers.go new file mode 100644 index 000000000000..9c99dff40b55 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_pollers.go @@ -0,0 +1,145 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// ServicesCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type ServicesCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ServicesCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ServicesCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ServicesCreateOrUpdateResponse will be returned. +func (p *ServicesCreateOrUpdatePoller) FinalResponse(ctx context.Context) (ServicesCreateOrUpdateResponse, error) { + respType := ServicesCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.SearchService) + if err != nil { + return ServicesCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ServicesCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SharedPrivateLinkResourcesCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type SharedPrivateLinkResourcesCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SharedPrivateLinkResourcesCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SharedPrivateLinkResourcesCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SharedPrivateLinkResourcesCreateOrUpdateResponse will be returned. +func (p *SharedPrivateLinkResourcesCreateOrUpdatePoller) FinalResponse(ctx context.Context) (SharedPrivateLinkResourcesCreateOrUpdateResponse, error) { + respType := SharedPrivateLinkResourcesCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.SharedPrivateLinkResource) + if err != nil { + return SharedPrivateLinkResourcesCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SharedPrivateLinkResourcesCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SharedPrivateLinkResourcesDeletePoller provides polling facilities until the operation reaches a terminal state. +type SharedPrivateLinkResourcesDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SharedPrivateLinkResourcesDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SharedPrivateLinkResourcesDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SharedPrivateLinkResourcesDeleteResponse will be returned. +func (p *SharedPrivateLinkResourcesDeletePoller) FinalResponse(ctx context.Context) (SharedPrivateLinkResourcesDeleteResponse, error) { + respType := SharedPrivateLinkResourcesDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return SharedPrivateLinkResourcesDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SharedPrivateLinkResourcesDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_privateendpointconnections_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_privateendpointconnections_client.go new file mode 100644 index 000000000000..8edf658994fe --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_privateendpointconnections_client.go @@ -0,0 +1,316 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointConnectionsClient contains the methods for the PrivateEndpointConnections group. +// Don't use this type directly, use NewPrivateEndpointConnectionsClient() instead. +type PrivateEndpointConnectionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateEndpointConnectionsClient creates a new instance of PrivateEndpointConnectionsClient with the specified values. +func NewPrivateEndpointConnectionsClient(con *arm.Connection, subscriptionID string) *PrivateEndpointConnectionsClient { + return &PrivateEndpointConnectionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Delete - Disconnects the private endpoint connection and deletes it from the search service. +// If the operation fails it returns the *CloudError error type. +func (client *PrivateEndpointConnectionsClient) Delete(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, options *SearchManagementRequestOptions) (PrivateEndpointConnectionsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, searchServiceName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNotFound) { + return PrivateEndpointConnectionsDeleteResponse{}, client.deleteHandleError(resp) + } + return client.deleteHandleResponse(resp) +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointConnectionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleResponse handles the Delete response. +func (client *PrivateEndpointConnectionsClient) deleteHandleResponse(resp *http.Response) (PrivateEndpointConnectionsDeleteResponse, error) { + result := PrivateEndpointConnectionsDeleteResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsDeleteResponse{}, err + } + return result, nil +} + +// deleteHandleError handles the Delete error response. +func (client *PrivateEndpointConnectionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the details of the private endpoint connection to the search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *PrivateEndpointConnectionsClient) Get(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, options *SearchManagementRequestOptions) (PrivateEndpointConnectionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, searchServiceName, privateEndpointConnectionName, options) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointConnectionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointConnectionsClient) getHandleResponse(resp *http.Response) (PrivateEndpointConnectionsGetResponse, error) { + result := PrivateEndpointConnectionsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateEndpointConnectionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByService - Gets a list of all private endpoint connections in the given service. +// If the operation fails it returns the *CloudError error type. +func (client *PrivateEndpointConnectionsClient) ListByService(resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) *PrivateEndpointConnectionsListByServicePager { + return &PrivateEndpointConnectionsListByServicePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByServiceCreateRequest(ctx, resourceGroupName, searchServiceName, options) + }, + advancer: func(ctx context.Context, resp PrivateEndpointConnectionsListByServiceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.PrivateEndpointConnectionListResult.NextLink) + }, + } +} + +// listByServiceCreateRequest creates the ListByService request. +func (client *PrivateEndpointConnectionsClient) listByServiceCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByServiceHandleResponse handles the ListByService response. +func (client *PrivateEndpointConnectionsClient) listByServiceHandleResponse(resp *http.Response) (PrivateEndpointConnectionsListByServiceResponse, error) { + result := PrivateEndpointConnectionsListByServiceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnectionListResult); err != nil { + return PrivateEndpointConnectionsListByServiceResponse{}, err + } + return result, nil +} + +// listByServiceHandleError handles the ListByService error response. +func (client *PrivateEndpointConnectionsClient) listByServiceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates a Private Endpoint connection to the search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *PrivateEndpointConnectionsClient) Update(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *SearchManagementRequestOptions) (PrivateEndpointConnectionsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, searchServiceName, privateEndpointConnectionName, privateEndpointConnection, options) + if err != nil { + return PrivateEndpointConnectionsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointConnectionsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointConnectionsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *PrivateEndpointConnectionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, privateEndpointConnectionName string, privateEndpointConnection PrivateEndpointConnection, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateEndpointConnections/{privateEndpointConnectionName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if privateEndpointConnectionName == "" { + return nil, errors.New("parameter privateEndpointConnectionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointConnectionName}", url.PathEscape(privateEndpointConnectionName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, privateEndpointConnection) +} + +// updateHandleResponse handles the Update response. +func (client *PrivateEndpointConnectionsClient) updateHandleResponse(resp *http.Response) (PrivateEndpointConnectionsUpdateResponse, error) { + result := PrivateEndpointConnectionsUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointConnection); err != nil { + return PrivateEndpointConnectionsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *PrivateEndpointConnectionsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_privatelinkresources_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_privatelinkresources_client.go new file mode 100644 index 000000000000..2b32a78d09a1 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_privatelinkresources_client.go @@ -0,0 +1,103 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateLinkResourcesClient contains the methods for the PrivateLinkResources group. +// Don't use this type directly, use NewPrivateLinkResourcesClient() instead. +type PrivateLinkResourcesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateLinkResourcesClient creates a new instance of PrivateLinkResourcesClient with the specified values. +func NewPrivateLinkResourcesClient(con *arm.Connection, subscriptionID string) *PrivateLinkResourcesClient { + return &PrivateLinkResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// ListSupported - Gets a list of all supported private link resource types for the given service. +// If the operation fails it returns the *CloudError error type. +func (client *PrivateLinkResourcesClient) ListSupported(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (PrivateLinkResourcesListSupportedResponse, error) { + req, err := client.listSupportedCreateRequest(ctx, resourceGroupName, searchServiceName, options) + if err != nil { + return PrivateLinkResourcesListSupportedResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateLinkResourcesListSupportedResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateLinkResourcesListSupportedResponse{}, client.listSupportedHandleError(resp) + } + return client.listSupportedHandleResponse(resp) +} + +// listSupportedCreateRequest creates the ListSupported request. +func (client *PrivateLinkResourcesClient) listSupportedCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/privateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listSupportedHandleResponse handles the ListSupported response. +func (client *PrivateLinkResourcesClient) listSupportedHandleResponse(resp *http.Response) (PrivateLinkResourcesListSupportedResponse, error) { + result := PrivateLinkResourcesListSupportedResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateLinkResourcesResult); err != nil { + return PrivateLinkResourcesListSupportedResponse{}, err + } + return result, nil +} + +// listSupportedHandleError handles the ListSupported error response. +func (client *PrivateLinkResourcesClient) listSupportedHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_querykeys_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_querykeys_client.go new file mode 100644 index 000000000000..3e94877a07a4 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_querykeys_client.go @@ -0,0 +1,236 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// QueryKeysClient contains the methods for the QueryKeys group. +// Don't use this type directly, use NewQueryKeysClient() instead. +type QueryKeysClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewQueryKeysClient creates a new instance of QueryKeysClient with the specified values. +func NewQueryKeysClient(con *arm.Connection, subscriptionID string) *QueryKeysClient { + return &QueryKeysClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// Create - Generates a new query key for the specified search service. You can create up to 50 query keys per service. +// If the operation fails it returns the *CloudError error type. +func (client *QueryKeysClient) Create(ctx context.Context, resourceGroupName string, searchServiceName string, name string, options *SearchManagementRequestOptions) (QueryKeysCreateResponse, error) { + req, err := client.createCreateRequest(ctx, resourceGroupName, searchServiceName, name, options) + if err != nil { + return QueryKeysCreateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return QueryKeysCreateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return QueryKeysCreateResponse{}, client.createHandleError(resp) + } + return client.createHandleResponse(resp) +} + +// createCreateRequest creates the Create request. +func (client *QueryKeysClient) createCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, name string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/createQueryKey/{name}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if name == "" { + return nil, errors.New("parameter name cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{name}", url.PathEscape(name)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// createHandleResponse handles the Create response. +func (client *QueryKeysClient) createHandleResponse(resp *http.Response) (QueryKeysCreateResponse, error) { + result := QueryKeysCreateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.QueryKey); err != nil { + return QueryKeysCreateResponse{}, err + } + return result, nil +} + +// createHandleError handles the Create error response. +func (client *QueryKeysClient) createHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes the specified query key. Unlike admin keys, query keys are not regenerated. The process for regenerating a query key is to delete and +// then recreate it. +// If the operation fails it returns the *CloudError error type. +func (client *QueryKeysClient) Delete(ctx context.Context, resourceGroupName string, searchServiceName string, key string, options *SearchManagementRequestOptions) (QueryKeysDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, searchServiceName, key, options) + if err != nil { + return QueryKeysDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return QueryKeysDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent, http.StatusNotFound) { + return QueryKeysDeleteResponse{}, client.deleteHandleError(resp) + } + return QueryKeysDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *QueryKeysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, key string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/deleteQueryKey/{key}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if key == "" { + return nil, errors.New("parameter key cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{key}", url.PathEscape(key)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *QueryKeysClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySearchService - Returns the list of query API keys for the given Azure Cognitive Search service. +// If the operation fails it returns the *CloudError error type. +func (client *QueryKeysClient) ListBySearchService(resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) *QueryKeysListBySearchServicePager { + return &QueryKeysListBySearchServicePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySearchServiceCreateRequest(ctx, resourceGroupName, searchServiceName, options) + }, + advancer: func(ctx context.Context, resp QueryKeysListBySearchServiceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ListQueryKeysResult.NextLink) + }, + } +} + +// listBySearchServiceCreateRequest creates the ListBySearchService request. +func (client *QueryKeysClient) listBySearchServiceCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/listQueryKeys" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySearchServiceHandleResponse handles the ListBySearchService response. +func (client *QueryKeysClient) listBySearchServiceHandleResponse(resp *http.Response) (QueryKeysListBySearchServiceResponse, error) { + result := QueryKeysListBySearchServiceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ListQueryKeysResult); err != nil { + return QueryKeysListBySearchServiceResponse{}, err + } + return result, nil +} + +// listBySearchServiceHandleError handles the ListBySearchService error response. +func (client *QueryKeysClient) listBySearchServiceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_response_types.go b/sdk/resourcemanager/search/armsearch/zz_generated_response_types.go new file mode 100644 index 000000000000..1520ec008e8f --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_response_types.go @@ -0,0 +1,377 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// AdminKeysGetResponse contains the response from method AdminKeys.Get. +type AdminKeysGetResponse struct { + AdminKeysGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AdminKeysGetResult contains the result from method AdminKeys.Get. +type AdminKeysGetResult struct { + AdminKeyResult +} + +// AdminKeysRegenerateResponse contains the response from method AdminKeys.Regenerate. +type AdminKeysRegenerateResponse struct { + AdminKeysRegenerateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// AdminKeysRegenerateResult contains the result from method AdminKeys.Regenerate. +type AdminKeysRegenerateResult struct { + AdminKeyResult +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// PrivateEndpointConnectionsDeleteResponse contains the response from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeleteResponse struct { + PrivateEndpointConnectionsDeleteResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsDeleteResult contains the result from method PrivateEndpointConnections.Delete. +type PrivateEndpointConnectionsDeleteResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsGetResponse contains the response from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResponse struct { + PrivateEndpointConnectionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsGetResult contains the result from method PrivateEndpointConnections.Get. +type PrivateEndpointConnectionsGetResult struct { + PrivateEndpointConnection +} + +// PrivateEndpointConnectionsListByServiceResponse contains the response from method PrivateEndpointConnections.ListByService. +type PrivateEndpointConnectionsListByServiceResponse struct { + PrivateEndpointConnectionsListByServiceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsListByServiceResult contains the result from method PrivateEndpointConnections.ListByService. +type PrivateEndpointConnectionsListByServiceResult struct { + PrivateEndpointConnectionListResult +} + +// PrivateEndpointConnectionsUpdateResponse contains the response from method PrivateEndpointConnections.Update. +type PrivateEndpointConnectionsUpdateResponse struct { + PrivateEndpointConnectionsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointConnectionsUpdateResult contains the result from method PrivateEndpointConnections.Update. +type PrivateEndpointConnectionsUpdateResult struct { + PrivateEndpointConnection +} + +// PrivateLinkResourcesListSupportedResponse contains the response from method PrivateLinkResources.ListSupported. +type PrivateLinkResourcesListSupportedResponse struct { + PrivateLinkResourcesListSupportedResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateLinkResourcesListSupportedResult contains the result from method PrivateLinkResources.ListSupported. +type PrivateLinkResourcesListSupportedResult struct { + PrivateLinkResourcesResult +} + +// QueryKeysCreateResponse contains the response from method QueryKeys.Create. +type QueryKeysCreateResponse struct { + QueryKeysCreateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// QueryKeysCreateResult contains the result from method QueryKeys.Create. +type QueryKeysCreateResult struct { + QueryKey +} + +// QueryKeysDeleteResponse contains the response from method QueryKeys.Delete. +type QueryKeysDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// QueryKeysListBySearchServiceResponse contains the response from method QueryKeys.ListBySearchService. +type QueryKeysListBySearchServiceResponse struct { + QueryKeysListBySearchServiceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// QueryKeysListBySearchServiceResult contains the result from method QueryKeys.ListBySearchService. +type QueryKeysListBySearchServiceResult struct { + ListQueryKeysResult +} + +// ServicesCheckNameAvailabilityResponse contains the response from method Services.CheckNameAvailability. +type ServicesCheckNameAvailabilityResponse struct { + ServicesCheckNameAvailabilityResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesCheckNameAvailabilityResult contains the result from method Services.CheckNameAvailability. +type ServicesCheckNameAvailabilityResult struct { + CheckNameAvailabilityOutput +} + +// ServicesCreateOrUpdatePollerResponse contains the response from method Services.CreateOrUpdate. +type ServicesCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *ServicesCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ServicesCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ServicesCreateOrUpdateResponse, error) { + respType := ServicesCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.SearchService) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ServicesCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *ServicesCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *ServicesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ServicesClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &ServicesCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ServicesCreateOrUpdateResponse contains the response from method Services.CreateOrUpdate. +type ServicesCreateOrUpdateResponse struct { + ServicesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesCreateOrUpdateResult contains the result from method Services.CreateOrUpdate. +type ServicesCreateOrUpdateResult struct { + SearchService +} + +// ServicesDeleteResponse contains the response from method Services.Delete. +type ServicesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesGetResponse contains the response from method Services.Get. +type ServicesGetResponse struct { + ServicesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesGetResult contains the result from method Services.Get. +type ServicesGetResult struct { + SearchService +} + +// ServicesListByResourceGroupResponse contains the response from method Services.ListByResourceGroup. +type ServicesListByResourceGroupResponse struct { + ServicesListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesListByResourceGroupResult contains the result from method Services.ListByResourceGroup. +type ServicesListByResourceGroupResult struct { + SearchServiceListResult +} + +// ServicesListBySubscriptionResponse contains the response from method Services.ListBySubscription. +type ServicesListBySubscriptionResponse struct { + ServicesListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesListBySubscriptionResult contains the result from method Services.ListBySubscription. +type ServicesListBySubscriptionResult struct { + SearchServiceListResult +} + +// ServicesUpdateResponse contains the response from method Services.Update. +type ServicesUpdateResponse struct { + ServicesUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ServicesUpdateResult contains the result from method Services.Update. +type ServicesUpdateResult struct { + SearchService +} + +// SharedPrivateLinkResourcesCreateOrUpdatePollerResponse contains the response from method SharedPrivateLinkResources.CreateOrUpdate. +type SharedPrivateLinkResourcesCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *SharedPrivateLinkResourcesCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SharedPrivateLinkResourcesCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SharedPrivateLinkResourcesCreateOrUpdateResponse, error) { + respType := SharedPrivateLinkResourcesCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.SharedPrivateLinkResource) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SharedPrivateLinkResourcesCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *SharedPrivateLinkResourcesCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *SharedPrivateLinkResourcesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SharedPrivateLinkResourcesClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &SharedPrivateLinkResourcesCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SharedPrivateLinkResourcesCreateOrUpdateResponse contains the response from method SharedPrivateLinkResources.CreateOrUpdate. +type SharedPrivateLinkResourcesCreateOrUpdateResponse struct { + SharedPrivateLinkResourcesCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SharedPrivateLinkResourcesCreateOrUpdateResult contains the result from method SharedPrivateLinkResources.CreateOrUpdate. +type SharedPrivateLinkResourcesCreateOrUpdateResult struct { + SharedPrivateLinkResource +} + +// SharedPrivateLinkResourcesDeletePollerResponse contains the response from method SharedPrivateLinkResources.Delete. +type SharedPrivateLinkResourcesDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *SharedPrivateLinkResourcesDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SharedPrivateLinkResourcesDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SharedPrivateLinkResourcesDeleteResponse, error) { + respType := SharedPrivateLinkResourcesDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SharedPrivateLinkResourcesDeletePollerResponse from the provided client and resume token. +func (l *SharedPrivateLinkResourcesDeletePollerResponse) Resume(ctx context.Context, client *SharedPrivateLinkResourcesClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SharedPrivateLinkResourcesClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &SharedPrivateLinkResourcesDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SharedPrivateLinkResourcesDeleteResponse contains the response from method SharedPrivateLinkResources.Delete. +type SharedPrivateLinkResourcesDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SharedPrivateLinkResourcesGetResponse contains the response from method SharedPrivateLinkResources.Get. +type SharedPrivateLinkResourcesGetResponse struct { + SharedPrivateLinkResourcesGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SharedPrivateLinkResourcesGetResult contains the result from method SharedPrivateLinkResources.Get. +type SharedPrivateLinkResourcesGetResult struct { + SharedPrivateLinkResource +} + +// SharedPrivateLinkResourcesListByServiceResponse contains the response from method SharedPrivateLinkResources.ListByService. +type SharedPrivateLinkResourcesListByServiceResponse struct { + SharedPrivateLinkResourcesListByServiceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SharedPrivateLinkResourcesListByServiceResult contains the result from method SharedPrivateLinkResources.ListByService. +type SharedPrivateLinkResourcesListByServiceResult struct { + SharedPrivateLinkResourceListResult +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_services_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_services_client.go new file mode 100644 index 000000000000..939dcfe3e56c --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_services_client.go @@ -0,0 +1,491 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ServicesClient contains the methods for the Services group. +// Don't use this type directly, use NewServicesClient() instead. +type ServicesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewServicesClient creates a new instance of ServicesClient with the specified values. +func NewServicesClient(con *arm.Connection, subscriptionID string) *ServicesClient { + return &ServicesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CheckNameAvailability - Checks whether or not the given search service name is available for use. Search service names must be globally unique since +// they are part of the service URI (https://.search.windows.net). +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) CheckNameAvailability(ctx context.Context, checkNameAvailabilityInput CheckNameAvailabilityInput, options *SearchManagementRequestOptions) (ServicesCheckNameAvailabilityResponse, error) { + req, err := client.checkNameAvailabilityCreateRequest(ctx, checkNameAvailabilityInput, options) + if err != nil { + return ServicesCheckNameAvailabilityResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ServicesCheckNameAvailabilityResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ServicesCheckNameAvailabilityResponse{}, client.checkNameAvailabilityHandleError(resp) + } + return client.checkNameAvailabilityHandleResponse(resp) +} + +// checkNameAvailabilityCreateRequest creates the CheckNameAvailability request. +func (client *ServicesClient) checkNameAvailabilityCreateRequest(ctx context.Context, checkNameAvailabilityInput CheckNameAvailabilityInput, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Search/checkNameAvailability" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, checkNameAvailabilityInput) +} + +// checkNameAvailabilityHandleResponse handles the CheckNameAvailability response. +func (client *ServicesClient) checkNameAvailabilityHandleResponse(resp *http.Response) (ServicesCheckNameAvailabilityResponse, error) { + result := ServicesCheckNameAvailabilityResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.CheckNameAvailabilityOutput); err != nil { + return ServicesCheckNameAvailabilityResponse{}, err + } + return result, nil +} + +// checkNameAvailabilityHandleError handles the CheckNameAvailability error response. +func (client *ServicesClient) checkNameAvailabilityHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginCreateOrUpdate - Creates or updates a search service in the given resource group. If the search service already exists, all properties will be updated +// with the given values. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, service SearchService, options *SearchManagementRequestOptions) (ServicesCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, searchServiceName, service, options) + if err != nil { + return ServicesCreateOrUpdatePollerResponse{}, err + } + result := ServicesCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ServicesClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return ServicesCreateOrUpdatePollerResponse{}, err + } + result.Poller = &ServicesCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Creates or updates a search service in the given resource group. If the search service already exists, all properties will be updated +// with the given values. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) createOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, service SearchService, options *SearchManagementRequestOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, searchServiceName, service, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ServicesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, service SearchService, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, service) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *ServicesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a search service in the given resource group, along with its associated resources. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) Delete(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (ServicesDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, searchServiceName, options) + if err != nil { + return ServicesDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ServicesDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent, http.StatusNotFound) { + return ServicesDeleteResponse{}, client.deleteHandleError(resp) + } + return ServicesDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ServicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ServicesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the search service with the given name in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) Get(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (ServicesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, searchServiceName, options) + if err != nil { + return ServicesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ServicesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ServicesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *ServicesClient) getCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ServicesClient) getHandleResponse(resp *http.Response) (ServicesGetResponse, error) { + result := ServicesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SearchService); err != nil { + return ServicesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *ServicesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Gets a list of all search services in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) ListByResourceGroup(resourceGroupName string, options *SearchManagementRequestOptions) *ServicesListByResourceGroupPager { + return &ServicesListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp ServicesListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SearchServiceListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ServicesClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ServicesClient) listByResourceGroupHandleResponse(resp *http.Response) (ServicesListByResourceGroupResponse, error) { + result := ServicesListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SearchServiceListResult); err != nil { + return ServicesListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *ServicesClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscription - Gets a list of all search services in the given subscription. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) ListBySubscription(options *SearchManagementRequestOptions) *ServicesListBySubscriptionPager { + return &ServicesListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp ServicesListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SearchServiceListResult.NextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ServicesClient) listBySubscriptionCreateRequest(ctx context.Context, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.Search/searchServices" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ServicesClient) listBySubscriptionHandleResponse(resp *http.Response) (ServicesListBySubscriptionResponse, error) { + result := ServicesListBySubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SearchServiceListResult); err != nil { + return ServicesListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *ServicesClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *ServicesClient) Update(ctx context.Context, resourceGroupName string, searchServiceName string, service SearchServiceUpdate, options *SearchManagementRequestOptions) (ServicesUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, searchServiceName, service, options) + if err != nil { + return ServicesUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ServicesUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ServicesUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *ServicesClient) updateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, service SearchServiceUpdate, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, service) +} + +// updateHandleResponse handles the Update response. +func (client *ServicesClient) updateHandleResponse(resp *http.Response) (ServicesUpdateResponse, error) { + result := ServicesUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SearchService); err != nil { + return ServicesUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *ServicesClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/search/armsearch/zz_generated_sharedprivatelinkresources_client.go b/sdk/resourcemanager/search/armsearch/zz_generated_sharedprivatelinkresources_client.go new file mode 100644 index 000000000000..f24be6af5a24 --- /dev/null +++ b/sdk/resourcemanager/search/armsearch/zz_generated_sharedprivatelinkresources_client.go @@ -0,0 +1,339 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armsearch + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// SharedPrivateLinkResourcesClient contains the methods for the SharedPrivateLinkResources group. +// Don't use this type directly, use NewSharedPrivateLinkResourcesClient() instead. +type SharedPrivateLinkResourcesClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewSharedPrivateLinkResourcesClient creates a new instance of SharedPrivateLinkResourcesClient with the specified values. +func NewSharedPrivateLinkResourcesClient(con *arm.Connection, subscriptionID string) *SharedPrivateLinkResourcesClient { + return &SharedPrivateLinkResourcesClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrUpdate - Initiates the creation or update of a shared private link resource managed by the search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, sharedPrivateLinkResource SharedPrivateLinkResource, options *SearchManagementRequestOptions) (SharedPrivateLinkResourcesCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, sharedPrivateLinkResource, options) + if err != nil { + return SharedPrivateLinkResourcesCreateOrUpdatePollerResponse{}, err + } + result := SharedPrivateLinkResourcesCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SharedPrivateLinkResourcesClient.CreateOrUpdate", "azure-async-operation", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return SharedPrivateLinkResourcesCreateOrUpdatePollerResponse{}, err + } + result.Poller = &SharedPrivateLinkResourcesCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Initiates the creation or update of a shared private link resource managed by the search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) createOrUpdate(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, sharedPrivateLinkResource SharedPrivateLinkResource, options *SearchManagementRequestOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, sharedPrivateLinkResource, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *SharedPrivateLinkResourcesClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, sharedPrivateLinkResource SharedPrivateLinkResource, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, sharedPrivateLinkResource) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *SharedPrivateLinkResourcesClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Initiates the deletion of the shared private link resource from the search service. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) BeginDelete(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, options *SearchManagementRequestOptions) (SharedPrivateLinkResourcesDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options) + if err != nil { + return SharedPrivateLinkResourcesDeletePollerResponse{}, err + } + result := SharedPrivateLinkResourcesDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SharedPrivateLinkResourcesClient.Delete", "azure-async-operation", resp, client.pl, client.deleteHandleError) + if err != nil { + return SharedPrivateLinkResourcesDeletePollerResponse{}, err + } + result.Poller = &SharedPrivateLinkResourcesDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Initiates the deletion of the shared private link resource from the search service. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) deleteOperation(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, options *SearchManagementRequestOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusAccepted, http.StatusNoContent, http.StatusNotFound) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *SharedPrivateLinkResourcesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *SharedPrivateLinkResourcesClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets the details of the shared private link resource managed by the search service in the given resource group. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) Get(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, options *SearchManagementRequestOptions) (SharedPrivateLinkResourcesGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, searchServiceName, sharedPrivateLinkResourceName, options) + if err != nil { + return SharedPrivateLinkResourcesGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SharedPrivateLinkResourcesGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SharedPrivateLinkResourcesGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *SharedPrivateLinkResourcesClient) getCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, sharedPrivateLinkResourceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources/{sharedPrivateLinkResourceName}" + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + if sharedPrivateLinkResourceName == "" { + return nil, errors.New("parameter sharedPrivateLinkResourceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{sharedPrivateLinkResourceName}", url.PathEscape(sharedPrivateLinkResourceName)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *SharedPrivateLinkResourcesClient) getHandleResponse(resp *http.Response) (SharedPrivateLinkResourcesGetResponse, error) { + result := SharedPrivateLinkResourcesGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedPrivateLinkResource); err != nil { + return SharedPrivateLinkResourcesGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *SharedPrivateLinkResourcesClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByService - Gets a list of all shared private link resources managed by the given service. +// If the operation fails it returns the *CloudError error type. +func (client *SharedPrivateLinkResourcesClient) ListByService(resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) *SharedPrivateLinkResourcesListByServicePager { + return &SharedPrivateLinkResourcesListByServicePager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByServiceCreateRequest(ctx, resourceGroupName, searchServiceName, options) + }, + advancer: func(ctx context.Context, resp SharedPrivateLinkResourcesListByServiceResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.SharedPrivateLinkResourceListResult.NextLink) + }, + } +} + +// listByServiceCreateRequest creates the ListByService request. +func (client *SharedPrivateLinkResourcesClient) listByServiceCreateRequest(ctx context.Context, resourceGroupName string, searchServiceName string, options *SearchManagementRequestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{searchServiceName}/sharedPrivateLinkResources" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if searchServiceName == "" { + return nil, errors.New("parameter searchServiceName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{searchServiceName}", url.PathEscape(searchServiceName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-08-01") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.ClientRequestID != nil { + req.Raw().Header.Set("x-ms-client-request-id", *options.ClientRequestID) + } + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByServiceHandleResponse handles the ListByService response. +func (client *SharedPrivateLinkResourcesClient) listByServiceHandleResponse(resp *http.Response) (SharedPrivateLinkResourcesListByServiceResponse, error) { + result := SharedPrivateLinkResourcesListByServiceResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SharedPrivateLinkResourceListResult); err != nil { + return SharedPrivateLinkResourcesListByServiceResponse{}, err + } + return result, nil +} + +// listByServiceHandleError handles the ListByService error response. +func (client *SharedPrivateLinkResourcesClient) listByServiceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := CloudError{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/security/armsecurity/CHANGELOG.md b/sdk/resourcemanager/security/armsecurity/CHANGELOG.md index 6a1d73d570b6..34f86d5bb408 100644 --- a/sdk/resourcemanager/security/armsecurity/CHANGELOG.md +++ b/sdk/resourcemanager/security/armsecurity/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-15) - Initial preview release. diff --git a/sdk/resourcemanager/security/armsecurity/autorest.md b/sdk/resourcemanager/security/armsecurity/autorest.md index c964442c4ba9..88d1ae198fe8 100644 --- a/sdk/resourcemanager/security/armsecurity/autorest.md +++ b/sdk/resourcemanager/security/armsecurity/autorest.md @@ -9,7 +9,7 @@ require: - https://github.com/Azure/azure-rest-api-specs/blob/bd64220293a403f70ae8beebd56fb86951007acf/specification/security/resource-manager/readme.md - https://github.com/Azure/azure-rest-api-specs/blob/bd64220293a403f70ae8beebd56fb86951007acf/specification/security/resource-manager/readme.go.md license-header: MICROSOFT_MIT_NO_VERSION -module-version: 0.1.0 +module-version: 0.1.1 modelerfour: lenient-model-deduplication: true ``` \ No newline at end of file diff --git a/sdk/resourcemanager/security/armsecurity/zz_generated_constants.go b/sdk/resourcemanager/security/armsecurity/zz_generated_constants.go index d3c851cf9dba..0c6b97ef99bd 100644 --- a/sdk/resourcemanager/security/armsecurity/zz_generated_constants.go +++ b/sdk/resourcemanager/security/armsecurity/zz_generated_constants.go @@ -10,7 +10,7 @@ package armsecurity const ( module = "armsecurity" - version = "v0.1.0" + version = "v0.1.1" ) // AADConnectivityState - The connectivity state of the external AAD solution diff --git a/sdk/resourcemanager/servicefabric/armservicefabric/CHANGELOG.md b/sdk/resourcemanager/servicefabric/armservicefabric/CHANGELOG.md index 1f7250ae5937..2276a757fdd8 100644 --- a/sdk/resourcemanager/servicefabric/armservicefabric/CHANGELOG.md +++ b/sdk/resourcemanager/servicefabric/armservicefabric/CHANGELOG.md @@ -1,5 +1,15 @@ # Release History +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + ## 0.1.0 (2021-10-20) - Initial preview release. diff --git a/sdk/resourcemanager/servicefabric/armservicefabric/zz_generated_constants.go b/sdk/resourcemanager/servicefabric/armservicefabric/zz_generated_constants.go index de55a9128660..186ceda7cdca 100644 --- a/sdk/resourcemanager/servicefabric/armservicefabric/zz_generated_constants.go +++ b/sdk/resourcemanager/servicefabric/armservicefabric/zz_generated_constants.go @@ -10,7 +10,7 @@ package armservicefabric const ( module = "armservicefabric" - version = "v0.1.0" + version = "v0.1.1" ) // AddOnFeatures - Available cluster add-on features diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/CHANGELOG.md b/sdk/resourcemanager/streamanalytics/armstreamanalytics/CHANGELOG.md new file mode 100644 index 000000000000..e4f3d9f035c1 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/CHANGELOG.md @@ -0,0 +1,15 @@ +# Release History + +## 0.1.1 (Unreleased) + +### Features Added + +### Breaking Changes + +### Bugs Fixed + +### Other Changes + +## 0.1.0 (2021-10-26) + +- Initial preview release. diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/LICENSE.txt b/sdk/resourcemanager/streamanalytics/armstreamanalytics/LICENSE.txt new file mode 100644 index 000000000000..dc0c2ffb3dc1 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/LICENSE.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Microsoft Corporation. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/README.md b/sdk/resourcemanager/streamanalytics/armstreamanalytics/README.md new file mode 100644 index 000000000000..617f623bd192 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/README.md @@ -0,0 +1,76 @@ +# Azure Stream Analytics Module for Go + +[![PkgGoDev](https://pkg.go.dev/badge/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/streamanalytics/armstreamanalytics)](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/streamanalytics/armstreamanalytics) + +The `armstreamanalytics` module provides operations for working with Azure Stream Analytics. + +[Source code](https://github.com/Azure/azure-sdk-for-go/tree/main/sdk/resourcemanager/streamanalytics/armstreamanalytics) + +# Getting started + +## Prerequisites + +- an [Azure subscription](https://azure.microsoft.com/free/) +- Go 1.13 or above + +## Install the package + +This project uses [Go modules](https://github.com/golang/go/wiki/Modules) for versioning and dependency management. + +Install the Azure Stream Analytics module: + +```sh +go get github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/streamanalytics/armstreamanalytics +``` + +## Authorization + +When creating a client, you will need to provide a credential for authenticating with Azure Stream Analytics. The `azidentity` module provides facilities for various ways of authenticating with Azure including client/secret, certificate, managed identity, and more. + +```go +cred, err := azidentity.NewDefaultAzureCredential(nil) +``` + +For more information on authentication, please see the documentation for `azidentity` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azidentity). + +## Connecting to Azure Stream Analytics + +Once you have a credential, create a connection to the desired ARM endpoint. The `github.com/Azure/azure-sdk-for-go/sdk/azcore/arm` package provides facilities for connecting with ARM endpoints including public and sovereign clouds as well as Azure Stack. + +```go +con := arm.NewDefaultConnection(cred, nil) +``` + +For more information on ARM connections, please see the documentation for `azcore` at [pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore](https://pkg.go.dev/github.com/Azure/azure-sdk-for-go/sdk/azcore). + +## Clients + +Azure Stream Analytics modules consist of one or more clients. A client groups a set of related APIs, providing access to its functionality within the specified subscription. Create one or more clients to access the APIs you require using your `arm.Connection`. + +```go +client := armstreamanalytics.NewInputsClient(con, "") +``` + +## Provide Feedback + +If you encounter bugs or have suggestions, please +[open an issue](https://github.com/Azure/azure-sdk-for-go/issues) and assign the `Stream Analytics` label. + +# Contributing + +This project welcomes contributions and suggestions. Most contributions require +you to agree to a Contributor License Agreement (CLA) declaring that you have +the right to, and actually do, grant us the rights to use your contribution. +For details, visit [https://cla.microsoft.com](https://cla.microsoft.com). + +When you submit a pull request, a CLA-bot will automatically determine whether +you need to provide a CLA and decorate the PR appropriately (e.g., label, +comment). Simply follow the instructions provided by the bot. You will only +need to do this once across all repos using our CLA. + +This project has adopted the +[Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). +For more information, see the +[Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any +additional questions or comments. \ No newline at end of file diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/autorest.md b/sdk/resourcemanager/streamanalytics/armstreamanalytics/autorest.md new file mode 100644 index 000000000000..b318cda0e9d2 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/autorest.md @@ -0,0 +1,12 @@ +### AutoRest Configuration + +> see https://aka.ms/autorest + +``` yaml +azure-arm: true +require: +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/streamanalytics/resource-manager/readme.md +- https://github.com/Azure/azure-rest-api-specs/blob/3c16aae50c7110e1aad241ac93995621d4093d46/specification/streamanalytics/resource-manager/readme.go.md +license-header: MICROSOFT_MIT_NO_VERSION +module-version: 0.1.0 +``` \ No newline at end of file diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/build.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/build.go new file mode 100644 index 000000000000..ad0aa60360a4 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/build.go @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file enables 'go generate' to regenerate this specific SDK +//go:generate pwsh.exe ../../../../eng/scripts/build.ps1 -skipBuild -cleanGenerated -format -tidy -generate resourcemanager/streamanalytics/armstreamanalytics + +package armstreamanalytics diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/ci.yml b/sdk/resourcemanager/streamanalytics/armstreamanalytics/ci.yml new file mode 100644 index 000000000000..51e23c7f0f85 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/ci.yml @@ -0,0 +1,27 @@ +# NOTE: Please refer to https://aka.ms/azsdk/engsys/ci-yaml before editing this file. +trigger: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/streamanalytics/armstreamanalytics/ + +pr: + branches: + include: + - main + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/resourcemanager/streamanalytics/armstreamanalytics/ + +stages: +- template: /eng/pipelines/templates/jobs/archetype-sdk-client.yml + parameters: + ServiceDirectory: 'resourcemanager/streamanalytics/armstreamanalytics' diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.mod b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.mod new file mode 100644 index 000000000000..1ddfef90c162 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.mod @@ -0,0 +1,8 @@ +module github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/streamanalytics/armstreamanalytics + +go 1.16 + +require ( + github.com/Azure/azure-sdk-for-go v58.2.0+incompatible + github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 +) diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.sum b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.sum new file mode 100644 index 000000000000..c8ff7a2143ad --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go.sum @@ -0,0 +1,30 @@ +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible h1:iCb2tuoEm3N7ZpUDOvu1Yxl1B3iOVDmaD6weaRuIPzs= +github.com/Azure/azure-sdk-for-go v58.2.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0 h1:lhSJz9RMbJcTgxifR1hUNJnn6CNYtbgEDtQV22/9RBA= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0 h1:v9p9TfTbf7AwNb5NYQt7hI41IfPoLFiFkLtb+bmGjT0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b h1:k+E048sYJHyVnsr1GDrRZWQ32D2C7lWs9JRc0bel53A= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6 h1:aRYxNxv6iGQlyVaZmk6ZgYEDa+Jg18DxebPSrd6bg1M= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/go_mod_tidy_hack.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go_mod_tidy_hack.go new file mode 100644 index 000000000000..5cf900630852 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/go_mod_tidy_hack.go @@ -0,0 +1,13 @@ +//go:build modhack +// +build modhack + +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +// This file, and the github.com/Azure/azure-sdk-for-go import, won't actually become part of +// the resultant binary. + +package armstreamanalytics + +// Necessary for safely adding multi-module repo. See: https://github.com/golang/go/wiki/Modules#is-it-possible-to-add-a-module-to-a-multi-module-repository +import _ "github.com/Azure/azure-sdk-for-go" diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_clusters_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_clusters_client.go new file mode 100644 index 000000000000..a4f06cd922d1 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_clusters_client.go @@ -0,0 +1,514 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ClustersClient contains the methods for the Clusters group. +// Don't use this type directly, use NewClustersClient() instead. +type ClustersClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewClustersClient creates a new instance of ClustersClient with the specified values. +func NewClustersClient(con *arm.Connection, subscriptionID string) *ClustersClient { + return &ClustersClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrUpdate - Creates a Stream Analytics Cluster or replaces an already existing cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) BeginCreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginCreateOrUpdateOptions) (ClustersCreateOrUpdatePollerResponse, error) { + resp, err := client.createOrUpdate(ctx, resourceGroupName, clusterName, cluster, options) + if err != nil { + return ClustersCreateOrUpdatePollerResponse{}, err + } + result := ClustersCreateOrUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ClustersClient.CreateOrUpdate", "", resp, client.pl, client.createOrUpdateHandleError) + if err != nil { + return ClustersCreateOrUpdatePollerResponse{}, err + } + result.Poller = &ClustersCreateOrUpdatePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrUpdate - Creates a Stream Analytics Cluster or replaces an already existing cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) createOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginCreateOrUpdateOptions) (*http.Response, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, clusterName, cluster, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrUpdateHandleError(resp) + } + return resp, nil +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *ClustersClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, cluster) +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *ClustersClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes the specified cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) BeginDelete(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersBeginDeleteOptions) (ClustersDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, clusterName, options) + if err != nil { + return ClustersDeletePollerResponse{}, err + } + result := ClustersDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ClustersClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return ClustersDeletePollerResponse{}, err + } + result.Poller = &ClustersDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes the specified cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) deleteOperation(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, clusterName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *ClustersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *ClustersClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets information about the specified cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) Get(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersGetOptions) (ClustersGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, clusterName, options) + if err != nil { + return ClustersGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return ClustersGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return ClustersGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *ClustersClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *ClustersClient) getHandleResponse(resp *http.Response) (ClustersGetResponse, error) { + result := ClustersGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Cluster); err != nil { + return ClustersGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *ClustersClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Lists all of the clusters in the given resource group. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) ListByResourceGroup(resourceGroupName string, options *ClustersListByResourceGroupOptions) *ClustersListByResourceGroupPager { + return &ClustersListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp ClustersListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ClusterListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *ClustersClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *ClustersListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *ClustersClient) listByResourceGroupHandleResponse(resp *http.Response) (ClustersListByResourceGroupResponse, error) { + result := ClustersListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ClusterListResult); err != nil { + return ClustersListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *ClustersClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListBySubscription - Lists all of the clusters in the given subscription. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) ListBySubscription(options *ClustersListBySubscriptionOptions) *ClustersListBySubscriptionPager { + return &ClustersListBySubscriptionPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listBySubscriptionCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp ClustersListBySubscriptionResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ClusterListResult.NextLink) + }, + } +} + +// listBySubscriptionCreateRequest creates the ListBySubscription request. +func (client *ClustersClient) listBySubscriptionCreateRequest(ctx context.Context, options *ClustersListBySubscriptionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/clusters" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listBySubscriptionHandleResponse handles the ListBySubscription response. +func (client *ClustersClient) listBySubscriptionHandleResponse(resp *http.Response) (ClustersListBySubscriptionResponse, error) { + result := ClustersListBySubscriptionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ClusterListResult); err != nil { + return ClustersListBySubscriptionResponse{}, err + } + return result, nil +} + +// listBySubscriptionHandleError handles the ListBySubscription error response. +func (client *ClustersClient) listBySubscriptionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListStreamingJobs - Lists all of the streaming jobs in the given cluster. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) ListStreamingJobs(resourceGroupName string, clusterName string, options *ClustersListStreamingJobsOptions) *ClustersListStreamingJobsPager { + return &ClustersListStreamingJobsPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listStreamingJobsCreateRequest(ctx, resourceGroupName, clusterName, options) + }, + advancer: func(ctx context.Context, resp ClustersListStreamingJobsResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.ClusterJobListResult.NextLink) + }, + } +} + +// listStreamingJobsCreateRequest creates the ListStreamingJobs request. +func (client *ClustersClient) listStreamingJobsCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *ClustersListStreamingJobsOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}/listStreamingJobs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listStreamingJobsHandleResponse handles the ListStreamingJobs response. +func (client *ClustersClient) listStreamingJobsHandleResponse(resp *http.Response) (ClustersListStreamingJobsResponse, error) { + result := ClustersListStreamingJobsResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.ClusterJobListResult); err != nil { + return ClustersListStreamingJobsResponse{}, err + } + return result, nil +} + +// listStreamingJobsHandleError handles the ListStreamingJobs error response. +func (client *ClustersClient) listStreamingJobsHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginUpdate - Updates an existing cluster. This can be used to partially update (ie. update one or two properties) a cluster without affecting the rest +// of the cluster definition. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) BeginUpdate(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginUpdateOptions) (ClustersUpdatePollerResponse, error) { + resp, err := client.update(ctx, resourceGroupName, clusterName, cluster, options) + if err != nil { + return ClustersUpdatePollerResponse{}, err + } + result := ClustersUpdatePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("ClustersClient.Update", "", resp, client.pl, client.updateHandleError) + if err != nil { + return ClustersUpdatePollerResponse{}, err + } + result.Poller = &ClustersUpdatePoller{ + pt: pt, + } + return result, nil +} + +// Update - Updates an existing cluster. This can be used to partially update (ie. update one or two properties) a cluster without affecting the rest of +// the cluster definition. +// If the operation fails it returns the *Error error type. +func (client *ClustersClient) update(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginUpdateOptions) (*http.Response, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, clusterName, cluster, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.updateHandleError(resp) + } + return resp, nil +} + +// updateCreateRequest creates the Update request. +func (client *ClustersClient) updateCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, cluster Cluster, options *ClustersBeginUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, cluster) +} + +// updateHandleError handles the Update error response. +func (client *ClustersClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_constants.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_constants.go new file mode 100644 index 000000000000..22c3a89ace18 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_constants.go @@ -0,0 +1,435 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +const ( + module = "armstreamanalytics" + version = "v0.1.1" +) + +// AuthenticationMode - Authentication Mode. Valid modes are ConnectionString, Msi and 'UserToken'. +type AuthenticationMode string + +const ( + AuthenticationModeConnectionString AuthenticationMode = "ConnectionString" + AuthenticationModeMsi AuthenticationMode = "Msi" + AuthenticationModeUserToken AuthenticationMode = "UserToken" +) + +// PossibleAuthenticationModeValues returns the possible values for the AuthenticationMode const type. +func PossibleAuthenticationModeValues() []AuthenticationMode { + return []AuthenticationMode{ + AuthenticationModeConnectionString, + AuthenticationModeMsi, + AuthenticationModeUserToken, + } +} + +// ToPtr returns a *AuthenticationMode pointing to the current value. +func (c AuthenticationMode) ToPtr() *AuthenticationMode { + return &c +} + +// ClusterProvisioningState - The status of the cluster provisioning. The three terminal states are: Succeeded, Failed and Canceled +type ClusterProvisioningState string + +const ( + // ClusterProvisioningStateCanceled - The cluster provisioning was canceled. + ClusterProvisioningStateCanceled ClusterProvisioningState = "Canceled" + // ClusterProvisioningStateFailed - The cluster provisioning failed. + ClusterProvisioningStateFailed ClusterProvisioningState = "Failed" + // ClusterProvisioningStateInProgress - The cluster provisioning was inprogress. + ClusterProvisioningStateInProgress ClusterProvisioningState = "InProgress" + // ClusterProvisioningStateSucceeded - The cluster provisioning succeeded. + ClusterProvisioningStateSucceeded ClusterProvisioningState = "Succeeded" +) + +// PossibleClusterProvisioningStateValues returns the possible values for the ClusterProvisioningState const type. +func PossibleClusterProvisioningStateValues() []ClusterProvisioningState { + return []ClusterProvisioningState{ + ClusterProvisioningStateCanceled, + ClusterProvisioningStateFailed, + ClusterProvisioningStateInProgress, + ClusterProvisioningStateSucceeded, + } +} + +// ToPtr returns a *ClusterProvisioningState pointing to the current value. +func (c ClusterProvisioningState) ToPtr() *ClusterProvisioningState { + return &c +} + +// ClusterSKUName - Specifies the SKU name of the cluster. Required on PUT (CreateOrUpdate) requests. +type ClusterSKUName string + +const ( + // ClusterSKUNameDefault - The default SKU. + ClusterSKUNameDefault ClusterSKUName = "Default" +) + +// PossibleClusterSKUNameValues returns the possible values for the ClusterSKUName const type. +func PossibleClusterSKUNameValues() []ClusterSKUName { + return []ClusterSKUName{ + ClusterSKUNameDefault, + } +} + +// ToPtr returns a *ClusterSKUName pointing to the current value. +func (c ClusterSKUName) ToPtr() *ClusterSKUName { + return &c +} + +// CompatibilityLevel - Controls certain runtime behaviors of the streaming job. +type CompatibilityLevel string + +const ( + CompatibilityLevelOne0 CompatibilityLevel = "1.0" +) + +// PossibleCompatibilityLevelValues returns the possible values for the CompatibilityLevel const type. +func PossibleCompatibilityLevelValues() []CompatibilityLevel { + return []CompatibilityLevel{ + CompatibilityLevelOne0, + } +} + +// ToPtr returns a *CompatibilityLevel pointing to the current value. +func (c CompatibilityLevel) ToPtr() *CompatibilityLevel { + return &c +} + +// ContentStoragePolicy - Valid values are JobStorageAccount and SystemAccount. If set to JobStorageAccount, this requires the user to also specify jobStorageAccount +// property. . +type ContentStoragePolicy string + +const ( + ContentStoragePolicyJobStorageAccount ContentStoragePolicy = "JobStorageAccount" + ContentStoragePolicySystemAccount ContentStoragePolicy = "SystemAccount" +) + +// PossibleContentStoragePolicyValues returns the possible values for the ContentStoragePolicy const type. +func PossibleContentStoragePolicyValues() []ContentStoragePolicy { + return []ContentStoragePolicy{ + ContentStoragePolicyJobStorageAccount, + ContentStoragePolicySystemAccount, + } +} + +// ToPtr returns a *ContentStoragePolicy pointing to the current value. +func (c ContentStoragePolicy) ToPtr() *ContentStoragePolicy { + return &c +} + +// Encoding - Specifies the encoding of the incoming data in the case of input and the encoding of outgoing data in the case of output. +type Encoding string + +const ( + EncodingUTF8 Encoding = "UTF8" +) + +// PossibleEncodingValues returns the possible values for the Encoding const type. +func PossibleEncodingValues() []Encoding { + return []Encoding{ + EncodingUTF8, + } +} + +// ToPtr returns a *Encoding pointing to the current value. +func (c Encoding) ToPtr() *Encoding { + return &c +} + +// EventSerializationType - Indicates the type of serialization that the input or output uses. Required on PUT (CreateOrReplace) requests. +type EventSerializationType string + +const ( + EventSerializationTypeAvro EventSerializationType = "Avro" + EventSerializationTypeCSV EventSerializationType = "Csv" + EventSerializationTypeCustomClr EventSerializationType = "CustomClr" + EventSerializationTypeJSON EventSerializationType = "Json" + EventSerializationTypeParquet EventSerializationType = "Parquet" +) + +// PossibleEventSerializationTypeValues returns the possible values for the EventSerializationType const type. +func PossibleEventSerializationTypeValues() []EventSerializationType { + return []EventSerializationType{ + EventSerializationTypeAvro, + EventSerializationTypeCSV, + EventSerializationTypeCustomClr, + EventSerializationTypeJSON, + EventSerializationTypeParquet, + } +} + +// ToPtr returns a *EventSerializationType pointing to the current value. +func (c EventSerializationType) ToPtr() *EventSerializationType { + return &c +} + +// EventsOutOfOrderPolicy - Indicates the policy to apply to events that arrive out of order in the input event stream. +type EventsOutOfOrderPolicy string + +const ( + EventsOutOfOrderPolicyAdjust EventsOutOfOrderPolicy = "Adjust" + EventsOutOfOrderPolicyDrop EventsOutOfOrderPolicy = "Drop" +) + +// PossibleEventsOutOfOrderPolicyValues returns the possible values for the EventsOutOfOrderPolicy const type. +func PossibleEventsOutOfOrderPolicyValues() []EventsOutOfOrderPolicy { + return []EventsOutOfOrderPolicy{ + EventsOutOfOrderPolicyAdjust, + EventsOutOfOrderPolicyDrop, + } +} + +// ToPtr returns a *EventsOutOfOrderPolicy pointing to the current value. +func (c EventsOutOfOrderPolicy) ToPtr() *EventsOutOfOrderPolicy { + return &c +} + +// JSONOutputSerializationFormat - Specifies the format of the JSON the output will be written in. The currently supported values are 'lineSeparated' indicating +// the output will be formatted by having each JSON object separated by a new +// line and 'array' indicating the output will be formatted as an array of JSON objects. +type JSONOutputSerializationFormat string + +const ( + JSONOutputSerializationFormatArray JSONOutputSerializationFormat = "Array" + JSONOutputSerializationFormatLineSeparated JSONOutputSerializationFormat = "LineSeparated" +) + +// PossibleJSONOutputSerializationFormatValues returns the possible values for the JSONOutputSerializationFormat const type. +func PossibleJSONOutputSerializationFormatValues() []JSONOutputSerializationFormat { + return []JSONOutputSerializationFormat{ + JSONOutputSerializationFormatArray, + JSONOutputSerializationFormatLineSeparated, + } +} + +// ToPtr returns a *JSONOutputSerializationFormat pointing to the current value. +func (c JSONOutputSerializationFormat) ToPtr() *JSONOutputSerializationFormat { + return &c +} + +// JobState - The current execution state of the streaming job. +type JobState string + +const ( + // JobStateCreated - The job is currently in the Created state. + JobStateCreated JobState = "Created" + // JobStateDegraded - The job is currently in the Degraded state. + JobStateDegraded JobState = "Degraded" + // JobStateDeleting - The job is currently in the Deleting state. + JobStateDeleting JobState = "Deleting" + // JobStateFailed - The job is currently in the Failed state. + JobStateFailed JobState = "Failed" + // JobStateRestarting - The job is currently in the Restarting state. + JobStateRestarting JobState = "Restarting" + // JobStateRunning - The job is currently in the Running state. + JobStateRunning JobState = "Running" + // JobStateScaling - The job is currently in the Scaling state. + JobStateScaling JobState = "Scaling" + // JobStateStarting - The job is currently in the Starting state. + JobStateStarting JobState = "Starting" + // JobStateStopped - The job is currently in the Stopped state. + JobStateStopped JobState = "Stopped" + // JobStateStopping - The job is currently in the Stopping state. + JobStateStopping JobState = "Stopping" +) + +// PossibleJobStateValues returns the possible values for the JobState const type. +func PossibleJobStateValues() []JobState { + return []JobState{ + JobStateCreated, + JobStateDegraded, + JobStateDeleting, + JobStateFailed, + JobStateRestarting, + JobStateRunning, + JobStateScaling, + JobStateStarting, + JobStateStopped, + JobStateStopping, + } +} + +// ToPtr returns a *JobState pointing to the current value. +func (c JobState) ToPtr() *JobState { + return &c +} + +// JobType - Describes the type of the job. Valid modes are Cloud and 'Edge'. +type JobType string + +const ( + JobTypeCloud JobType = "Cloud" + JobTypeEdge JobType = "Edge" +) + +// PossibleJobTypeValues returns the possible values for the JobType const type. +func PossibleJobTypeValues() []JobType { + return []JobType{ + JobTypeCloud, + JobTypeEdge, + } +} + +// ToPtr returns a *JobType pointing to the current value. +func (c JobType) ToPtr() *JobType { + return &c +} + +// OutputErrorPolicy - Indicates the policy to apply to events that arrive at the output and cannot be written to the external storage due to being malformed +// (missing column values, column values of wrong type or size). +type OutputErrorPolicy string + +const ( + OutputErrorPolicyDrop OutputErrorPolicy = "Drop" + OutputErrorPolicyStop OutputErrorPolicy = "Stop" +) + +// PossibleOutputErrorPolicyValues returns the possible values for the OutputErrorPolicy const type. +func PossibleOutputErrorPolicyValues() []OutputErrorPolicy { + return []OutputErrorPolicy{ + OutputErrorPolicyDrop, + OutputErrorPolicyStop, + } +} + +// ToPtr returns a *OutputErrorPolicy pointing to the current value. +func (c OutputErrorPolicy) ToPtr() *OutputErrorPolicy { + return &c +} + +// OutputStartMode - Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should +// start whenever the job is started, start at a custom user time +// stamp specified via the outputStartTime property, or start from the last event output time. +type OutputStartMode string + +const ( + OutputStartModeCustomTime OutputStartMode = "CustomTime" + OutputStartModeJobStartTime OutputStartMode = "JobStartTime" + OutputStartModeLastOutputEventTime OutputStartMode = "LastOutputEventTime" +) + +// PossibleOutputStartModeValues returns the possible values for the OutputStartMode const type. +func PossibleOutputStartModeValues() []OutputStartMode { + return []OutputStartMode{ + OutputStartModeCustomTime, + OutputStartModeJobStartTime, + OutputStartModeLastOutputEventTime, + } +} + +// ToPtr returns a *OutputStartMode pointing to the current value. +func (c OutputStartMode) ToPtr() *OutputStartMode { + return &c +} + +// QueryTestingResultStatus - The status of the query testing request. +type QueryTestingResultStatus string + +const ( + // QueryTestingResultStatusCompilerError - The query testing operation failed due to a compiler error. + QueryTestingResultStatusCompilerError QueryTestingResultStatus = "CompilerError" + // QueryTestingResultStatusRuntimeError - The query testing operation failed due to a runtime error. + QueryTestingResultStatusRuntimeError QueryTestingResultStatus = "RuntimeError" + // QueryTestingResultStatusStarted - The query testing operation was initiated. + QueryTestingResultStatusStarted QueryTestingResultStatus = "Started" + // QueryTestingResultStatusSuccess - The query testing operation succeeded. + QueryTestingResultStatusSuccess QueryTestingResultStatus = "Success" + // QueryTestingResultStatusTimeout - The query testing operation failed due to a timeout. + QueryTestingResultStatusTimeout QueryTestingResultStatus = "Timeout" + // QueryTestingResultStatusUnknownError - The query testing operation failed due to an unknown error . + QueryTestingResultStatusUnknownError QueryTestingResultStatus = "UnknownError" +) + +// PossibleQueryTestingResultStatusValues returns the possible values for the QueryTestingResultStatus const type. +func PossibleQueryTestingResultStatusValues() []QueryTestingResultStatus { + return []QueryTestingResultStatus{ + QueryTestingResultStatusCompilerError, + QueryTestingResultStatusRuntimeError, + QueryTestingResultStatusStarted, + QueryTestingResultStatusSuccess, + QueryTestingResultStatusTimeout, + QueryTestingResultStatusUnknownError, + } +} + +// ToPtr returns a *QueryTestingResultStatus pointing to the current value. +func (c QueryTestingResultStatus) ToPtr() *QueryTestingResultStatus { + return &c +} + +// SampleInputResultStatus - The status of the sample input request. +type SampleInputResultStatus string + +const ( + // SampleInputResultStatusErrorConnectingToInput - The sample input operation failed to connect to the input. + SampleInputResultStatusErrorConnectingToInput SampleInputResultStatus = "ErrorConnectingToInput" + // SampleInputResultStatusNoEventsFoundInRange - The sample input operation found no events in the range. + SampleInputResultStatusNoEventsFoundInRange SampleInputResultStatus = "NoEventsFoundInRange" + // SampleInputResultStatusReadAllEventsInRange - The sample input operation successfully read all the events in the range. + SampleInputResultStatusReadAllEventsInRange SampleInputResultStatus = "ReadAllEventsInRange" +) + +// PossibleSampleInputResultStatusValues returns the possible values for the SampleInputResultStatus const type. +func PossibleSampleInputResultStatusValues() []SampleInputResultStatus { + return []SampleInputResultStatus{ + SampleInputResultStatusErrorConnectingToInput, + SampleInputResultStatusNoEventsFoundInRange, + SampleInputResultStatusReadAllEventsInRange, + } +} + +// ToPtr returns a *SampleInputResultStatus pointing to the current value. +func (c SampleInputResultStatus) ToPtr() *SampleInputResultStatus { + return &c +} + +// StreamingJobSKUName - The name of the SKU. Required on PUT (CreateOrReplace) requests. +type StreamingJobSKUName string + +const ( + StreamingJobSKUNameStandard StreamingJobSKUName = "Standard" +) + +// PossibleStreamingJobSKUNameValues returns the possible values for the StreamingJobSKUName const type. +func PossibleStreamingJobSKUNameValues() []StreamingJobSKUName { + return []StreamingJobSKUName{ + StreamingJobSKUNameStandard, + } +} + +// ToPtr returns a *StreamingJobSKUName pointing to the current value. +func (c StreamingJobSKUName) ToPtr() *StreamingJobSKUName { + return &c +} + +// TestDatasourceResultStatus - The status of the test input or output request. +type TestDatasourceResultStatus string + +const ( + // TestDatasourceResultStatusTestFailed - The test datasource operation failed. + TestDatasourceResultStatusTestFailed TestDatasourceResultStatus = "TestFailed" + // TestDatasourceResultStatusTestSucceeded - The test datasource operation succeeded. + TestDatasourceResultStatusTestSucceeded TestDatasourceResultStatus = "TestSucceeded" +) + +// PossibleTestDatasourceResultStatusValues returns the possible values for the TestDatasourceResultStatus const type. +func PossibleTestDatasourceResultStatusValues() []TestDatasourceResultStatus { + return []TestDatasourceResultStatus{ + TestDatasourceResultStatusTestFailed, + TestDatasourceResultStatusTestSucceeded, + } +} + +// ToPtr returns a *TestDatasourceResultStatus pointing to the current value. +func (c TestDatasourceResultStatus) ToPtr() *TestDatasourceResultStatus { + return &c +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_functions_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_functions_client.go new file mode 100644 index 000000000000..c19cd4198f42 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_functions_client.go @@ -0,0 +1,547 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// FunctionsClient contains the methods for the Functions group. +// Don't use this type directly, use NewFunctionsClient() instead. +type FunctionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewFunctionsClient creates a new instance of FunctionsClient with the specified values. +func NewFunctionsClient(con *arm.Connection, subscriptionID string) *FunctionsClient { + return &FunctionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrReplace - Creates a function or replaces an already existing function under an existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) CreateOrReplace(ctx context.Context, resourceGroupName string, jobName string, functionName string, function Function, options *FunctionsCreateOrReplaceOptions) (FunctionsCreateOrReplaceResponse, error) { + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, jobName, functionName, function, options) + if err != nil { + return FunctionsCreateOrReplaceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FunctionsCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return FunctionsCreateOrReplaceResponse{}, client.createOrReplaceHandleError(resp) + } + return client.createOrReplaceHandleResponse(resp) +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *FunctionsClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, function Function, options *FunctionsCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, function) +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *FunctionsClient) createOrReplaceHandleResponse(resp *http.Response) (FunctionsCreateOrReplaceResponse, error) { + result := FunctionsCreateOrReplaceResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Function); err != nil { + return FunctionsCreateOrReplaceResponse{}, err + } + return result, nil +} + +// createOrReplaceHandleError handles the CreateOrReplace error response. +func (client *FunctionsClient) createOrReplaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes a function from the streaming job. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) Delete(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsDeleteOptions) (FunctionsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobName, functionName, options) + if err != nil { + return FunctionsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FunctionsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return FunctionsDeleteResponse{}, client.deleteHandleError(resp) + } + return FunctionsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *FunctionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *FunctionsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details about the specified function. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) Get(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsGetOptions) (FunctionsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobName, functionName, options) + if err != nil { + return FunctionsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FunctionsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FunctionsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *FunctionsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *FunctionsClient) getHandleResponse(resp *http.Response) (FunctionsGetResponse, error) { + result := FunctionsGetResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Function); err != nil { + return FunctionsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *FunctionsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByStreamingJob - Lists all of the functions under the specified streaming job. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) ListByStreamingJob(resourceGroupName string, jobName string, options *FunctionsListByStreamingJobOptions) *FunctionsListByStreamingJobPager { + return &FunctionsListByStreamingJobPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByStreamingJobCreateRequest(ctx, resourceGroupName, jobName, options) + }, + advancer: func(ctx context.Context, resp FunctionsListByStreamingJobResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.FunctionListResult.NextLink) + }, + } +} + +// listByStreamingJobCreateRequest creates the ListByStreamingJob request. +func (client *FunctionsClient) listByStreamingJobCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *FunctionsListByStreamingJobOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByStreamingJobHandleResponse handles the ListByStreamingJob response. +func (client *FunctionsClient) listByStreamingJobHandleResponse(resp *http.Response) (FunctionsListByStreamingJobResponse, error) { + result := FunctionsListByStreamingJobResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.FunctionListResult); err != nil { + return FunctionsListByStreamingJobResponse{}, err + } + return result, nil +} + +// listByStreamingJobHandleError handles the ListByStreamingJob error response. +func (client *FunctionsClient) listByStreamingJobHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// RetrieveDefaultDefinition - Retrieves the default definition of a function based on the parameters specified. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) RetrieveDefaultDefinition(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsRetrieveDefaultDefinitionOptions) (FunctionsRetrieveDefaultDefinitionResponse, error) { + req, err := client.retrieveDefaultDefinitionCreateRequest(ctx, resourceGroupName, jobName, functionName, options) + if err != nil { + return FunctionsRetrieveDefaultDefinitionResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FunctionsRetrieveDefaultDefinitionResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FunctionsRetrieveDefaultDefinitionResponse{}, client.retrieveDefaultDefinitionHandleError(resp) + } + return client.retrieveDefaultDefinitionHandleResponse(resp) +} + +// retrieveDefaultDefinitionCreateRequest creates the RetrieveDefaultDefinition request. +func (client *FunctionsClient) retrieveDefaultDefinitionCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsRetrieveDefaultDefinitionOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}/retrieveDefaultDefinition" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.FunctionRetrieveDefaultDefinitionParameters != nil { + return req, runtime.MarshalAsJSON(req, options.FunctionRetrieveDefaultDefinitionParameters) + } + return req, nil +} + +// retrieveDefaultDefinitionHandleResponse handles the RetrieveDefaultDefinition response. +func (client *FunctionsClient) retrieveDefaultDefinitionHandleResponse(resp *http.Response) (FunctionsRetrieveDefaultDefinitionResponse, error) { + result := FunctionsRetrieveDefaultDefinitionResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.Function); err != nil { + return FunctionsRetrieveDefaultDefinitionResponse{}, err + } + return result, nil +} + +// retrieveDefaultDefinitionHandleError handles the RetrieveDefaultDefinition error response. +func (client *FunctionsClient) retrieveDefaultDefinitionHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTest - Tests if the information provided for a function is valid. This can range from testing the connection to the underlying web service behind +// the function or making sure the function code provided is +// syntactically correct. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) BeginTest(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsBeginTestOptions) (FunctionsTestPollerResponse, error) { + resp, err := client.test(ctx, resourceGroupName, jobName, functionName, options) + if err != nil { + return FunctionsTestPollerResponse{}, err + } + result := FunctionsTestPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("FunctionsClient.Test", "", resp, client.pl, client.testHandleError) + if err != nil { + return FunctionsTestPollerResponse{}, err + } + result.Poller = &FunctionsTestPoller{ + pt: pt, + } + return result, nil +} + +// Test - Tests if the information provided for a function is valid. This can range from testing the connection to the underlying web service behind the +// function or making sure the function code provided is +// syntactically correct. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) test(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsBeginTestOptions) (*http.Response, error) { + req, err := client.testCreateRequest(ctx, resourceGroupName, jobName, functionName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.testHandleError(resp) + } + return resp, nil +} + +// testCreateRequest creates the Test request. +func (client *FunctionsClient) testCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, options *FunctionsBeginTestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}/test" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Function != nil { + return req, runtime.MarshalAsJSON(req, *options.Function) + } + return req, nil +} + +// testHandleError handles the Test error response. +func (client *FunctionsClient) testHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing function under an existing streaming job. This can be used to partially update (ie. update one or two properties) a function +// without affecting the rest the job or function +// definition. +// If the operation fails it returns the *Error error type. +func (client *FunctionsClient) Update(ctx context.Context, resourceGroupName string, jobName string, functionName string, function Function, options *FunctionsUpdateOptions) (FunctionsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, jobName, functionName, function, options) + if err != nil { + return FunctionsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return FunctionsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return FunctionsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *FunctionsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, jobName string, functionName string, function Function, options *FunctionsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/functions/{functionName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if functionName == "" { + return nil, errors.New("parameter functionName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{functionName}", url.PathEscape(functionName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, function) +} + +// updateHandleResponse handles the Update response. +func (client *FunctionsClient) updateHandleResponse(resp *http.Response) (FunctionsUpdateResponse, error) { + result := FunctionsUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Function); err != nil { + return FunctionsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *FunctionsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_inputs_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_inputs_client.go new file mode 100644 index 000000000000..782928f31013 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_inputs_client.go @@ -0,0 +1,470 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// InputsClient contains the methods for the Inputs group. +// Don't use this type directly, use NewInputsClient() instead. +type InputsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewInputsClient creates a new instance of InputsClient with the specified values. +func NewInputsClient(con *arm.Connection, subscriptionID string) *InputsClient { + return &InputsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrReplace - Creates an input or replaces an already existing input under an existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) CreateOrReplace(ctx context.Context, resourceGroupName string, jobName string, inputName string, input Input, options *InputsCreateOrReplaceOptions) (InputsCreateOrReplaceResponse, error) { + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, jobName, inputName, input, options) + if err != nil { + return InputsCreateOrReplaceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return InputsCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return InputsCreateOrReplaceResponse{}, client.createOrReplaceHandleError(resp) + } + return client.createOrReplaceHandleResponse(resp) +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *InputsClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, jobName string, inputName string, input Input, options *InputsCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs/{inputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if inputName == "" { + return nil, errors.New("parameter inputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inputName}", url.PathEscape(inputName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, input) +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *InputsClient) createOrReplaceHandleResponse(resp *http.Response) (InputsCreateOrReplaceResponse, error) { + result := InputsCreateOrReplaceResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Input); err != nil { + return InputsCreateOrReplaceResponse{}, err + } + return result, nil +} + +// createOrReplaceHandleError handles the CreateOrReplace error response. +func (client *InputsClient) createOrReplaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes an input from the streaming job. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) Delete(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsDeleteOptions) (InputsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobName, inputName, options) + if err != nil { + return InputsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return InputsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return InputsDeleteResponse{}, client.deleteHandleError(resp) + } + return InputsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *InputsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs/{inputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if inputName == "" { + return nil, errors.New("parameter inputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inputName}", url.PathEscape(inputName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *InputsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details about the specified input. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) Get(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsGetOptions) (InputsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobName, inputName, options) + if err != nil { + return InputsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return InputsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return InputsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *InputsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs/{inputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if inputName == "" { + return nil, errors.New("parameter inputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inputName}", url.PathEscape(inputName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *InputsClient) getHandleResponse(resp *http.Response) (InputsGetResponse, error) { + result := InputsGetResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Input); err != nil { + return InputsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *InputsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByStreamingJob - Lists all of the inputs under the specified streaming job. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) ListByStreamingJob(resourceGroupName string, jobName string, options *InputsListByStreamingJobOptions) *InputsListByStreamingJobPager { + return &InputsListByStreamingJobPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByStreamingJobCreateRequest(ctx, resourceGroupName, jobName, options) + }, + advancer: func(ctx context.Context, resp InputsListByStreamingJobResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.InputListResult.NextLink) + }, + } +} + +// listByStreamingJobCreateRequest creates the ListByStreamingJob request. +func (client *InputsClient) listByStreamingJobCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *InputsListByStreamingJobOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByStreamingJobHandleResponse handles the ListByStreamingJob response. +func (client *InputsClient) listByStreamingJobHandleResponse(resp *http.Response) (InputsListByStreamingJobResponse, error) { + result := InputsListByStreamingJobResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.InputListResult); err != nil { + return InputsListByStreamingJobResponse{}, err + } + return result, nil +} + +// listByStreamingJobHandleError handles the ListByStreamingJob error response. +func (client *InputsClient) listByStreamingJobHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTest - Tests whether an input’s datasource is reachable and usable by the Azure Stream Analytics service. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) BeginTest(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsBeginTestOptions) (InputsTestPollerResponse, error) { + resp, err := client.test(ctx, resourceGroupName, jobName, inputName, options) + if err != nil { + return InputsTestPollerResponse{}, err + } + result := InputsTestPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("InputsClient.Test", "", resp, client.pl, client.testHandleError) + if err != nil { + return InputsTestPollerResponse{}, err + } + result.Poller = &InputsTestPoller{ + pt: pt, + } + return result, nil +} + +// Test - Tests whether an input’s datasource is reachable and usable by the Azure Stream Analytics service. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) test(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsBeginTestOptions) (*http.Response, error) { + req, err := client.testCreateRequest(ctx, resourceGroupName, jobName, inputName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.testHandleError(resp) + } + return resp, nil +} + +// testCreateRequest creates the Test request. +func (client *InputsClient) testCreateRequest(ctx context.Context, resourceGroupName string, jobName string, inputName string, options *InputsBeginTestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs/{inputName}/test" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if inputName == "" { + return nil, errors.New("parameter inputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inputName}", url.PathEscape(inputName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Input != nil { + return req, runtime.MarshalAsJSON(req, *options.Input) + } + return req, nil +} + +// testHandleError handles the Test error response. +func (client *InputsClient) testHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing input under an existing streaming job. This can be used to partially update (ie. update one or two properties) an input +// without affecting the rest the job or input definition. +// If the operation fails it returns the *Error error type. +func (client *InputsClient) Update(ctx context.Context, resourceGroupName string, jobName string, inputName string, input Input, options *InputsUpdateOptions) (InputsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, jobName, inputName, input, options) + if err != nil { + return InputsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return InputsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return InputsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *InputsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, jobName string, inputName string, input Input, options *InputsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/inputs/{inputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if inputName == "" { + return nil, errors.New("parameter inputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{inputName}", url.PathEscape(inputName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, input) +} + +// updateHandleResponse handles the Update response. +func (client *InputsClient) updateHandleResponse(resp *http.Response) (InputsUpdateResponse, error) { + result := InputsUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Input); err != nil { + return InputsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *InputsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_models.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_models.go new file mode 100644 index 000000000000..d71222ea8ba2 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_models.go @@ -0,0 +1,4329 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "encoding/json" + "reflect" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// AggregateFunctionProperties - The properties that are associated with an aggregate function. +type AggregateFunctionProperties struct { + FunctionProperties +} + +// MarshalJSON implements the json.Marshaller interface for type AggregateFunctionProperties. +func (a AggregateFunctionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.FunctionProperties.marshalInternal(objectMap, "Aggregate") + return json.Marshal(objectMap) +} + +// AvroSerialization - Describes how data from an input is serialized or how data is serialized when written to an output in Avro format. +type AvroSerialization struct { + Serialization + // The properties that are associated with the Avro serialization type. Required on PUT (CreateOrReplace) requests. + Properties map[string]interface{} `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AvroSerialization. +func (a AvroSerialization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.Serialization.marshalInternal(objectMap, EventSerializationTypeAvro) + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AvroSerialization. +func (a *AvroSerialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.Serialization.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureDataLakeStoreOutputDataSource - Describes an Azure Data Lake Store output data source. +type AzureDataLakeStoreOutputDataSource struct { + OutputDataSource + // The properties that are associated with an Azure Data Lake Store output. Required on PUT (CreateOrReplace) requests. + Properties *AzureDataLakeStoreOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureDataLakeStoreOutputDataSource. +func (a AzureDataLakeStoreOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.OutputDataSource.marshalInternal(objectMap, "Microsoft.DataLake/Accounts") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureDataLakeStoreOutputDataSource. +func (a *AzureDataLakeStoreOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureDataLakeStoreOutputDataSourceProperties - The properties that are associated with an Azure Data Lake Store. +type AzureDataLakeStoreOutputDataSourceProperties struct { + OAuthBasedDataSourceProperties + // The name of the Azure Data Lake Store account. Required on PUT (CreateOrReplace) requests. + AccountName *string `json:"accountName,omitempty"` + + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` + + // The date format. Wherever {date} appears in filePathPrefix, the value of this property is used as the date format instead. + DateFormat *string `json:"dateFormat,omitempty"` + + // The location of the file to which the output should be written to. Required on PUT (CreateOrReplace) requests. + FilePathPrefix *string `json:"filePathPrefix,omitempty"` + + // The tenant id of the user used to obtain the refresh token. Required on PUT (CreateOrReplace) requests. + TenantID *string `json:"tenantId,omitempty"` + + // The time format. Wherever {time} appears in filePathPrefix, the value of this property is used as the time format instead. + TimeFormat *string `json:"timeFormat,omitempty"` +} + +// AzureFunctionOutputDataSource - Defines the metadata of AzureFunctionOutputDataSource +type AzureFunctionOutputDataSource struct { + OutputDataSource + // The properties that are associated with a Azure Function output. Required on PUT (CreateOrReplace) requests. + Properties *AzureFunctionOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureFunctionOutputDataSource. +func (a AzureFunctionOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.OutputDataSource.marshalInternal(objectMap, "Microsoft.AzureFunction") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureFunctionOutputDataSource. +func (a *AzureFunctionOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureFunctionOutputDataSourceProperties - The properties that are associated with a DocumentDB output. +type AzureFunctionOutputDataSourceProperties struct { + // If you want to use an Azure Function from another subscription, you can do so by providing the key to access your function. + APIKey *string `json:"apiKey,omitempty"` + + // The name of your Azure Functions app. + FunctionAppName *string `json:"functionAppName,omitempty"` + + // The name of the function in your Azure Functions app. + FunctionName *string `json:"functionName,omitempty"` + + // A property that lets you specify the maximum number of events in each batch that's sent to Azure Functions. The default value is 100. + MaxBatchCount *float32 `json:"maxBatchCount,omitempty"` + + // A property that lets you set the maximum size for each output batch that's sent to your Azure function. The input unit is in bytes. By default, this + // value is 262,144 bytes (256 KB). + MaxBatchSize *float32 `json:"maxBatchSize,omitempty"` +} + +// AzureMachineLearningServiceFunctionBinding - The binding to an Azure Machine Learning web service. +type AzureMachineLearningServiceFunctionBinding struct { + FunctionBinding + // The binding properties associated with an Azure Machine learning web service. + Properties *AzureMachineLearningServiceFunctionBindingProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningServiceFunctionBinding. +func (a AzureMachineLearningServiceFunctionBinding) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.FunctionBinding.marshalInternal(objectMap, "Microsoft.MachineLearningServices") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureMachineLearningServiceFunctionBinding. +func (a *AzureMachineLearningServiceFunctionBinding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.FunctionBinding.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureMachineLearningServiceFunctionBindingProperties - The binding properties associated with an Azure Machine learning web service. +type AzureMachineLearningServiceFunctionBindingProperties struct { + // The API key used to authenticate with Request-Response endpoint. + APIKey *string `json:"apiKey,omitempty"` + + // Number between 1 and 10000 describing maximum number of rows for every Azure ML RRS execute request. Default is 1000. + BatchSize *int32 `json:"batchSize,omitempty"` + + // The Request-Response execute endpoint of the Azure Machine Learning web service. + Endpoint *string `json:"endpoint,omitempty"` + + // The inputs for the Azure Machine Learning web service endpoint. + Inputs []*AzureMachineLearningServiceInputColumn `json:"inputs,omitempty"` + + // The number of parallel requests that will be sent per partition of your job to the machine learning service. Default is 1. + NumberOfParallelRequests *int32 `json:"numberOfParallelRequests,omitempty"` + + // A list of outputs from the Azure Machine Learning web service endpoint execution. + Outputs []*AzureMachineLearningServiceOutputColumn `json:"outputs,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningServiceFunctionBindingProperties. +func (a AzureMachineLearningServiceFunctionBindingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "apiKey", a.APIKey) + populate(objectMap, "batchSize", a.BatchSize) + populate(objectMap, "endpoint", a.Endpoint) + populate(objectMap, "inputs", a.Inputs) + populate(objectMap, "numberOfParallelRequests", a.NumberOfParallelRequests) + populate(objectMap, "outputs", a.Outputs) + return json.Marshal(objectMap) +} + +// AzureMachineLearningServiceFunctionBindingRetrievalProperties - The binding retrieval properties associated with an Azure Machine learning web service. +type AzureMachineLearningServiceFunctionBindingRetrievalProperties struct { + // The Request-Response execute endpoint of the Azure Machine Learning web service. + ExecuteEndpoint *string `json:"executeEndpoint,omitempty"` + + // The function type. + UdfType *string `json:"udfType,omitempty"` +} + +// AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters - The parameters needed to retrieve the default function definition for an Azure +// Machine Learning web service function. +type AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters struct { + FunctionRetrieveDefaultDefinitionParameters + // The binding retrieval properties associated with an Azure Machine learning web service. + BindingRetrievalProperties *AzureMachineLearningServiceFunctionBindingRetrievalProperties `json:"bindingRetrievalProperties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters. +func (a AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.FunctionRetrieveDefaultDefinitionParameters.marshalInternal(objectMap, "Microsoft.MachineLearningServices") + populate(objectMap, "bindingRetrievalProperties", a.BindingRetrievalProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters. +func (a *AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bindingRetrievalProperties": + err = unpopulate(val, &a.BindingRetrievalProperties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.FunctionRetrieveDefaultDefinitionParameters.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureMachineLearningServiceInputColumn - Describes an input column for the Azure Machine Learning web service endpoint. +type AzureMachineLearningServiceInputColumn struct { + // The (Azure Machine Learning supported) data type of the input column. + DataType *string `json:"dataType,omitempty"` + + // The zero based index of the function parameter this input maps to. + MapTo *int32 `json:"mapTo,omitempty"` + + // The name of the input column. + Name *string `json:"name,omitempty"` +} + +// AzureMachineLearningServiceInputs - The inputs for the Azure Machine Learning web service endpoint. +type AzureMachineLearningServiceInputs struct { + // A list of input columns for the Azure Machine Learning web service endpoint. + ColumnNames []*AzureMachineLearningServiceInputColumn `json:"columnNames,omitempty"` + + // The name of the input. This is the name provided while authoring the endpoint. + Name *string `json:"name,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningServiceInputs. +func (a AzureMachineLearningServiceInputs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "columnNames", a.ColumnNames) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// AzureMachineLearningServiceOutputColumn - Describes an output column for the Azure Machine Learning web service endpoint. +type AzureMachineLearningServiceOutputColumn struct { + // The (Azure Machine Learning supported) data type of the output column. + DataType *string `json:"dataType,omitempty"` + + // The zero based index of the function parameter this input maps to. + MapTo *int32 `json:"mapTo,omitempty"` + + // The name of the output column. + Name *string `json:"name,omitempty"` +} + +// AzureMachineLearningStudioFunctionBinding - The binding to an Azure Machine Learning Studio. +type AzureMachineLearningStudioFunctionBinding struct { + FunctionBinding + // The binding properties associated with an Azure Machine learning Studio. + Properties *AzureMachineLearningStudioFunctionBindingProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningStudioFunctionBinding. +func (a AzureMachineLearningStudioFunctionBinding) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.FunctionBinding.marshalInternal(objectMap, "Microsoft.MachineLearning/WebService") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureMachineLearningStudioFunctionBinding. +func (a *AzureMachineLearningStudioFunctionBinding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.FunctionBinding.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureMachineLearningStudioFunctionBindingProperties - The binding properties associated with an Azure Machine learning Studio. +type AzureMachineLearningStudioFunctionBindingProperties struct { + // The API key used to authenticate with Request-Response endpoint. + APIKey *string `json:"apiKey,omitempty"` + + // Number between 1 and 10000 describing maximum number of rows for every Azure ML RRS execute request. Default is 1000. + BatchSize *int32 `json:"batchSize,omitempty"` + + // The Request-Response execute endpoint of the Azure Machine Learning Studio. Find out more here: + // https://docs.microsoft.com/en-us/azure/machine-learning/machine-learning-consume-web-services#request-response-service-rrs + Endpoint *string `json:"endpoint,omitempty"` + + // The inputs for the Azure Machine Learning Studio endpoint. + Inputs *AzureMachineLearningStudioInputs `json:"inputs,omitempty"` + + // A list of outputs from the Azure Machine Learning Studio endpoint execution. + Outputs []*AzureMachineLearningStudioOutputColumn `json:"outputs,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningStudioFunctionBindingProperties. +func (a AzureMachineLearningStudioFunctionBindingProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "apiKey", a.APIKey) + populate(objectMap, "batchSize", a.BatchSize) + populate(objectMap, "endpoint", a.Endpoint) + populate(objectMap, "inputs", a.Inputs) + populate(objectMap, "outputs", a.Outputs) + return json.Marshal(objectMap) +} + +// AzureMachineLearningStudioFunctionBindingRetrievalProperties - The binding retrieval properties associated with an Azure Machine learning Studio. +type AzureMachineLearningStudioFunctionBindingRetrievalProperties struct { + // The Request-Response execute endpoint of the Azure Machine Learning Studio. Find out more here: + // https://docs.microsoft.com/en-us/azure/machine-learning/machine-learning-consume-web-services#request-response-service-rrs + ExecuteEndpoint *string `json:"executeEndpoint,omitempty"` + + // The function type. + UdfType *string `json:"udfType,omitempty"` +} + +// AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters - The parameters needed to retrieve the default function definition for an Azure +// Machine Learning Studio function. +type AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters struct { + FunctionRetrieveDefaultDefinitionParameters + // The binding retrieval properties associated with an Azure Machine learning Studio. + BindingRetrievalProperties *AzureMachineLearningStudioFunctionBindingRetrievalProperties `json:"bindingRetrievalProperties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters. +func (a AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.FunctionRetrieveDefaultDefinitionParameters.marshalInternal(objectMap, "Microsoft.MachineLearning/WebService") + populate(objectMap, "bindingRetrievalProperties", a.BindingRetrievalProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters. +func (a *AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bindingRetrievalProperties": + err = unpopulate(val, &a.BindingRetrievalProperties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.FunctionRetrieveDefaultDefinitionParameters.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureMachineLearningStudioInputColumn - Describes an input column for the Azure Machine Learning Studio endpoint. +type AzureMachineLearningStudioInputColumn struct { + // The (Azure Machine Learning supported) data type of the input column. A list of valid Azure Machine Learning data types are described at https://msdn.microsoft.com/en-us/library/azure/dn905923.aspx + // . + DataType *string `json:"dataType,omitempty"` + + // The zero based index of the function parameter this input maps to. + MapTo *int32 `json:"mapTo,omitempty"` + + // The name of the input column. + Name *string `json:"name,omitempty"` +} + +// AzureMachineLearningStudioInputs - The inputs for the Azure Machine Learning Studio endpoint. +type AzureMachineLearningStudioInputs struct { + // A list of input columns for the Azure Machine Learning Studio endpoint. + ColumnNames []*AzureMachineLearningStudioInputColumn `json:"columnNames,omitempty"` + + // The name of the input. This is the name provided while authoring the endpoint. + Name *string `json:"name,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureMachineLearningStudioInputs. +func (a AzureMachineLearningStudioInputs) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "columnNames", a.ColumnNames) + populate(objectMap, "name", a.Name) + return json.Marshal(objectMap) +} + +// AzureMachineLearningStudioOutputColumn - Describes an output column for the Azure Machine Learning Studio endpoint. +type AzureMachineLearningStudioOutputColumn struct { + // The (Azure Machine Learning supported) data type of the output column. A list of valid Azure Machine Learning data types are described at https://msdn.microsoft.com/en-us/library/azure/dn905923.aspx + // . + DataType *string `json:"dataType,omitempty"` + + // The name of the output column. + Name *string `json:"name,omitempty"` +} + +// AzureSQLDatabaseDataSourceProperties - The properties that are associated with an Azure SQL database data source. +type AzureSQLDatabaseDataSourceProperties struct { + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` + + // The name of the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Database *string `json:"database,omitempty"` + + // Max Batch count for write to Sql database, the default value is 10,000. Optional on PUT requests. + MaxBatchCount *float32 `json:"maxBatchCount,omitempty"` + + // Max Write r count, currently only 1(single writer) and 0(based on query partition) are available. Optional on PUT requests. + MaxWriterCount *float32 `json:"maxWriterCount,omitempty"` + + // The password that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Password *string `json:"password,omitempty"` + + // The name of the SQL server containing the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Server *string `json:"server,omitempty"` + + // The name of the table in the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Table *string `json:"table,omitempty"` + + // The user name that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. + User *string `json:"user,omitempty"` +} + +// AzureSQLDatabaseOutputDataSource - Describes an Azure SQL database output data source. +type AzureSQLDatabaseOutputDataSource struct { + OutputDataSource + // The properties that are associated with an Azure SQL database output. Required on PUT (CreateOrReplace) requests. + Properties *AzureSQLDatabaseOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureSQLDatabaseOutputDataSource. +func (a AzureSQLDatabaseOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.OutputDataSource.marshalInternal(objectMap, "Microsoft.Sql/Server/Database") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureSQLDatabaseOutputDataSource. +func (a *AzureSQLDatabaseOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureSQLDatabaseOutputDataSourceProperties - The properties that are associated with an Azure SQL database output. +type AzureSQLDatabaseOutputDataSourceProperties struct { + AzureSQLDatabaseDataSourceProperties +} + +// AzureSQLReferenceInputDataSource - Describes an Azure SQL database reference input data source. +type AzureSQLReferenceInputDataSource struct { + ReferenceInputDataSource + // Describes Azure SQL database reference input data source properties. + Properties *AzureSQLReferenceInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureSQLReferenceInputDataSource. +func (a AzureSQLReferenceInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.ReferenceInputDataSource.marshalInternal(objectMap, "Microsoft.Sql/Server/Database") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureSQLReferenceInputDataSource. +func (a *AzureSQLReferenceInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.ReferenceInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureSQLReferenceInputDataSourceProperties - Describes Azure SQL database reference input data source properties. +type AzureSQLReferenceInputDataSourceProperties struct { + // This element is associated with the datasource element. This is the name of the database that output will be written to. + Database *string `json:"database,omitempty"` + + // This element is associated with the datasource element. This query is used to fetch incremental changes from the SQL database. To use this option, we + // recommend using temporal tables in Azure SQL + // Database. + DeltaSnapshotQuery *string `json:"deltaSnapshotQuery,omitempty"` + + // This element is associated with the datasource element. This query is used to fetch data from the sql database. + FullSnapshotQuery *string `json:"fullSnapshotQuery,omitempty"` + + // This element is associated with the datasource element. This is the password that will be used to connect to the SQL Database instance. + Password *string `json:"password,omitempty"` + + // This element is associated with the datasource element. This indicates how frequently the data will be fetched from the database. It is of DateTime format. + RefreshRate *string `json:"refreshRate,omitempty"` + + // This element is associated with the datasource element. This element is of enum type. It indicates what kind of data refresh option do we want to + // use:Static/RefreshPeriodicallyWithFull/RefreshPeriodicallyWithDelta + RefreshType *string `json:"refreshType,omitempty"` + + // This element is associated with the datasource element. This is the name of the server that contains the database that will be written to. + Server *string `json:"server,omitempty"` + + // This element is associated with the datasource element. The name of the table in the Azure SQL database.. + Table *string `json:"table,omitempty"` + + // This element is associated with the datasource element. This is the user name that will be used to connect to the SQL Database instance. + User *string `json:"user,omitempty"` +} + +// AzureSynapseDataSourceProperties - The properties that are associated with an Azure SQL database data source. +type AzureSynapseDataSourceProperties struct { + // The name of the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Database *string `json:"database,omitempty"` + + // The password that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Password *string `json:"password,omitempty"` + + // The name of the SQL server containing the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Server *string `json:"server,omitempty"` + + // The name of the table in the Azure SQL database. Required on PUT (CreateOrReplace) requests. + Table *string `json:"table,omitempty"` + + // The user name that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. + User *string `json:"user,omitempty"` +} + +// AzureSynapseOutputDataSource - Describes an Azure Synapse output data source. +type AzureSynapseOutputDataSource struct { + OutputDataSource + // The properties that are associated with an Azure Synapse output. Required on PUT (CreateOrReplace) requests. + Properties *AzureSynapseOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureSynapseOutputDataSource. +func (a AzureSynapseOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.OutputDataSource.marshalInternal(objectMap, "Microsoft.Sql/Server/DataWarehouse") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureSynapseOutputDataSource. +func (a *AzureSynapseOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureSynapseOutputDataSourceProperties - The properties that are associated with an Azure Synapse output. +type AzureSynapseOutputDataSourceProperties struct { + AzureSynapseDataSourceProperties +} + +// AzureTableOutputDataSource - Describes an Azure Table output data source. +type AzureTableOutputDataSource struct { + OutputDataSource + // The properties that are associated with an Azure Table output. Required on PUT (CreateOrReplace) requests. + Properties *AzureTableOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureTableOutputDataSource. +func (a AzureTableOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + a.OutputDataSource.marshalInternal(objectMap, "Microsoft.Storage/Table") + populate(objectMap, "properties", a.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type AzureTableOutputDataSource. +func (a *AzureTableOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &a.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := a.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// AzureTableOutputDataSourceProperties - The properties that are associated with an Azure Table output. +type AzureTableOutputDataSourceProperties struct { + // The account key for the Azure Storage account. Required on PUT (CreateOrReplace) requests. + AccountKey *string `json:"accountKey,omitempty"` + + // The name of the Azure Storage account. Required on PUT (CreateOrReplace) requests. + AccountName *string `json:"accountName,omitempty"` + + // The number of rows to write to the Azure Table at a time. + BatchSize *int32 `json:"batchSize,omitempty"` + + // If specified, each item in the array is the name of a column to remove (if present) from output event entities. + ColumnsToRemove []*string `json:"columnsToRemove,omitempty"` + + // This element indicates the name of a column from the SELECT statement in the query that will be used as the partition key for the Azure Table. Required + // on PUT (CreateOrReplace) requests. + PartitionKey *string `json:"partitionKey,omitempty"` + + // This element indicates the name of a column from the SELECT statement in the query that will be used as the row key for the Azure Table. Required on + // PUT (CreateOrReplace) requests. + RowKey *string `json:"rowKey,omitempty"` + + // The name of the Azure Table. Required on PUT (CreateOrReplace) requests. + Table *string `json:"table,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type AzureTableOutputDataSourceProperties. +func (a AzureTableOutputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "accountKey", a.AccountKey) + populate(objectMap, "accountName", a.AccountName) + populate(objectMap, "batchSize", a.BatchSize) + populate(objectMap, "columnsToRemove", a.ColumnsToRemove) + populate(objectMap, "partitionKey", a.PartitionKey) + populate(objectMap, "rowKey", a.RowKey) + populate(objectMap, "table", a.Table) + return json.Marshal(objectMap) +} + +// BlobDataSourceProperties - The properties that are associated with a blob data source. +type BlobDataSourceProperties struct { + // The name of a container within the associated Storage account. This container contains either the blob(s) to be read from or written to. Required on + // PUT (CreateOrReplace) requests. + Container *string `json:"container,omitempty"` + + // The date format. Wherever {date} appears in pathPattern, the value of this property is used as the date format instead. + DateFormat *string `json:"dateFormat,omitempty"` + + // The blob path pattern. Not a regular expression. It represents a pattern against which blob names will be matched to determine whether or not they should + // be included as input or output to the job. See + // https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output + // for a more detailed explanation + // and example. + PathPattern *string `json:"pathPattern,omitempty"` + + // A list of one or more Azure Storage accounts. Required on PUT (CreateOrReplace) requests. + StorageAccounts []*StorageAccount `json:"storageAccounts,omitempty"` + + // The time format. Wherever {time} appears in pathPattern, the value of this property is used as the time format instead. + TimeFormat *string `json:"timeFormat,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobDataSourceProperties. +func (b BlobDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (b BlobDataSourceProperties) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "container", b.Container) + populate(objectMap, "dateFormat", b.DateFormat) + populate(objectMap, "pathPattern", b.PathPattern) + populate(objectMap, "storageAccounts", b.StorageAccounts) + populate(objectMap, "timeFormat", b.TimeFormat) +} + +// BlobOutputDataSource - Describes a blob output data source. +type BlobOutputDataSource struct { + OutputDataSource + // The properties that are associated with a blob output. Required on PUT (CreateOrReplace) requests. + Properties *BlobOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobOutputDataSource. +func (b BlobOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.OutputDataSource.marshalInternal(objectMap, "Microsoft.Storage/Blob") + populate(objectMap, "properties", b.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobOutputDataSource. +func (b *BlobOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &b.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := b.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// BlobOutputDataSourceProperties - The properties that are associated with a blob output. +type BlobOutputDataSourceProperties struct { + BlobDataSourceProperties + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobOutputDataSourceProperties. +func (b BlobOutputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.BlobDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "authenticationMode", b.AuthenticationMode) + return json.Marshal(objectMap) +} + +// BlobReferenceInputDataSource - Describes a blob input data source that contains reference data. +type BlobReferenceInputDataSource struct { + ReferenceInputDataSource + // The properties that are associated with a blob input containing reference data. Required on PUT (CreateOrReplace) requests. + Properties *BlobReferenceInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobReferenceInputDataSource. +func (b BlobReferenceInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.ReferenceInputDataSource.marshalInternal(objectMap, "Microsoft.Storage/Blob") + populate(objectMap, "properties", b.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobReferenceInputDataSource. +func (b *BlobReferenceInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &b.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := b.ReferenceInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// BlobReferenceInputDataSourceProperties - The properties that are associated with a blob input containing reference data. +type BlobReferenceInputDataSourceProperties struct { + BlobDataSourceProperties +} + +// BlobStreamInputDataSource - Describes a blob input data source that contains stream data. +type BlobStreamInputDataSource struct { + StreamInputDataSource + // The properties that are associated with a blob input containing stream data. Required on PUT (CreateOrReplace) requests. + Properties *BlobStreamInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobStreamInputDataSource. +func (b BlobStreamInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.StreamInputDataSource.marshalInternal(objectMap, "Microsoft.Storage/Blob") + populate(objectMap, "properties", b.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type BlobStreamInputDataSource. +func (b *BlobStreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &b.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := b.StreamInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// BlobStreamInputDataSourceProperties - The properties that are associated with a blob input containing stream data. +type BlobStreamInputDataSourceProperties struct { + BlobDataSourceProperties + // The partition count of the blob input data source. Range 1 - 256. + SourcePartitionCount *int32 `json:"sourcePartitionCount,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type BlobStreamInputDataSourceProperties. +func (b BlobStreamInputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + b.BlobDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "sourcePartitionCount", b.SourcePartitionCount) + return json.Marshal(objectMap) +} + +// CSVSerialization - Describes how data from an input is serialized or how data is serialized when written to an output in CSV format. +type CSVSerialization struct { + Serialization + // The properties that are associated with the CSV serialization type. Required on PUT (CreateOrReplace) requests. + Properties *CSVSerializationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CSVSerialization. +func (c CSVSerialization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.Serialization.marshalInternal(objectMap, EventSerializationTypeCSV) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CSVSerialization. +func (c *CSVSerialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.Serialization.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// CSVSerializationProperties - The properties that are associated with the CSV serialization type. +type CSVSerializationProperties struct { + // Specifies the encoding of the incoming data in the case of input and the encoding of outgoing data in the case of output. Required on PUT (CreateOrReplace) + // requests. + Encoding *Encoding `json:"encoding,omitempty"` + + // Specifies the delimiter that will be used to separate comma-separated value (CSV) records. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input + // or + // https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a list of supported values. Required on PUT (CreateOrReplace) requests. + FieldDelimiter *string `json:"fieldDelimiter,omitempty"` +} + +// CSharpFunctionBinding - The binding to a CSharp function. +type CSharpFunctionBinding struct { + FunctionBinding + // The binding properties associated with a CSharp function. + Properties *CSharpFunctionBindingProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CSharpFunctionBinding. +func (c CSharpFunctionBinding) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.FunctionBinding.marshalInternal(objectMap, "Microsoft.StreamAnalytics/CLRUdf") + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CSharpFunctionBinding. +func (c *CSharpFunctionBinding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.FunctionBinding.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// CSharpFunctionBindingProperties - The binding properties associated with a CSharp function. +type CSharpFunctionBindingProperties struct { + // The Csharp code containing a single function definition. + Class *string `json:"class,omitempty"` + + // The Csharp code containing a single function definition. + DllPath *string `json:"dllPath,omitempty"` + + // The Csharp code containing a single function definition. + Method *string `json:"method,omitempty"` + + // The Csharp code containing a single function definition. + Script *string `json:"script,omitempty"` +} + +// CSharpFunctionBindingRetrievalProperties - The binding retrieval properties associated with a CSharp function. +type CSharpFunctionBindingRetrievalProperties struct { + // The CSharp code containing a single function definition. + Script *string `json:"script,omitempty"` + + // The function type. + UdfType *string `json:"udfType,omitempty"` +} + +// CSharpFunctionRetrieveDefaultDefinitionParameters - The parameters needed to retrieve the default function definition for a CSharp function. +type CSharpFunctionRetrieveDefaultDefinitionParameters struct { + FunctionRetrieveDefaultDefinitionParameters + // The binding retrieval properties associated with a CSharp function. + BindingRetrievalProperties *CSharpFunctionBindingRetrievalProperties `json:"bindingRetrievalProperties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CSharpFunctionRetrieveDefaultDefinitionParameters. +func (c CSharpFunctionRetrieveDefaultDefinitionParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.FunctionRetrieveDefaultDefinitionParameters.marshalInternal(objectMap, "Microsoft.StreamAnalytics/CLRUdf") + populate(objectMap, "bindingRetrievalProperties", c.BindingRetrievalProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CSharpFunctionRetrieveDefaultDefinitionParameters. +func (c *CSharpFunctionRetrieveDefaultDefinitionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bindingRetrievalProperties": + err = unpopulate(val, &c.BindingRetrievalProperties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.FunctionRetrieveDefaultDefinitionParameters.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// Cluster - A Stream Analytics Cluster object +type Cluster struct { + TrackedResource + // The properties associated with a Stream Analytics cluster. + Properties *ClusterProperties `json:"properties,omitempty"` + + // The SKU of the cluster. This determines the size/capacity of the cluster. Required on PUT (CreateOrUpdate) requests. + SKU *ClusterSKU `json:"sku,omitempty"` + + // READ-ONLY; The current entity tag for the cluster. This is an opaque string. You can use it to detect whether the resource has changed between requests. + // You can also use it in the If-Match or If-None-Match + // headers for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Cluster. +func (c Cluster) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "etag", c.Etag) + populate(objectMap, "properties", c.Properties) + populate(objectMap, "sku", c.SKU) + return json.Marshal(objectMap) +} + +// ClusterInfo - The properties associated with a Stream Analytics cluster. +type ClusterInfo struct { + // The resource id of cluster. + ID *string `json:"id,omitempty"` +} + +// ClusterJob - A streaming job. +type ClusterJob struct { + // READ-ONLY; Resource ID of the streaming job. + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The current execution state of the streaming job. + JobState *JobState `json:"jobState,omitempty" azure:"ro"` + + // READ-ONLY; The number of streaming units that are used by the streaming job. + StreamingUnits *int32 `json:"streamingUnits,omitempty" azure:"ro"` +} + +// ClusterJobListResult - A list of streaming jobs. Populated by a List operation. +type ClusterJobListResult struct { + // READ-ONLY; The URL to fetch the next set of streaming jobs. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of streaming jobs. + Value []*ClusterJob `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ClusterJobListResult. +func (c ClusterJobListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// ClusterListResult - A list of clusters populated by a 'list' operation. +type ClusterListResult struct { + // READ-ONLY; The URL to fetch the next set of clusters. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of clusters. + Value []*Cluster `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ClusterListResult. +func (c ClusterListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", c.NextLink) + populate(objectMap, "value", c.Value) + return json.Marshal(objectMap) +} + +// ClusterProperties - The properties associated with a Stream Analytics cluster. +type ClusterProperties struct { + // READ-ONLY; Represents the number of streaming units currently being used on the cluster. + CapacityAllocated *int32 `json:"capacityAllocated,omitempty" azure:"ro"` + + // READ-ONLY; Represents the sum of the SUs of all streaming jobs associated with the cluster. If all of the jobs were running, this would be the capacity + // allocated. + CapacityAssigned *int32 `json:"capacityAssigned,omitempty" azure:"ro"` + + // READ-ONLY; Unique identifier for the cluster. + ClusterID *string `json:"clusterId,omitempty" azure:"ro"` + + // READ-ONLY; The date this cluster was created. + CreatedDate *time.Time `json:"createdDate,omitempty" azure:"ro"` + + // READ-ONLY; The status of the cluster provisioning. The three terminal states are: Succeeded, Failed and Canceled + ProvisioningState *ClusterProvisioningState `json:"provisioningState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type ClusterProperties. +func (c ClusterProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "capacityAllocated", c.CapacityAllocated) + populate(objectMap, "capacityAssigned", c.CapacityAssigned) + populate(objectMap, "clusterId", c.ClusterID) + populate(objectMap, "createdDate", (*timeRFC3339)(c.CreatedDate)) + populate(objectMap, "provisioningState", c.ProvisioningState) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ClusterProperties. +func (c *ClusterProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "capacityAllocated": + err = unpopulate(val, &c.CapacityAllocated) + delete(rawMsg, key) + case "capacityAssigned": + err = unpopulate(val, &c.CapacityAssigned) + delete(rawMsg, key) + case "clusterId": + err = unpopulate(val, &c.ClusterID) + delete(rawMsg, key) + case "createdDate": + var aux timeRFC3339 + err = unpopulate(val, &aux) + c.CreatedDate = (*time.Time)(&aux) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &c.ProvisioningState) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ClusterSKU - The SKU of the cluster. This determines the size/capacity of the cluster. Required on PUT (CreateOrUpdate) requests. +type ClusterSKU struct { + // Denotes the number of streaming units the cluster can support. Valid values for this property are multiples of 36 with a minimum value of 36 and maximum + // value of 216. Required on PUT (CreateOrUpdate) + // requests. + Capacity *int32 `json:"capacity,omitempty"` + + // Specifies the SKU name of the cluster. Required on PUT (CreateOrUpdate) requests. + Name *ClusterSKUName `json:"name,omitempty"` +} + +// ClustersBeginCreateOrUpdateOptions contains the optional parameters for the Clusters.BeginCreateOrUpdate method. +type ClustersBeginCreateOrUpdateOptions struct { + // The ETag of the resource. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string + // Set to '*' to allow a new resource to be created, but to prevent updating an existing record set. Other values will result in a 412 Pre-condition Failed + // response. + IfNoneMatch *string +} + +// ClustersBeginDeleteOptions contains the optional parameters for the Clusters.BeginDelete method. +type ClustersBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// ClustersBeginUpdateOptions contains the optional parameters for the Clusters.BeginUpdate method. +type ClustersBeginUpdateOptions struct { + // The ETag of the resource. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string +} + +// ClustersGetOptions contains the optional parameters for the Clusters.Get method. +type ClustersGetOptions struct { + // placeholder for future optional parameters +} + +// ClustersListByResourceGroupOptions contains the optional parameters for the Clusters.ListByResourceGroup method. +type ClustersListByResourceGroupOptions struct { + // placeholder for future optional parameters +} + +// ClustersListBySubscriptionOptions contains the optional parameters for the Clusters.ListBySubscription method. +type ClustersListBySubscriptionOptions struct { + // placeholder for future optional parameters +} + +// ClustersListStreamingJobsOptions contains the optional parameters for the Clusters.ListStreamingJobs method. +type ClustersListStreamingJobsOptions struct { + // placeholder for future optional parameters +} + +// CompileQuery - The query compilation object which defines the input, output, and transformation for the query compilation. +type CompileQuery struct { + // REQUIRED; Describes the type of the job. Valid values are Cloud and 'Edge'. + JobType *JobType `json:"jobType,omitempty"` + + // REQUIRED; The query to compile. + Query *string `json:"query,omitempty"` + + // The query to compile. + CompatibilityLevel *CompatibilityLevel `json:"compatibilityLevel,omitempty"` + + // The functions for the query compilation. + Functions []*QueryFunction `json:"functions,omitempty"` + + // The inputs for the query compilation. + Inputs []*QueryInput `json:"inputs,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CompileQuery. +func (c CompileQuery) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "compatibilityLevel", c.CompatibilityLevel) + populate(objectMap, "functions", c.Functions) + populate(objectMap, "inputs", c.Inputs) + populate(objectMap, "jobType", c.JobType) + populate(objectMap, "query", c.Query) + return json.Marshal(objectMap) +} + +// Compression - Describes how input data is compressed +type Compression struct { + // REQUIRED + Type *string `json:"type,omitempty"` +} + +// CustomClrSerialization - Describes how data from an input is serialized or how data is serialized when written to an output in custom format. +type CustomClrSerialization struct { + Serialization + // The properties that are associated with the CustomClr serialization type. Required on PUT (CreateOrReplace) requests. + Properties *CustomClrSerializationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type CustomClrSerialization. +func (c CustomClrSerialization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + c.Serialization.marshalInternal(objectMap, EventSerializationTypeCustomClr) + populate(objectMap, "properties", c.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type CustomClrSerialization. +func (c *CustomClrSerialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &c.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := c.Serialization.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// CustomClrSerializationProperties - The properties that are associated with the CustomClr serialization type. +type CustomClrSerializationProperties struct { + // The serialization class name. + SerializationClassName *string `json:"serializationClassName,omitempty"` + + // The serialization library path. + SerializationDllPath *string `json:"serializationDllPath,omitempty"` +} + +// DiagnosticCondition - Condition applicable to the resource, or to the job overall, that warrant customer attention. +type DiagnosticCondition struct { + // READ-ONLY; The opaque diagnostic code. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; The human-readable message describing the condition in detail. Localized in the Accept-Language of the client request. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; The UTC timestamp of when the condition started. Customers should be able to find a corresponding event in the ops log around this time. + Since *string `json:"since,omitempty" azure:"ro"` +} + +// Diagnostics - Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. +type Diagnostics struct { + // READ-ONLY; A collection of zero or more conditions applicable to the resource, or to the job overall, that warrant customer attention. + Conditions []*DiagnosticCondition `json:"conditions,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Diagnostics. +func (d Diagnostics) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "conditions", d.Conditions) + return json.Marshal(objectMap) +} + +// DocumentDbOutputDataSource - Describes a DocumentDB output data source. +type DocumentDbOutputDataSource struct { + OutputDataSource + // The properties that are associated with a DocumentDB output. Required on PUT (CreateOrReplace) requests. + Properties *DocumentDbOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type DocumentDbOutputDataSource. +func (d DocumentDbOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + d.OutputDataSource.marshalInternal(objectMap, "Microsoft.Storage/DocumentDB") + populate(objectMap, "properties", d.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type DocumentDbOutputDataSource. +func (d *DocumentDbOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &d.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := d.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// DocumentDbOutputDataSourceProperties - The properties that are associated with a DocumentDB output. +type DocumentDbOutputDataSourceProperties struct { + // The DocumentDB account name or ID. Required on PUT (CreateOrReplace) requests. + AccountID *string `json:"accountId,omitempty"` + + // The account key for the DocumentDB account. Required on PUT (CreateOrReplace) requests. + AccountKey *string `json:"accountKey,omitempty"` + + // The collection name pattern for the collections to be used. The collection name format can be constructed using the optional {partition} token, where + // partitions start from 0. See the DocumentDB + // section of https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for more information. Required on PUT (CreateOrReplace) + // requests. + CollectionNamePattern *string `json:"collectionNamePattern,omitempty"` + + // The name of the DocumentDB database. Required on PUT (CreateOrReplace) requests. + Database *string `json:"database,omitempty"` + + // The name of the field in output events used to specify the primary key which insert or update operations are based on. + DocumentID *string `json:"documentId,omitempty"` + + // The name of the field in output events used to specify the key for partitioning output across collections. If 'collectionNamePattern' contains the {partition} + // token, this property is required to be + // specified. + PartitionKey *string `json:"partitionKey,omitempty"` +} + +// Error - Common error representation. +// Implements the error and azcore.HTTPResponse interfaces. +type Error struct { + raw string + // Error definition properties. + InnerError *ErrorError `json:"error,omitempty"` +} + +// Error implements the error interface for type Error. +// The contents of the error text are not contractual and subject to change. +func (e Error) Error() string { + return e.raw +} + +// ErrorDetails - Common error details representation. +type ErrorDetails struct { + // Error code. + Code *string `json:"code,omitempty"` + + // Error message. + Message *string `json:"message,omitempty"` + + // Error target. + Target *string `json:"target,omitempty"` +} + +// ErrorError - Error definition properties. +type ErrorError struct { + // Error code. + Code *string `json:"code,omitempty"` + + // Error details. + Details []*ErrorDetails `json:"details,omitempty"` + + // Error message. + Message *string `json:"message,omitempty"` + + // Error target. + Target *string `json:"target,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ErrorError. +func (e ErrorError) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "code", e.Code) + populate(objectMap, "details", e.Details) + populate(objectMap, "message", e.Message) + populate(objectMap, "target", e.Target) + return json.Marshal(objectMap) +} + +// ErrorResponse - Describes the error that occurred. +type ErrorResponse struct { + // READ-ONLY; Error code associated with the error that occurred. + Code *string `json:"code,omitempty" azure:"ro"` + + // READ-ONLY; Describes the error in detail. + Message *string `json:"message,omitempty" azure:"ro"` +} + +// EventHubDataSourceProperties - The common properties that are associated with Event Hub data sources. +type EventHubDataSourceProperties struct { + ServiceBusDataSourceProperties + // The name of the Event Hub. Required on PUT (CreateOrReplace) requests. + EventHubName *string `json:"eventHubName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubDataSourceProperties. +func (e EventHubDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (e EventHubDataSourceProperties) marshalInternal(objectMap map[string]interface{}) { + e.ServiceBusDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "eventHubName", e.EventHubName) +} + +// EventHubOutputDataSource - Describes an Event Hub output data source. +type EventHubOutputDataSource struct { + OutputDataSource + // The properties that are associated with an Event Hub output. Required on PUT (CreateOrReplace) requests. + Properties *EventHubOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubOutputDataSource. +func (e EventHubOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.OutputDataSource.marshalInternal(objectMap, "Microsoft.ServiceBus/EventHub") + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventHubOutputDataSource. +func (e *EventHubOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &e.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := e.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// EventHubOutputDataSourceProperties - The properties that are associated with an Event Hub output. +type EventHubOutputDataSourceProperties struct { + EventHubDataSourceProperties + // The key/column that is used to determine to which partition to send event data. + PartitionKey *string `json:"partitionKey,omitempty"` + PropertyColumns []*string `json:"propertyColumns,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubOutputDataSourceProperties. +func (e EventHubOutputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.EventHubDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "partitionKey", e.PartitionKey) + populate(objectMap, "propertyColumns", e.PropertyColumns) + return json.Marshal(objectMap) +} + +// EventHubStreamInputDataSource - Describes an Event Hub input data source that contains stream data. +type EventHubStreamInputDataSource struct { + StreamInputDataSource + // The properties that are associated with an Event Hub input containing stream data. Required on PUT (CreateOrReplace) requests. + Properties *EventHubStreamInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubStreamInputDataSource. +func (e EventHubStreamInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.StreamInputDataSource.marshalInternal(objectMap, "Microsoft.ServiceBus/EventHub") + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventHubStreamInputDataSource. +func (e *EventHubStreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &e.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := e.StreamInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// EventHubStreamInputDataSourceProperties - The properties that are associated with a Event Hub input containing stream data. +type EventHubStreamInputDataSourceProperties struct { + EventHubDataSourceProperties + // The name of an Event Hub Consumer Group that should be used to read events from the Event Hub. Specifying distinct consumer group names for multiple + // inputs allows each of those inputs to receive the + // same events from the Event Hub. If not specified, the input uses the Event Hub’s default consumer group. + ConsumerGroupName *string `json:"consumerGroupName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubStreamInputDataSourceProperties. +func (e EventHubStreamInputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.EventHubDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "consumerGroupName", e.ConsumerGroupName) + return json.Marshal(objectMap) +} + +// EventHubV2OutputDataSource - Describes an Event Hub output data source. +type EventHubV2OutputDataSource struct { + OutputDataSource + // The properties that are associated with an Event Hub output. Required on PUT (CreateOrReplace) requests. + Properties *EventHubOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubV2OutputDataSource. +func (e EventHubV2OutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.OutputDataSource.marshalInternal(objectMap, "Microsoft.EventHub/EventHub") + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventHubV2OutputDataSource. +func (e *EventHubV2OutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &e.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := e.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// EventHubV2StreamInputDataSource - Describes an Event Hub input data source that contains stream data. +type EventHubV2StreamInputDataSource struct { + StreamInputDataSource + // The properties that are associated with an Event Hub input containing stream data. Required on PUT (CreateOrReplace) requests. + Properties *EventHubStreamInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type EventHubV2StreamInputDataSource. +func (e EventHubV2StreamInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + e.StreamInputDataSource.marshalInternal(objectMap, "Microsoft.EventHub/EventHub") + populate(objectMap, "properties", e.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type EventHubV2StreamInputDataSource. +func (e *EventHubV2StreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &e.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := e.StreamInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// External - The storage account where the custom code artifacts are located. +type External struct { + Container *string `json:"container,omitempty"` + Path *string `json:"path,omitempty"` + + // The properties that are associated with an Azure Storage account + StorageAccount *StorageAccount `json:"storageAccount,omitempty"` +} + +// Function - A function object, containing all information associated with the named function. All functions are contained under a streaming job. +type Function struct { + SubResource + // The properties that are associated with a function. + Properties FunctionPropertiesClassification `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Function. +func (f Function) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + f.SubResource.marshalInternal(objectMap) + populate(objectMap, "properties", f.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Function. +func (f *Function) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + f.Properties, err = unmarshalFunctionPropertiesClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := f.SubResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// FunctionBindingClassification provides polymorphic access to related types. +// Call the interface's GetFunctionBinding() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AzureMachineLearningServiceFunctionBinding, *AzureMachineLearningStudioFunctionBinding, *CSharpFunctionBinding, *FunctionBinding, +// - *JavaScriptFunctionBinding +type FunctionBindingClassification interface { + // GetFunctionBinding returns the FunctionBinding content of the underlying type. + GetFunctionBinding() *FunctionBinding +} + +// FunctionBinding - The physical binding of the function. For example, in the Azure Machine Learning web service’s case, this describes the endpoint. +type FunctionBinding struct { + // REQUIRED; Indicates the function binding type. + Type *string `json:"type,omitempty"` +} + +// GetFunctionBinding implements the FunctionBindingClassification interface for type FunctionBinding. +func (f *FunctionBinding) GetFunctionBinding() *FunctionBinding { return f } + +// UnmarshalJSON implements the json.Unmarshaller interface for type FunctionBinding. +func (f *FunctionBinding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return f.unmarshalInternal(rawMsg) +} + +func (f FunctionBinding) marshalInternal(objectMap map[string]interface{}, discValue string) { + f.Type = &discValue + objectMap["type"] = f.Type +} + +func (f *FunctionBinding) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &f.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +type FunctionConfiguration struct { + // The physical binding of the function. For example, in the Azure Machine Learning web service’s case, this describes the endpoint. + Binding FunctionBindingClassification `json:"binding,omitempty"` + Inputs []*FunctionInput `json:"inputs,omitempty"` + + // Describes the output of a function. + Output *FunctionOutput `json:"output,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type FunctionConfiguration. +func (f FunctionConfiguration) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "binding", f.Binding) + populate(objectMap, "inputs", f.Inputs) + populate(objectMap, "output", f.Output) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FunctionConfiguration. +func (f *FunctionConfiguration) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "binding": + f.Binding, err = unmarshalFunctionBindingClassification(val) + delete(rawMsg, key) + case "inputs": + err = unpopulate(val, &f.Inputs) + delete(rawMsg, key) + case "output": + err = unpopulate(val, &f.Output) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// FunctionInput - Describes one input parameter of a function. +type FunctionInput struct { + // The (Azure Stream Analytics supported) data type of the function input parameter. A list of valid Azure Stream Analytics data types are described at + // https://msdn.microsoft.com/en-us/library/azure/dn835065.aspx + DataType *string `json:"dataType,omitempty"` + + // A flag indicating if the parameter is a configuration parameter. True if this input parameter is expected to be a constant. Default is false. + IsConfigurationParameter *bool `json:"isConfigurationParameter,omitempty"` +} + +// FunctionListResult - Object containing a list of functions under a streaming job. +type FunctionListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of functions under a streaming job. Populated by a 'List' operation. + Value []*Function `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type FunctionListResult. +func (f FunctionListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", f.NextLink) + populate(objectMap, "value", f.Value) + return json.Marshal(objectMap) +} + +// FunctionOutput - Describes the output of a function. +type FunctionOutput struct { + // The (Azure Stream Analytics supported) data type of the function output. A list of valid Azure Stream Analytics data types are described at https://msdn.microsoft.com/en-us/library/azure/dn835065.aspx + DataType *string `json:"dataType,omitempty"` +} + +// FunctionPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetFunctionProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AggregateFunctionProperties, *FunctionProperties, *ScalarFunctionProperties +type FunctionPropertiesClassification interface { + // GetFunctionProperties returns the FunctionProperties content of the underlying type. + GetFunctionProperties() *FunctionProperties +} + +// FunctionProperties - The properties that are associated with a function. +type FunctionProperties struct { + // REQUIRED; Indicates the type of function. + Type *string `json:"type,omitempty"` + Properties *FunctionConfiguration `json:"properties,omitempty"` + + // READ-ONLY; The current entity tag for the function. This is an opaque string. You can use it to detect whether the resource has changed between requests. + // You can also use it in the If-Match or If-None-Match + // headers for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// GetFunctionProperties implements the FunctionPropertiesClassification interface for type FunctionProperties. +func (f *FunctionProperties) GetFunctionProperties() *FunctionProperties { return f } + +// UnmarshalJSON implements the json.Unmarshaller interface for type FunctionProperties. +func (f *FunctionProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return f.unmarshalInternal(rawMsg) +} + +func (f FunctionProperties) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "etag", f.Etag) + populate(objectMap, "properties", f.Properties) + f.Type = &discValue + objectMap["type"] = f.Type +} + +func (f *FunctionProperties) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "etag": + err = unpopulate(val, &f.Etag) + delete(rawMsg, key) + case "properties": + err = unpopulate(val, &f.Properties) + delete(rawMsg, key) + case "type": + err = unpopulate(val, &f.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// FunctionRetrieveDefaultDefinitionParametersClassification provides polymorphic access to related types. +// Call the interface's GetFunctionRetrieveDefaultDefinitionParameters() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters, *AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters, +// - *CSharpFunctionRetrieveDefaultDefinitionParameters, *FunctionRetrieveDefaultDefinitionParameters, *JavaScriptFunctionRetrieveDefaultDefinitionParameters +type FunctionRetrieveDefaultDefinitionParametersClassification interface { + // GetFunctionRetrieveDefaultDefinitionParameters returns the FunctionRetrieveDefaultDefinitionParameters content of the underlying type. + GetFunctionRetrieveDefaultDefinitionParameters() *FunctionRetrieveDefaultDefinitionParameters +} + +// FunctionRetrieveDefaultDefinitionParameters - Parameters used to specify the type of function to retrieve the default definition for. +type FunctionRetrieveDefaultDefinitionParameters struct { + // REQUIRED; Indicates the function binding type. + BindingType *string `json:"bindingType,omitempty"` +} + +// GetFunctionRetrieveDefaultDefinitionParameters implements the FunctionRetrieveDefaultDefinitionParametersClassification interface for type FunctionRetrieveDefaultDefinitionParameters. +func (f *FunctionRetrieveDefaultDefinitionParameters) GetFunctionRetrieveDefaultDefinitionParameters() *FunctionRetrieveDefaultDefinitionParameters { + return f +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type FunctionRetrieveDefaultDefinitionParameters. +func (f *FunctionRetrieveDefaultDefinitionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return f.unmarshalInternal(rawMsg) +} + +func (f FunctionRetrieveDefaultDefinitionParameters) marshalInternal(objectMap map[string]interface{}, discValue string) { + f.BindingType = &discValue + objectMap["bindingType"] = f.BindingType +} + +func (f *FunctionRetrieveDefaultDefinitionParameters) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "bindingType": + err = unpopulate(val, &f.BindingType) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// FunctionsBeginTestOptions contains the optional parameters for the Functions.BeginTest method. +type FunctionsBeginTestOptions struct { + // If the function specified does not already exist, this parameter must contain the full function definition intended to be tested. If the function specified + // already exists, this parameter can be left null to test the existing function as is or if specified, the properties specified will overwrite the corresponding + // properties in the existing function (exactly like a PATCH operation) and the resulting function will be tested. + Function *Function +} + +// FunctionsCreateOrReplaceOptions contains the optional parameters for the Functions.CreateOrReplace method. +type FunctionsCreateOrReplaceOptions struct { + // The ETag of the function. Omit this value to always overwrite the current function. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string + // Set to '*' to allow a new function to be created, but to prevent updating an existing function. Other values will result in a 412 Pre-condition Failed + // response. + IfNoneMatch *string +} + +// FunctionsDeleteOptions contains the optional parameters for the Functions.Delete method. +type FunctionsDeleteOptions struct { + // placeholder for future optional parameters +} + +// FunctionsGetOptions contains the optional parameters for the Functions.Get method. +type FunctionsGetOptions struct { + // placeholder for future optional parameters +} + +// FunctionsListByStreamingJobOptions contains the optional parameters for the Functions.ListByStreamingJob method. +type FunctionsListByStreamingJobOptions struct { + // The $select OData query parameter. This is a comma-separated list of structural properties to include in the response, or "*" to include all properties. + // By default, all properties are returned except diagnostics. Currently only accepts '*' as a valid value. + Select *string +} + +// FunctionsRetrieveDefaultDefinitionOptions contains the optional parameters for the Functions.RetrieveDefaultDefinition method. +type FunctionsRetrieveDefaultDefinitionOptions struct { + // Parameters used to specify the type of function to retrieve the default definition for. + FunctionRetrieveDefaultDefinitionParameters FunctionRetrieveDefaultDefinitionParametersClassification +} + +// FunctionsUpdateOptions contains the optional parameters for the Functions.Update method. +type FunctionsUpdateOptions struct { + // The ETag of the function. Omit this value to always overwrite the current function. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string +} + +// Identity - Describes how identity is verified +type Identity struct { + PrincipalID *string `json:"principalId,omitempty"` + TenantID *string `json:"tenantId,omitempty"` + Type *string `json:"type,omitempty"` +} + +// Input - An input object, containing all information associated with the named input. All inputs are contained under a streaming job. +type Input struct { + SubResource + // The properties that are associated with an input. Required on PUT (CreateOrReplace) requests. + Properties InputPropertiesClassification `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Input. +func (i Input) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + i.SubResource.marshalInternal(objectMap) + populate(objectMap, "properties", i.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Input. +func (i *Input) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + i.Properties, err = unmarshalInputPropertiesClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := i.SubResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// InputListResult - Object containing a list of inputs under a streaming job. +type InputListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of inputs under a streaming job. Populated by a 'List' operation. + Value []*Input `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type InputListResult. +func (i InputListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", i.NextLink) + populate(objectMap, "value", i.Value) + return json.Marshal(objectMap) +} + +// InputPropertiesClassification provides polymorphic access to related types. +// Call the interface's GetInputProperties() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *InputProperties, *ReferenceInputProperties, *StreamInputProperties +type InputPropertiesClassification interface { + // GetInputProperties returns the InputProperties content of the underlying type. + GetInputProperties() *InputProperties +} + +// InputProperties - The properties that are associated with an input. +type InputProperties struct { + // REQUIRED; Indicates whether the input is a source of reference data or stream data. Required on PUT (CreateOrReplace) requests. + Type *string `json:"type,omitempty"` + + // Describes how input data is compressed + Compression *Compression `json:"compression,omitempty"` + + // partitionKey Describes a key in the input data which is used for partitioning the input data + PartitionKey *string `json:"partitionKey,omitempty"` + + // Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. + Serialization SerializationClassification `json:"serialization,omitempty"` + + // READ-ONLY; Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. + Diagnostics *Diagnostics `json:"diagnostics,omitempty" azure:"ro"` + + // READ-ONLY; The current entity tag for the input. This is an opaque string. You can use it to detect whether the resource has changed between requests. + // You can also use it in the If-Match or If-None-Match headers + // for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// GetInputProperties implements the InputPropertiesClassification interface for type InputProperties. +func (i *InputProperties) GetInputProperties() *InputProperties { return i } + +// UnmarshalJSON implements the json.Unmarshaller interface for type InputProperties. +func (i *InputProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return i.unmarshalInternal(rawMsg) +} + +func (i InputProperties) marshalInternal(objectMap map[string]interface{}, discValue string) { + populate(objectMap, "compression", i.Compression) + populate(objectMap, "diagnostics", i.Diagnostics) + populate(objectMap, "etag", i.Etag) + populate(objectMap, "partitionKey", i.PartitionKey) + populate(objectMap, "serialization", i.Serialization) + i.Type = &discValue + objectMap["type"] = i.Type +} + +func (i *InputProperties) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "compression": + err = unpopulate(val, &i.Compression) + delete(rawMsg, key) + case "diagnostics": + err = unpopulate(val, &i.Diagnostics) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, &i.Etag) + delete(rawMsg, key) + case "partitionKey": + err = unpopulate(val, &i.PartitionKey) + delete(rawMsg, key) + case "serialization": + i.Serialization, err = unmarshalSerializationClassification(val) + delete(rawMsg, key) + case "type": + err = unpopulate(val, &i.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// InputsBeginTestOptions contains the optional parameters for the Inputs.BeginTest method. +type InputsBeginTestOptions struct { + // If the input specified does not already exist, this parameter must contain the full input definition intended to be tested. If the input specified already + // exists, this parameter can be left null to test the existing input as is or if specified, the properties specified will overwrite the corresponding properties + // in the existing input (exactly like a PATCH operation) and the resulting input will be tested. + Input *Input +} + +// InputsCreateOrReplaceOptions contains the optional parameters for the Inputs.CreateOrReplace method. +type InputsCreateOrReplaceOptions struct { + // The ETag of the input. Omit this value to always overwrite the current input. Specify the last-seen ETag value to prevent accidentally overwriting concurrent + // changes. + IfMatch *string + // Set to '*' to allow a new input to be created, but to prevent updating an existing input. Other values will result in a 412 Pre-condition Failed response. + IfNoneMatch *string +} + +// InputsDeleteOptions contains the optional parameters for the Inputs.Delete method. +type InputsDeleteOptions struct { + // placeholder for future optional parameters +} + +// InputsGetOptions contains the optional parameters for the Inputs.Get method. +type InputsGetOptions struct { + // placeholder for future optional parameters +} + +// InputsListByStreamingJobOptions contains the optional parameters for the Inputs.ListByStreamingJob method. +type InputsListByStreamingJobOptions struct { + // The $select OData query parameter. This is a comma-separated list of structural properties to include in the response, or "*" to include all properties. + // By default, all properties are returned except diagnostics. Currently only accepts '*' as a valid value. + Select *string +} + +// InputsUpdateOptions contains the optional parameters for the Inputs.Update method. +type InputsUpdateOptions struct { + // The ETag of the input. Omit this value to always overwrite the current input. Specify the last-seen ETag value to prevent accidentally overwriting concurrent + // changes. + IfMatch *string +} + +// IoTHubStreamInputDataSource - Describes an IoT Hub input data source that contains stream data. +type IoTHubStreamInputDataSource struct { + StreamInputDataSource + // The properties that are associated with an IoT Hub input containing stream data. Required on PUT (CreateOrReplace) requests. + Properties *IoTHubStreamInputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type IoTHubStreamInputDataSource. +func (i IoTHubStreamInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + i.StreamInputDataSource.marshalInternal(objectMap, "Microsoft.Devices/IotHubs") + populate(objectMap, "properties", i.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type IoTHubStreamInputDataSource. +func (i *IoTHubStreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &i.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := i.StreamInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// IoTHubStreamInputDataSourceProperties - The properties that are associated with a IoT Hub input containing stream data. +type IoTHubStreamInputDataSourceProperties struct { + // The name of an IoT Hub Consumer Group that should be used to read events from the IoT Hub. If not specified, the input uses the Iot Hub’s default consumer + // group. + ConsumerGroupName *string `json:"consumerGroupName,omitempty"` + + // The IoT Hub endpoint to connect to (ie. messages/events, messages/operationsMonitoringEvents, etc.). + Endpoint *string `json:"endpoint,omitempty"` + + // The name or the URI of the IoT Hub. Required on PUT (CreateOrReplace) requests. + IotHubNamespace *string `json:"iotHubNamespace,omitempty"` + + // The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. + SharedAccessPolicyKey *string `json:"sharedAccessPolicyKey,omitempty"` + + // The shared access policy name for the IoT Hub. This policy must contain at least the Service connect permission. Required on PUT (CreateOrReplace) requests. + SharedAccessPolicyName *string `json:"sharedAccessPolicyName,omitempty"` +} + +// JSONSerialization - Describes how data from an input is serialized or how data is serialized when written to an output in JSON format. +type JSONSerialization struct { + Serialization + // The properties that are associated with the JSON serialization type. Required on PUT (CreateOrReplace) requests. + Properties *JSONSerializationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JSONSerialization. +func (j JSONSerialization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.Serialization.marshalInternal(objectMap, EventSerializationTypeJSON) + populate(objectMap, "properties", j.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JSONSerialization. +func (j *JSONSerialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &j.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.Serialization.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JSONSerializationProperties - The properties that are associated with the JSON serialization type. +type JSONSerializationProperties struct { + // Specifies the encoding of the incoming data in the case of input and the encoding of outgoing data in the case of output. Required on PUT (CreateOrReplace) + // requests. + Encoding *Encoding `json:"encoding,omitempty"` + + // This property only applies to JSON serialization of outputs only. It is not applicable to inputs. This property specifies the format of the JSON the + // output will be written in. The currently supported + // values are 'lineSeparated' indicating the output will be formatted by having each JSON object separated by a new line and 'array' indicating the output + // will be formatted as an array of JSON objects. + // Default value is 'lineSeparated' if left null. + Format *JSONOutputSerializationFormat `json:"format,omitempty"` +} + +// JavaScriptFunctionBinding - The binding to a JavaScript function. +type JavaScriptFunctionBinding struct { + FunctionBinding + // The binding properties associated with a JavaScript function. + Properties *JavaScriptFunctionBindingProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JavaScriptFunctionBinding. +func (j JavaScriptFunctionBinding) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.FunctionBinding.marshalInternal(objectMap, "Microsoft.StreamAnalytics/JavascriptUdf") + populate(objectMap, "properties", j.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JavaScriptFunctionBinding. +func (j *JavaScriptFunctionBinding) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &j.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.FunctionBinding.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JavaScriptFunctionBindingProperties - The binding properties associated with a JavaScript function. +type JavaScriptFunctionBindingProperties struct { + // The JavaScript code containing a single function definition. For example: 'function (x, y) { return x + y; }' + Script *string `json:"script,omitempty"` +} + +// JavaScriptFunctionBindingRetrievalProperties - The binding retrieval properties associated with a JavaScript function. +type JavaScriptFunctionBindingRetrievalProperties struct { + // The JavaScript code containing a single function definition. For example: 'function (x, y) { return x + y; }'. + Script *string `json:"script,omitempty"` + + // The function type. + UdfType *string `json:"udfType,omitempty"` +} + +// JavaScriptFunctionRetrieveDefaultDefinitionParameters - The parameters needed to retrieve the default function definition for a JavaScript function. +type JavaScriptFunctionRetrieveDefaultDefinitionParameters struct { + FunctionRetrieveDefaultDefinitionParameters + // The binding retrieval properties associated with a JavaScript function. + BindingRetrievalProperties *JavaScriptFunctionBindingRetrievalProperties `json:"bindingRetrievalProperties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type JavaScriptFunctionRetrieveDefaultDefinitionParameters. +func (j JavaScriptFunctionRetrieveDefaultDefinitionParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + j.FunctionRetrieveDefaultDefinitionParameters.marshalInternal(objectMap, "Microsoft.StreamAnalytics/JavascriptUdf") + populate(objectMap, "bindingRetrievalProperties", j.BindingRetrievalProperties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type JavaScriptFunctionRetrieveDefaultDefinitionParameters. +func (j *JavaScriptFunctionRetrieveDefaultDefinitionParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "bindingRetrievalProperties": + err = unpopulate(val, &j.BindingRetrievalProperties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := j.FunctionRetrieveDefaultDefinitionParameters.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// JobStorageAccount - The properties that are associated with an Azure Storage account with MSI +type JobStorageAccount struct { + StorageAccount + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` +} + +// OAuthBasedDataSourceProperties - The properties that are associated with data sources that use OAuth as their authentication model. +type OAuthBasedDataSourceProperties struct { + // A refresh token that can be used to obtain a valid access token that can then be used to authenticate with the data source. A valid refresh token is + // currently only obtainable via the Azure Portal. It + // is recommended to put a dummy string value here when creating the data source and then going to the Azure Portal to authenticate the data source which + // will update this property with a valid refresh + // token. Required on PUT (CreateOrReplace) requests. + RefreshToken *string `json:"refreshToken,omitempty"` + + // The user display name of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh + // token. + TokenUserDisplayName *string `json:"tokenUserDisplayName,omitempty"` + + // The user principal name (UPN) of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain + // the refresh token. + TokenUserPrincipalName *string `json:"tokenUserPrincipalName,omitempty"` +} + +// Operation - A Stream Analytics REST API operation +type Operation struct { + // READ-ONLY; Contains the localized display information for this particular operation / action. + Display *OperationDisplay `json:"display,omitempty" azure:"ro"` + + // READ-ONLY; The name of the operation being performed on this particular object. + Name *string `json:"name,omitempty" azure:"ro"` +} + +// OperationDisplay - Contains the localized display information for this particular operation / action. +type OperationDisplay struct { + // READ-ONLY; The localized friendly description for the operation. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; The localized friendly name for the operation. + Operation *string `json:"operation,omitempty" azure:"ro"` + + // READ-ONLY; The localized friendly form of the resource provider name. + Provider *string `json:"provider,omitempty" azure:"ro"` + + // READ-ONLY; The localized friendly form of the resource type related to this action/operation. + Resource *string `json:"resource,omitempty" azure:"ro"` +} + +// OperationListResult - Result of the request to list Stream Analytics operations. It contains a list of operations and a URL link to get the next set +// of results. +type OperationListResult struct { + // READ-ONLY; URL to get the next set of operation list results if there are any. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; List of Stream Analytics operations supported by the Microsoft.StreamAnalytics resource provider. + Value []*Operation `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OperationListResult. +func (o OperationListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OperationsListOptions contains the optional parameters for the Operations.List method. +type OperationsListOptions struct { + // placeholder for future optional parameters +} + +// Output - An output object, containing all information associated with the named output. All outputs are contained under a streaming job. +type Output struct { + SubResource + // The properties that are associated with an output. Required on PUT (CreateOrReplace) requests. + Properties *OutputProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Output. +func (o Output) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + o.SubResource.marshalInternal(objectMap) + populate(objectMap, "properties", o.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Output. +func (o *Output) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &o.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := o.SubResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// OutputDataSourceClassification provides polymorphic access to related types. +// Call the interface's GetOutputDataSource() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AzureDataLakeStoreOutputDataSource, *AzureFunctionOutputDataSource, *AzureSqlDatabaseOutputDataSource, *AzureSynapseOutputDataSource, +// - *AzureTableOutputDataSource, *BlobOutputDataSource, *DocumentDbOutputDataSource, *EventHubOutputDataSource, *EventHubV2OutputDataSource, +// - *OutputDataSource, *PowerBIOutputDataSource, *RawOutputDatasource, *ServiceBusQueueOutputDataSource, *ServiceBusTopicOutputDataSource +type OutputDataSourceClassification interface { + // GetOutputDataSource returns the OutputDataSource content of the underlying type. + GetOutputDataSource() *OutputDataSource +} + +// OutputDataSource - Describes the data source that output will be written to. +type OutputDataSource struct { + // REQUIRED; Indicates the type of data source output will be written to. Required on PUT (CreateOrReplace) requests. + Type *string `json:"type,omitempty"` +} + +// GetOutputDataSource implements the OutputDataSourceClassification interface for type OutputDataSource. +func (o *OutputDataSource) GetOutputDataSource() *OutputDataSource { return o } + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputDataSource. +func (o *OutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return o.unmarshalInternal(rawMsg) +} + +func (o OutputDataSource) marshalInternal(objectMap map[string]interface{}, discValue string) { + o.Type = &discValue + objectMap["type"] = o.Type +} + +func (o *OutputDataSource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &o.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// OutputListResult - Object containing a list of outputs under a streaming job. +type OutputListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of outputs under a streaming job. Populated by a 'List' operation. + Value []*Output `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OutputListResult. +func (o OutputListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", o.NextLink) + populate(objectMap, "value", o.Value) + return json.Marshal(objectMap) +} + +// OutputProperties - The properties that are associated with an output. +type OutputProperties struct { + // Describes the data source that output will be written to. Required on PUT (CreateOrReplace) requests. + Datasource OutputDataSourceClassification `json:"datasource,omitempty"` + + // Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. + Serialization SerializationClassification `json:"serialization,omitempty"` + SizeWindow *float32 `json:"sizeWindow,omitempty"` + TimeWindow *string `json:"timeWindow,omitempty"` + + // READ-ONLY; Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. + Diagnostics *Diagnostics `json:"diagnostics,omitempty" azure:"ro"` + + // READ-ONLY; The current entity tag for the output. This is an opaque string. You can use it to detect whether the resource has changed between requests. + // You can also use it in the If-Match or If-None-Match + // headers for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type OutputProperties. +func (o OutputProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "datasource", o.Datasource) + populate(objectMap, "diagnostics", o.Diagnostics) + populate(objectMap, "etag", o.Etag) + populate(objectMap, "serialization", o.Serialization) + populate(objectMap, "sizeWindow", o.SizeWindow) + populate(objectMap, "timeWindow", o.TimeWindow) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type OutputProperties. +func (o *OutputProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "datasource": + o.Datasource, err = unmarshalOutputDataSourceClassification(val) + delete(rawMsg, key) + case "diagnostics": + err = unpopulate(val, &o.Diagnostics) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, &o.Etag) + delete(rawMsg, key) + case "serialization": + o.Serialization, err = unmarshalSerializationClassification(val) + delete(rawMsg, key) + case "sizeWindow": + err = unpopulate(val, &o.SizeWindow) + delete(rawMsg, key) + case "timeWindow": + err = unpopulate(val, &o.TimeWindow) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// OutputsBeginTestOptions contains the optional parameters for the Outputs.BeginTest method. +type OutputsBeginTestOptions struct { + // If the output specified does not already exist, this parameter must contain the full output definition intended to be tested. If the output specified + // already exists, this parameter can be left null to test the existing output as is or if specified, the properties specified will overwrite the corresponding + // properties in the existing output (exactly like a PATCH operation) and the resulting output will be tested. + Output *Output +} + +// OutputsCreateOrReplaceOptions contains the optional parameters for the Outputs.CreateOrReplace method. +type OutputsCreateOrReplaceOptions struct { + // The ETag of the output. Omit this value to always overwrite the current output. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string + // Set to '*' to allow a new output to be created, but to prevent updating an existing output. Other values will result in a 412 Pre-condition Failed response. + IfNoneMatch *string +} + +// OutputsDeleteOptions contains the optional parameters for the Outputs.Delete method. +type OutputsDeleteOptions struct { + // placeholder for future optional parameters +} + +// OutputsGetOptions contains the optional parameters for the Outputs.Get method. +type OutputsGetOptions struct { + // placeholder for future optional parameters +} + +// OutputsListByStreamingJobOptions contains the optional parameters for the Outputs.ListByStreamingJob method. +type OutputsListByStreamingJobOptions struct { + // The $select OData query parameter. This is a comma-separated list of structural properties to include in the response, or "*" to include all properties. + // By default, all properties are returned except diagnostics. Currently only accepts '*' as a valid value. + Select *string +} + +// OutputsUpdateOptions contains the optional parameters for the Outputs.Update method. +type OutputsUpdateOptions struct { + // The ETag of the output. Omit this value to always overwrite the current output. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string +} + +// ParquetSerialization - Describes how data from an input is serialized or how data is serialized when written to an output in Parquet format. +type ParquetSerialization struct { + Serialization + // The properties that are associated with the Parquet serialization type. Required on PUT (CreateOrReplace) requests. + Properties map[string]interface{} `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ParquetSerialization. +func (p ParquetSerialization) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.Serialization.marshalInternal(objectMap, EventSerializationTypeParquet) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ParquetSerialization. +func (p *ParquetSerialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := p.Serialization.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// PowerBIOutputDataSource - Describes a Power BI output data source. +type PowerBIOutputDataSource struct { + OutputDataSource + // The properties that are associated with a Power BI output. Required on PUT (CreateOrReplace) requests. + Properties *PowerBIOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PowerBIOutputDataSource. +func (p PowerBIOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.OutputDataSource.marshalInternal(objectMap, "PowerBI") + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type PowerBIOutputDataSource. +func (p *PowerBIOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &p.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := p.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// PowerBIOutputDataSourceProperties - The properties that are associated with a Power BI output. +type PowerBIOutputDataSourceProperties struct { + OAuthBasedDataSourceProperties + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` + + // The name of the Power BI dataset. Required on PUT (CreateOrReplace) requests. + Dataset *string `json:"dataset,omitempty"` + + // The ID of the Power BI group. + GroupID *string `json:"groupId,omitempty"` + + // The name of the Power BI group. Use this property to help remember which specific Power BI group id was used. + GroupName *string `json:"groupName,omitempty"` + + // The name of the Power BI table under the specified dataset. Required on PUT (CreateOrReplace) requests. + Table *string `json:"table,omitempty"` +} + +// PrivateEndpoint - Complete information about the private endpoint. +type PrivateEndpoint struct { + ProxyResource + // The properties associated with a private endpoint. + Properties *PrivateEndpointProperties `json:"properties,omitempty"` + + // READ-ONLY; Unique opaque string (generally a GUID) that represents the metadata state of the resource (private endpoint) and changes whenever the resource + // is updated. Required on PUT (CreateOrUpdate) requests. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpoint. +func (p PrivateEndpoint) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + p.ProxyResource.marshalInternal(objectMap) + populate(objectMap, "etag", p.Etag) + populate(objectMap, "properties", p.Properties) + return json.Marshal(objectMap) +} + +// PrivateEndpointListResult - A list of private endpoints. +type PrivateEndpointListResult struct { + // READ-ONLY; The URL to fetch the next set of private endpoints. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of private endpoints. + Value []*PrivateEndpoint `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointListResult. +func (p PrivateEndpointListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", p.NextLink) + populate(objectMap, "value", p.Value) + return json.Marshal(objectMap) +} + +// PrivateEndpointProperties - The properties associated with a private endpoint. +type PrivateEndpointProperties struct { + // A list of connections to the remote resource. Immutable after it is set. + ManualPrivateLinkServiceConnections []*PrivateLinkServiceConnection `json:"manualPrivateLinkServiceConnections,omitempty"` + + // READ-ONLY; The date when this private endpoint was created. + CreatedDate *string `json:"createdDate,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateEndpointProperties. +func (p PrivateEndpointProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "createdDate", p.CreatedDate) + populate(objectMap, "manualPrivateLinkServiceConnections", p.ManualPrivateLinkServiceConnections) + return json.Marshal(objectMap) +} + +// PrivateEndpointsBeginDeleteOptions contains the optional parameters for the PrivateEndpoints.BeginDelete method. +type PrivateEndpointsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointsCreateOrUpdateOptions contains the optional parameters for the PrivateEndpoints.CreateOrUpdate method. +type PrivateEndpointsCreateOrUpdateOptions struct { + // The ETag of the resource. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string + // Set to '*' to allow a new resource to be created, but to prevent updating an existing record set. Other values will result in a 412 Pre-condition Failed + // response. + IfNoneMatch *string +} + +// PrivateEndpointsGetOptions contains the optional parameters for the PrivateEndpoints.Get method. +type PrivateEndpointsGetOptions struct { + // placeholder for future optional parameters +} + +// PrivateEndpointsListByClusterOptions contains the optional parameters for the PrivateEndpoints.ListByCluster method. +type PrivateEndpointsListByClusterOptions struct { + // placeholder for future optional parameters +} + +// PrivateLinkConnectionState - A collection of read-only information about the state of the connection to the private remote resource. +type PrivateLinkConnectionState struct { + // READ-ONLY; A message indicating if changes on the service provider require any updates on the consumer. + ActionsRequired *string `json:"actionsRequired,omitempty" azure:"ro"` + + // READ-ONLY; The reason for approval/rejection of the connection. + Description *string `json:"description,omitempty" azure:"ro"` + + // READ-ONLY; Indicates whether the connection has been Approved/Rejected/Removed by the owner of the remote resource/service. + Status *string `json:"status,omitempty" azure:"ro"` +} + +// PrivateLinkServiceConnection - A grouping of information about the connection to the remote resource. +type PrivateLinkServiceConnection struct { + // Bag of properties defining a privatelinkServiceConnection. + Properties *PrivateLinkServiceConnectionProperties `json:"properties,omitempty"` +} + +// PrivateLinkServiceConnectionProperties - Bag of properties defining a privatelinkServiceConnection. +type PrivateLinkServiceConnectionProperties struct { + // The ID(s) of the group(s) obtained from the remote resource that this private endpoint should connect to. Required on PUT (CreateOrUpdate) requests. + GroupIDs []*string `json:"groupIds,omitempty"` + + // A collection of read-only information about the state of the connection to the private remote resource. + PrivateLinkServiceConnectionState *PrivateLinkConnectionState `json:"privateLinkServiceConnectionState,omitempty"` + + // The resource id of the private link service. Required on PUT (CreateOrUpdate) requests. + PrivateLinkServiceID *string `json:"privateLinkServiceId,omitempty"` + + // A message passed to the owner of the remote resource with this connection request. Restricted to 140 chars. + RequestMessage *string `json:"requestMessage,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type PrivateLinkServiceConnectionProperties. +func (p PrivateLinkServiceConnectionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "groupIds", p.GroupIDs) + populate(objectMap, "privateLinkServiceConnectionState", p.PrivateLinkServiceConnectionState) + populate(objectMap, "privateLinkServiceId", p.PrivateLinkServiceID) + populate(objectMap, "requestMessage", p.RequestMessage) + return json.Marshal(objectMap) +} + +// ProxyResource - The resource model definition for a ARM proxy resource. It will have everything other than required location and tags +type ProxyResource struct { + Resource +} + +func (p ProxyResource) marshalInternal(objectMap map[string]interface{}) { + p.Resource.marshalInternal(objectMap) +} + +// QueryCompilationError - An error produced by the compiler. +type QueryCompilationError struct { + // READ-ONLY; Describes the error location in the original query. Not set if isGlobal is true. + EndColumn *int32 `json:"endColumn,omitempty" azure:"ro"` + + // READ-ONLY; Describes the error location in the original query. Not set if isGlobal is true. + EndLine *int32 `json:"endLine,omitempty" azure:"ro"` + + // READ-ONLY; Whether the error is not for a specific part but for the entire query. + IsGlobal *bool `json:"isGlobal,omitempty" azure:"ro"` + + // READ-ONLY; The content of the error message. + Message *string `json:"message,omitempty" azure:"ro"` + + // READ-ONLY; Describes the error location in the original query. Not set if isGlobal is true. + StartColumn *int32 `json:"startColumn,omitempty" azure:"ro"` + + // READ-ONLY; Describes the error location in the original query. Not set if isGlobal is true. + StartLine *int32 `json:"startLine,omitempty" azure:"ro"` +} + +// QueryCompilationResult - The result of the query compilation request. +type QueryCompilationResult struct { + // READ-ONLY; Error messages produced by the compiler. + Errors []*QueryCompilationError `json:"errors,omitempty" azure:"ro"` + + // READ-ONLY; All function names used by the query. + Functions []*string `json:"functions,omitempty" azure:"ro"` + + // READ-ONLY; All input names used by the query. + Inputs []*string `json:"inputs,omitempty" azure:"ro"` + + // READ-ONLY; All output names used by the query. + Outputs []*string `json:"outputs,omitempty" azure:"ro"` + + // READ-ONLY; Warning messages produced by the compiler. + Warnings []*string `json:"warnings,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type QueryCompilationResult. +func (q QueryCompilationResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "errors", q.Errors) + populate(objectMap, "functions", q.Functions) + populate(objectMap, "inputs", q.Inputs) + populate(objectMap, "outputs", q.Outputs) + populate(objectMap, "warnings", q.Warnings) + return json.Marshal(objectMap) +} + +// QueryFunction - A function for the query compilation. +type QueryFunction struct { + // REQUIRED; The type of the function binding. + BindingType *string `json:"bindingType,omitempty"` + + // REQUIRED; The inputs for the function. + Inputs []*FunctionInput `json:"inputs,omitempty"` + + // REQUIRED; The name of the function. + Name *string `json:"name,omitempty"` + + // REQUIRED; An output for the function. + Output *FunctionOutput `json:"output,omitempty"` + + // REQUIRED; The type of the function. + Type *string `json:"type,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type QueryFunction. +func (q QueryFunction) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "bindingType", q.BindingType) + populate(objectMap, "inputs", q.Inputs) + populate(objectMap, "name", q.Name) + populate(objectMap, "output", q.Output) + populate(objectMap, "type", q.Type) + return json.Marshal(objectMap) +} + +// QueryInput - An input for the query compilation. +type QueryInput struct { + // REQUIRED; The name of the input. + Name *string `json:"name,omitempty"` + + // REQUIRED; The type of the input, can be Stream or Reference. + Type *string `json:"type,omitempty"` +} + +// QueryTestingResult - The result of the query testing request. +type QueryTestingResult struct { + Error + // READ-ONLY; The SAS URL to the outputs payload. + OutputURI *string `json:"outputUri,omitempty" azure:"ro"` + + // READ-ONLY; The status of the query testing request. + Status *QueryTestingResultStatus `json:"status,omitempty" azure:"ro"` +} + +// RawInputDatasourceProperties - The properties that are associated with a raw input. +type RawInputDatasourceProperties struct { + // The JSON serialized content of the input data. Either payload or payloadUri must be set, but not both. + Payload *string `json:"payload,omitempty"` + + // The SAS URL to a blob containing the JSON serialized content of the input data. Either payload or payloadUri must be set, but not both. + PayloadURI *string `json:"payloadUri,omitempty"` +} + +// RawOutputDatasource - Describes a raw output data source. This data source type is only applicable/usable when using the query testing API. You cannot +// create a job with this data source type or add an output of this data +// source type to an existing job. +type RawOutputDatasource struct { + OutputDataSource + // The properties that are associated with a raw output. Required on PUT (CreateOrReplace) requests. + Properties *RawOutputDatasourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RawOutputDatasource. +func (r RawOutputDatasource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.OutputDataSource.marshalInternal(objectMap, "Raw") + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RawOutputDatasource. +func (r *RawOutputDatasource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := r.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// RawOutputDatasourceProperties - The properties that are associated with a raw output. +type RawOutputDatasourceProperties struct { + // The SAS URL to a blob where the output should be written. If this property is not set, output data will be written into a temporary storage, and a SAS + // URL to that temporary storage will be included in + // the result. + PayloadURI *string `json:"payloadUri,omitempty"` +} + +// RawReferenceInputDataSource - Describes a raw input data source that contains reference data. This data source type is only applicable/usable when using +// the query testing API. You cannot create a job with this data source type or +// add an input of this data source type to an existing job. +type RawReferenceInputDataSource struct { + ReferenceInputDataSource + // The properties that are associated with a raw input containing reference data. Required on PUT (CreateOrReplace) requests. + Properties *RawInputDatasourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RawReferenceInputDataSource. +func (r RawReferenceInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.ReferenceInputDataSource.marshalInternal(objectMap, "Raw") + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RawReferenceInputDataSource. +func (r *RawReferenceInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := r.ReferenceInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// RawStreamInputDataSource - Describes a raw input data source that contains stream data. This data source type is only applicable/usable when using the +// query testing API. You cannot create a job with this data source type or add +// an input of this data source type to an existing job. +type RawStreamInputDataSource struct { + StreamInputDataSource + // The properties that are associated with a raw input. Required on PUT (CreateOrReplace) requests. + Properties *RawInputDatasourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type RawStreamInputDataSource. +func (r RawStreamInputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.StreamInputDataSource.marshalInternal(objectMap, "Raw") + populate(objectMap, "properties", r.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type RawStreamInputDataSource. +func (r *RawStreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &r.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := r.StreamInputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ReferenceInputDataSourceClassification provides polymorphic access to related types. +// Call the interface's GetReferenceInputDataSource() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AzureSqlReferenceInputDataSource, *BlobReferenceInputDataSource, *RawReferenceInputDataSource, *ReferenceInputDataSource +type ReferenceInputDataSourceClassification interface { + // GetReferenceInputDataSource returns the ReferenceInputDataSource content of the underlying type. + GetReferenceInputDataSource() *ReferenceInputDataSource +} + +// ReferenceInputDataSource - Describes an input data source that contains reference data. +type ReferenceInputDataSource struct { + // REQUIRED; Indicates the type of input data source containing reference data. Required on PUT (CreateOrReplace) requests. + Type *string `json:"type,omitempty"` +} + +// GetReferenceInputDataSource implements the ReferenceInputDataSourceClassification interface for type ReferenceInputDataSource. +func (r *ReferenceInputDataSource) GetReferenceInputDataSource() *ReferenceInputDataSource { return r } + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReferenceInputDataSource. +func (r *ReferenceInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return r.unmarshalInternal(rawMsg) +} + +func (r ReferenceInputDataSource) marshalInternal(objectMap map[string]interface{}, discValue string) { + r.Type = &discValue + objectMap["type"] = r.Type +} + +func (r *ReferenceInputDataSource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &r.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ReferenceInputProperties - The properties that are associated with an input containing reference data. +type ReferenceInputProperties struct { + InputProperties + // Describes an input data source that contains reference data. Required on PUT (CreateOrReplace) requests. + Datasource ReferenceInputDataSourceClassification `json:"datasource,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ReferenceInputProperties. +func (r ReferenceInputProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.InputProperties.marshalInternal(objectMap, "Reference") + populate(objectMap, "datasource", r.Datasource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ReferenceInputProperties. +func (r *ReferenceInputProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "datasource": + r.Datasource, err = unmarshalReferenceInputDataSourceClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := r.InputProperties.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// Resource - The base resource definition +type Resource struct { + // READ-ONLY; Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; The name of the resource + Name *string `json:"name,omitempty" azure:"ro"` + + // READ-ONLY; The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type Resource. +func (r Resource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + r.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (r Resource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", r.ID) + populate(objectMap, "name", r.Name) + populate(objectMap, "type", r.Type) +} + +// ResourceTestStatus - Describes the status of the test operation along with error information, if applicable. +type ResourceTestStatus struct { + // READ-ONLY; Describes the error that occurred. + Error *ErrorResponse `json:"error,omitempty" azure:"ro"` + + // READ-ONLY; The status of the test operation. + Status *string `json:"status,omitempty" azure:"ro"` +} + +// SampleInput - The stream analytics input to sample. +type SampleInput struct { + // Defaults to the default ASA job compatibility level. Today it is 1.2 + CompatibilityLevel *string `json:"compatibilityLevel,omitempty"` + + // Defaults to en-US. + DataLocale *string `json:"dataLocale,omitempty"` + + // The SAS URI of the storage blob for service to write the sampled events to. If this parameter is not provided, service will write events to he system + // account and share a temporary SAS URI to it. + EventsURI *string `json:"eventsUri,omitempty"` + + // The stream analytics input to sample. + Input *Input `json:"input,omitempty"` +} + +// SampleInputResult - The result of the sample input request. +type SampleInputResult struct { + Error + // READ-ONLY; Diagnostics messages. E.g. message indicating some partitions from the input have no data. + Diagnostics []*string `json:"diagnostics,omitempty" azure:"ro"` + + // READ-ONLY; A SAS URL to download the sampled input data. + EventsDownloadURL *string `json:"eventsDownloadUrl,omitempty" azure:"ro"` + + // READ-ONLY; The timestamp for the last event in the data. It is in DateTime format. + LastArrivalTime *string `json:"lastArrivalTime,omitempty" azure:"ro"` + + // READ-ONLY; The status of the sample input request. + Status *SampleInputResultStatus `json:"status,omitempty" azure:"ro"` +} + +// ScalarFunctionProperties - The properties that are associated with a scalar function. +type ScalarFunctionProperties struct { + FunctionProperties +} + +// MarshalJSON implements the json.Marshaller interface for type ScalarFunctionProperties. +func (s ScalarFunctionProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.FunctionProperties.marshalInternal(objectMap, "Scalar") + return json.Marshal(objectMap) +} + +// SerializationClassification provides polymorphic access to related types. +// Call the interface's GetSerialization() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *AvroSerialization, *CsvSerialization, *CustomClrSerialization, *JsonSerialization, *ParquetSerialization, *Serialization +type SerializationClassification interface { + // GetSerialization returns the Serialization content of the underlying type. + GetSerialization() *Serialization +} + +// Serialization - Describes how data from an input is serialized or how data is serialized when written to an output. +type Serialization struct { + // REQUIRED; Indicates the type of serialization that the input or output uses. Required on PUT (CreateOrReplace) requests. + Type *EventSerializationType `json:"type,omitempty"` +} + +// GetSerialization implements the SerializationClassification interface for type Serialization. +func (s *Serialization) GetSerialization() *Serialization { return s } + +// UnmarshalJSON implements the json.Unmarshaller interface for type Serialization. +func (s *Serialization) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return s.unmarshalInternal(rawMsg) +} + +func (s Serialization) marshalInternal(objectMap map[string]interface{}, discValue EventSerializationType) { + s.Type = &discValue + objectMap["type"] = s.Type +} + +func (s *Serialization) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &s.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// ServiceBusDataSourceProperties - The common properties that are associated with Service Bus data sources (Queues, Topics, Event Hubs, etc.). +type ServiceBusDataSourceProperties struct { + // Authentication Mode. + AuthenticationMode *AuthenticationMode `json:"authenticationMode,omitempty"` + + // The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. + ServiceBusNamespace *string `json:"serviceBusNamespace,omitempty"` + + // The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. + SharedAccessPolicyKey *string `json:"sharedAccessPolicyKey,omitempty"` + + // The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. + SharedAccessPolicyName *string `json:"sharedAccessPolicyName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusDataSourceProperties. +func (s ServiceBusDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (s ServiceBusDataSourceProperties) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "authenticationMode", s.AuthenticationMode) + populate(objectMap, "serviceBusNamespace", s.ServiceBusNamespace) + populate(objectMap, "sharedAccessPolicyKey", s.SharedAccessPolicyKey) + populate(objectMap, "sharedAccessPolicyName", s.SharedAccessPolicyName) +} + +// ServiceBusQueueOutputDataSource - Describes a Service Bus Queue output data source. +type ServiceBusQueueOutputDataSource struct { + OutputDataSource + // The properties that are associated with a Service Bus Queue output. Required on PUT (CreateOrReplace) requests. + Properties *ServiceBusQueueOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusQueueOutputDataSource. +func (s ServiceBusQueueOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.OutputDataSource.marshalInternal(objectMap, "Microsoft.ServiceBus/Queue") + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceBusQueueOutputDataSource. +func (s *ServiceBusQueueOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ServiceBusQueueOutputDataSourceProperties - The properties that are associated with a Service Bus Queue output. +type ServiceBusQueueOutputDataSourceProperties struct { + ServiceBusDataSourceProperties + // A string array of the names of output columns to be attached to Service Bus messages as custom properties. + PropertyColumns []*string `json:"propertyColumns,omitempty"` + + // The name of the Service Bus Queue. Required on PUT (CreateOrReplace) requests. + QueueName *string `json:"queueName,omitempty"` + + // Dictionary of + SystemPropertyColumns map[string]*string `json:"systemPropertyColumns,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusQueueOutputDataSourceProperties. +func (s ServiceBusQueueOutputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ServiceBusDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "propertyColumns", s.PropertyColumns) + populate(objectMap, "queueName", s.QueueName) + populate(objectMap, "systemPropertyColumns", s.SystemPropertyColumns) + return json.Marshal(objectMap) +} + +// ServiceBusTopicOutputDataSource - Describes a Service Bus Topic output data source. +type ServiceBusTopicOutputDataSource struct { + OutputDataSource + // The properties that are associated with a Service Bus Topic output. Required on PUT (CreateOrReplace) requests. + Properties *ServiceBusTopicOutputDataSourceProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusTopicOutputDataSource. +func (s ServiceBusTopicOutputDataSource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.OutputDataSource.marshalInternal(objectMap, "Microsoft.ServiceBus/Topic") + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type ServiceBusTopicOutputDataSource. +func (s *ServiceBusTopicOutputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.OutputDataSource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// ServiceBusTopicOutputDataSourceProperties - The properties that are associated with a Service Bus Topic output. +type ServiceBusTopicOutputDataSourceProperties struct { + ServiceBusDataSourceProperties + // A string array of the names of output columns to be attached to Service Bus messages as custom properties. + PropertyColumns []*string `json:"propertyColumns,omitempty"` + + // Dictionary of + SystemPropertyColumns map[string]*string `json:"systemPropertyColumns,omitempty"` + + // The name of the Service Bus Topic. Required on PUT (CreateOrReplace) requests. + TopicName *string `json:"topicName,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type ServiceBusTopicOutputDataSourceProperties. +func (s ServiceBusTopicOutputDataSourceProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.ServiceBusDataSourceProperties.marshalInternal(objectMap) + populate(objectMap, "propertyColumns", s.PropertyColumns) + populate(objectMap, "systemPropertyColumns", s.SystemPropertyColumns) + populate(objectMap, "topicName", s.TopicName) + return json.Marshal(objectMap) +} + +// StartStreamingJobParameters - Parameters supplied to the Start Streaming Job operation. +type StartStreamingJobParameters struct { + // Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should start whenever + // the job is started, start at a custom user time + // stamp specified via the outputStartTime property, or start from the last event output time. + OutputStartMode *OutputStartMode `json:"outputStartMode,omitempty"` + + // Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event + // stream will start whenever the streaming job is + // started. This property must have a value if outputStartMode is set to CustomTime. + OutputStartTime *time.Time `json:"outputStartTime,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StartStreamingJobParameters. +func (s StartStreamingJobParameters) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "outputStartMode", s.OutputStartMode) + populate(objectMap, "outputStartTime", (*timeRFC3339)(s.OutputStartTime)) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StartStreamingJobParameters. +func (s *StartStreamingJobParameters) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "outputStartMode": + err = unpopulate(val, &s.OutputStartMode) + delete(rawMsg, key) + case "outputStartTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.OutputStartTime = (*time.Time)(&aux) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StorageAccount - The properties that are associated with an Azure Storage account +type StorageAccount struct { + // The account key for the Azure Storage account. Required on PUT (CreateOrReplace) requests. + AccountKey *string `json:"accountKey,omitempty"` + + // The name of the Azure Storage account. Required on PUT (CreateOrReplace) requests. + AccountName *string `json:"accountName,omitempty"` +} + +// StreamInputDataSourceClassification provides polymorphic access to related types. +// Call the interface's GetStreamInputDataSource() method to access the common type. +// Use a type switch to determine the concrete type. The possible types are: +// - *BlobStreamInputDataSource, *EventHubStreamInputDataSource, *EventHubV2StreamInputDataSource, *IoTHubStreamInputDataSource, +// - *RawStreamInputDataSource, *StreamInputDataSource +type StreamInputDataSourceClassification interface { + // GetStreamInputDataSource returns the StreamInputDataSource content of the underlying type. + GetStreamInputDataSource() *StreamInputDataSource +} + +// StreamInputDataSource - Describes an input data source that contains stream data. +type StreamInputDataSource struct { + // REQUIRED; Indicates the type of input data source containing stream data. Required on PUT (CreateOrReplace) requests. + Type *string `json:"type,omitempty"` +} + +// GetStreamInputDataSource implements the StreamInputDataSourceClassification interface for type StreamInputDataSource. +func (s *StreamInputDataSource) GetStreamInputDataSource() *StreamInputDataSource { return s } + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamInputDataSource. +func (s *StreamInputDataSource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return s.unmarshalInternal(rawMsg) +} + +func (s StreamInputDataSource) marshalInternal(objectMap map[string]interface{}, discValue string) { + s.Type = &discValue + objectMap["type"] = s.Type +} + +func (s *StreamInputDataSource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "type": + err = unpopulate(val, &s.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamInputProperties - The properties that are associated with an input containing stream data. +type StreamInputProperties struct { + InputProperties + // Describes an input data source that contains stream data. Required on PUT (CreateOrReplace) requests. + Datasource StreamInputDataSourceClassification `json:"datasource,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamInputProperties. +func (s StreamInputProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.InputProperties.marshalInternal(objectMap, "Stream") + populate(objectMap, "datasource", s.Datasource) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamInputProperties. +func (s *StreamInputProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "datasource": + s.Datasource, err = unmarshalStreamInputDataSourceClassification(val) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.InputProperties.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// StreamingJob - A streaming job object, containing all information associated with the named streaming job. +type StreamingJob struct { + TrackedResource + // Describes the system-assigned managed identity assigned to this job that can be used to authenticate with inputs and outputs. + Identity *Identity `json:"identity,omitempty"` + + // The properties that are associated with a streaming job. Required on PUT (CreateOrReplace) requests. + Properties *StreamingJobProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingJob. +func (s StreamingJob) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.TrackedResource.marshalInternal(objectMap) + populate(objectMap, "identity", s.Identity) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// StreamingJobListResult - Object containing a list of streaming jobs. +type StreamingJobListResult struct { + // READ-ONLY; The link (url) to the next page of results. + NextLink *string `json:"nextLink,omitempty" azure:"ro"` + + // READ-ONLY; A list of streaming jobs. Populated by a 'List' operation. + Value []*StreamingJob `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingJobListResult. +func (s StreamingJobListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "nextLink", s.NextLink) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// StreamingJobProperties - The properties that are associated with a streaming job. +type StreamingJobProperties struct { + // The cluster which streaming jobs will run on. + Cluster *ClusterInfo `json:"cluster,omitempty"` + + // Controls certain runtime behaviors of the streaming job. + CompatibilityLevel *CompatibilityLevel `json:"compatibilityLevel,omitempty"` + + // Valid values are JobStorageAccount and SystemAccount. If set to JobStorageAccount, this requires the user to also specify jobStorageAccount property. + // . + ContentStoragePolicy *ContentStoragePolicy `json:"contentStoragePolicy,omitempty"` + + // The data locale of the stream analytics job. Value should be the name of a supported .NET Culture from the set + // https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx. Defaults to 'en-US' if none specified. + DataLocale *string `json:"dataLocale,omitempty"` + + // The maximum tolerable delay in seconds where events arriving late could be included. Supported range is -1 to 1814399 (20.23:59:59 days) and -1 is used + // to specify wait indefinitely. If the property is + // absent, it is interpreted to have a value of -1. + EventsLateArrivalMaxDelayInSeconds *int32 `json:"eventsLateArrivalMaxDelayInSeconds,omitempty"` + + // The maximum tolerable delay in seconds where out-of-order events can be adjusted to be back in order. + EventsOutOfOrderMaxDelayInSeconds *int32 `json:"eventsOutOfOrderMaxDelayInSeconds,omitempty"` + + // Indicates the policy to apply to events that arrive out of order in the input event stream. + EventsOutOfOrderPolicy *EventsOutOfOrderPolicy `json:"eventsOutOfOrderPolicy,omitempty"` + + // The storage account where the custom code artifacts are located. + Externals *External `json:"externals,omitempty"` + + // A list of one or more functions for the streaming job. The name property for each function is required when specifying this property in a PUT request. + // This property cannot be modify via a PATCH + // operation. You must use the PATCH API available for the individual transformation. + Functions []*Function `json:"functions,omitempty"` + + // A list of one or more inputs to the streaming job. The name property for each input is required when specifying this property in a PUT request. This + // property cannot be modify via a PATCH operation. + // You must use the PATCH API available for the individual input. + Inputs []*Input `json:"inputs,omitempty"` + + // The properties that are associated with an Azure Storage account with MSI + JobStorageAccount *JobStorageAccount `json:"jobStorageAccount,omitempty"` + + // Describes the type of the job. Valid modes are Cloud and 'Edge'. + JobType *JobType `json:"jobType,omitempty"` + + // Indicates the policy to apply to events that arrive at the output and cannot be written to the external storage due to being malformed (missing column + // values, column values of wrong type or size). + OutputErrorPolicy *OutputErrorPolicy `json:"outputErrorPolicy,omitempty"` + + // This property should only be utilized when it is desired that the job be started immediately upon creation. Value may be JobStartTime, CustomTime, or + // LastOutputEventTime to indicate whether the + // starting point of the output event stream should start whenever the job is started, start at a custom user time stamp specified via the outputStartTime + // property, or start from the last event output + // time. + OutputStartMode *OutputStartMode `json:"outputStartMode,omitempty"` + + // Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event + // stream will start whenever the streaming job is + // started. This property must have a value if outputStartMode is set to CustomTime. + OutputStartTime *time.Time `json:"outputStartTime,omitempty"` + + // A list of one or more outputs for the streaming job. The name property for each output is required when specifying this property in a PUT request. This + // property cannot be modify via a PATCH operation. + // You must use the PATCH API available for the individual output. + Outputs []*Output `json:"outputs,omitempty"` + + // Describes the SKU of the streaming job. Required on PUT (CreateOrReplace) requests. + SKU *StreamingJobSKU `json:"sku,omitempty"` + + // Indicates the query and the number of streaming units to use for the streaming job. The name property of the transformation is required when specifying + // this property in a PUT request. This property + // cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation. + Transformation *Transformation `json:"transformation,omitempty"` + + // READ-ONLY; Value is an ISO-8601 formatted UTC timestamp indicating when the streaming job was created. + CreatedDate *time.Time `json:"createdDate,omitempty" azure:"ro"` + + // READ-ONLY; The current entity tag for the streaming job. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. You can also use it in the If-Match or If-None-Match + // headers for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` + + // READ-ONLY; A GUID uniquely identifying the streaming job. This GUID is generated upon creation of the streaming job. + JobID *string `json:"jobId,omitempty" azure:"ro"` + + // READ-ONLY; Describes the state of the streaming job. + JobState *string `json:"jobState,omitempty" azure:"ro"` + + // READ-ONLY; Value is either an ISO-8601 formatted timestamp indicating the last output event time of the streaming job or null indicating that output + // has not yet been produced. In case of multiple outputs or + // multiple streams, this shows the latest value in that set. + LastOutputEventTime *time.Time `json:"lastOutputEventTime,omitempty" azure:"ro"` + + // READ-ONLY; Describes the provisioning status of the streaming job. + ProvisioningState *string `json:"provisioningState,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type StreamingJobProperties. +func (s StreamingJobProperties) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "cluster", s.Cluster) + populate(objectMap, "compatibilityLevel", s.CompatibilityLevel) + populate(objectMap, "contentStoragePolicy", s.ContentStoragePolicy) + populate(objectMap, "createdDate", (*timeRFC3339)(s.CreatedDate)) + populate(objectMap, "dataLocale", s.DataLocale) + populate(objectMap, "etag", s.Etag) + populate(objectMap, "eventsLateArrivalMaxDelayInSeconds", s.EventsLateArrivalMaxDelayInSeconds) + populate(objectMap, "eventsOutOfOrderMaxDelayInSeconds", s.EventsOutOfOrderMaxDelayInSeconds) + populate(objectMap, "eventsOutOfOrderPolicy", s.EventsOutOfOrderPolicy) + populate(objectMap, "externals", s.Externals) + populate(objectMap, "functions", s.Functions) + populate(objectMap, "inputs", s.Inputs) + populate(objectMap, "jobId", s.JobID) + populate(objectMap, "jobState", s.JobState) + populate(objectMap, "jobStorageAccount", s.JobStorageAccount) + populate(objectMap, "jobType", s.JobType) + populate(objectMap, "lastOutputEventTime", (*timeRFC3339)(s.LastOutputEventTime)) + populate(objectMap, "outputErrorPolicy", s.OutputErrorPolicy) + populate(objectMap, "outputStartMode", s.OutputStartMode) + populate(objectMap, "outputStartTime", (*timeRFC3339)(s.OutputStartTime)) + populate(objectMap, "outputs", s.Outputs) + populate(objectMap, "provisioningState", s.ProvisioningState) + populate(objectMap, "sku", s.SKU) + populate(objectMap, "transformation", s.Transformation) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type StreamingJobProperties. +func (s *StreamingJobProperties) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "cluster": + err = unpopulate(val, &s.Cluster) + delete(rawMsg, key) + case "compatibilityLevel": + err = unpopulate(val, &s.CompatibilityLevel) + delete(rawMsg, key) + case "contentStoragePolicy": + err = unpopulate(val, &s.ContentStoragePolicy) + delete(rawMsg, key) + case "createdDate": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.CreatedDate = (*time.Time)(&aux) + delete(rawMsg, key) + case "dataLocale": + err = unpopulate(val, &s.DataLocale) + delete(rawMsg, key) + case "etag": + err = unpopulate(val, &s.Etag) + delete(rawMsg, key) + case "eventsLateArrivalMaxDelayInSeconds": + err = unpopulate(val, &s.EventsLateArrivalMaxDelayInSeconds) + delete(rawMsg, key) + case "eventsOutOfOrderMaxDelayInSeconds": + err = unpopulate(val, &s.EventsOutOfOrderMaxDelayInSeconds) + delete(rawMsg, key) + case "eventsOutOfOrderPolicy": + err = unpopulate(val, &s.EventsOutOfOrderPolicy) + delete(rawMsg, key) + case "externals": + err = unpopulate(val, &s.Externals) + delete(rawMsg, key) + case "functions": + err = unpopulate(val, &s.Functions) + delete(rawMsg, key) + case "inputs": + err = unpopulate(val, &s.Inputs) + delete(rawMsg, key) + case "jobId": + err = unpopulate(val, &s.JobID) + delete(rawMsg, key) + case "jobState": + err = unpopulate(val, &s.JobState) + delete(rawMsg, key) + case "jobStorageAccount": + err = unpopulate(val, &s.JobStorageAccount) + delete(rawMsg, key) + case "jobType": + err = unpopulate(val, &s.JobType) + delete(rawMsg, key) + case "lastOutputEventTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.LastOutputEventTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "outputErrorPolicy": + err = unpopulate(val, &s.OutputErrorPolicy) + delete(rawMsg, key) + case "outputStartMode": + err = unpopulate(val, &s.OutputStartMode) + delete(rawMsg, key) + case "outputStartTime": + var aux timeRFC3339 + err = unpopulate(val, &aux) + s.OutputStartTime = (*time.Time)(&aux) + delete(rawMsg, key) + case "outputs": + err = unpopulate(val, &s.Outputs) + delete(rawMsg, key) + case "provisioningState": + err = unpopulate(val, &s.ProvisioningState) + delete(rawMsg, key) + case "sku": + err = unpopulate(val, &s.SKU) + delete(rawMsg, key) + case "transformation": + err = unpopulate(val, &s.Transformation) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// StreamingJobSKU - The properties that are associated with a SKU. +type StreamingJobSKU struct { + // The name of the SKU. Required on PUT (CreateOrReplace) requests. + Name *StreamingJobSKUName `json:"name,omitempty"` +} + +// StreamingJobsBeginCreateOrReplaceOptions contains the optional parameters for the StreamingJobs.BeginCreateOrReplace method. +type StreamingJobsBeginCreateOrReplaceOptions struct { + // The ETag of the streaming job. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string + // Set to '*' to allow a new streaming job to be created, but to prevent updating an existing record set. Other values will result in a 412 Pre-condition + // Failed response. + IfNoneMatch *string +} + +// StreamingJobsBeginDeleteOptions contains the optional parameters for the StreamingJobs.BeginDelete method. +type StreamingJobsBeginDeleteOptions struct { + // placeholder for future optional parameters +} + +// StreamingJobsBeginStartOptions contains the optional parameters for the StreamingJobs.BeginStart method. +type StreamingJobsBeginStartOptions struct { + // Parameters applicable to a start streaming job operation. + StartJobParameters *StartStreamingJobParameters +} + +// StreamingJobsBeginStopOptions contains the optional parameters for the StreamingJobs.BeginStop method. +type StreamingJobsBeginStopOptions struct { + // placeholder for future optional parameters +} + +// StreamingJobsGetOptions contains the optional parameters for the StreamingJobs.Get method. +type StreamingJobsGetOptions struct { + // The $expand OData query parameter. This is a comma-separated list of additional streaming job properties to include in the response, beyond the default + // set returned when this parameter is absent. The default set is all streaming job properties other than 'inputs', 'transformation', 'outputs', and 'functions'. + Expand *string +} + +// StreamingJobsListByResourceGroupOptions contains the optional parameters for the StreamingJobs.ListByResourceGroup method. +type StreamingJobsListByResourceGroupOptions struct { + // The $expand OData query parameter. This is a comma-separated list of additional streaming job properties to include in the response, beyond the default + // set returned when this parameter is absent. The default set is all streaming job properties other than 'inputs', 'transformation', 'outputs', and 'functions'. + Expand *string +} + +// StreamingJobsListOptions contains the optional parameters for the StreamingJobs.List method. +type StreamingJobsListOptions struct { + // The $expand OData query parameter. This is a comma-separated list of additional streaming job properties to include in the response, beyond the default + // set returned when this parameter is absent. The default set is all streaming job properties other than 'inputs', 'transformation', 'outputs', and 'functions'. + Expand *string +} + +// StreamingJobsUpdateOptions contains the optional parameters for the StreamingJobs.Update method. +type StreamingJobsUpdateOptions struct { + // The ETag of the streaming job. Omit this value to always overwrite the current record set. Specify the last-seen ETag value to prevent accidentally overwriting + // concurrent changes. + IfMatch *string +} + +// SubResource - The base sub-resource model definition. +type SubResource struct { + // Resource name + Name *string `json:"name,omitempty"` + + // READ-ONLY; Resource Id + ID *string `json:"id,omitempty" azure:"ro"` + + // READ-ONLY; Resource type + Type *string `json:"type,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SubResource. +func (s SubResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubResource. +func (s *SubResource) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + return s.unmarshalInternal(rawMsg) +} + +func (s SubResource) marshalInternal(objectMap map[string]interface{}) { + populate(objectMap, "id", s.ID) + populate(objectMap, "name", s.Name) + populate(objectMap, "type", s.Type) +} + +func (s *SubResource) unmarshalInternal(rawMsg map[string]json.RawMessage) error { + for key, val := range rawMsg { + var err error + switch key { + case "id": + err = unpopulate(val, &s.ID) + delete(rawMsg, key) + case "name": + err = unpopulate(val, &s.Name) + delete(rawMsg, key) + case "type": + err = unpopulate(val, &s.Type) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + return nil +} + +// SubscriptionQuota - Describes the current quota for the subscription. +type SubscriptionQuota struct { + SubResource + // READ-ONLY; Describes the properties of the quota. + Properties *SubscriptionQuotaProperties `json:"properties,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionQuota. +func (s SubscriptionQuota) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + s.SubResource.marshalInternal(objectMap) + populate(objectMap, "properties", s.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type SubscriptionQuota. +func (s *SubscriptionQuota) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &s.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := s.SubResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// SubscriptionQuotaProperties - Describes the properties of the quota. +type SubscriptionQuotaProperties struct { + // READ-ONLY; The current usage of this resource. + CurrentCount *int32 `json:"currentCount,omitempty" azure:"ro"` + + // READ-ONLY; The max permitted usage of this resource. + MaxCount *int32 `json:"maxCount,omitempty" azure:"ro"` +} + +// SubscriptionQuotasListResult - Result of the GetQuotas operation. It contains a list of quotas for the subscription in a particular region. +type SubscriptionQuotasListResult struct { + // READ-ONLY; List of quotas for the subscription in a particular region. + Value []*SubscriptionQuota `json:"value,omitempty" azure:"ro"` +} + +// MarshalJSON implements the json.Marshaller interface for type SubscriptionQuotasListResult. +func (s SubscriptionQuotasListResult) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + populate(objectMap, "value", s.Value) + return json.Marshal(objectMap) +} + +// SubscriptionsBeginSampleInputOptions contains the optional parameters for the Subscriptions.BeginSampleInput method. +type SubscriptionsBeginSampleInputOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionsBeginTestInputOptions contains the optional parameters for the Subscriptions.BeginTestInput method. +type SubscriptionsBeginTestInputOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionsBeginTestOutputOptions contains the optional parameters for the Subscriptions.BeginTestOutput method. +type SubscriptionsBeginTestOutputOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionsBeginTestQueryOptions contains the optional parameters for the Subscriptions.BeginTestQuery method. +type SubscriptionsBeginTestQueryOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionsCompileQueryOptions contains the optional parameters for the Subscriptions.CompileQuery method. +type SubscriptionsCompileQueryOptions struct { + // placeholder for future optional parameters +} + +// SubscriptionsListQuotasOptions contains the optional parameters for the Subscriptions.ListQuotas method. +type SubscriptionsListQuotasOptions struct { + // placeholder for future optional parameters +} + +// TestDatasourceResult - The result of the test input or output request. +type TestDatasourceResult struct { + Error + // READ-ONLY; The status of the sample output request. + Status *TestDatasourceResultStatus `json:"status,omitempty" azure:"ro"` +} + +// TestInput - A stream analytics input. +type TestInput struct { + // REQUIRED; The stream analytics input to test. + Input *Input `json:"input,omitempty"` +} + +// TestOutput - A stream analytics output. +type TestOutput struct { + // REQUIRED; The stream analytics output to test. + Output *Output `json:"output,omitempty"` +} + +// TestQuery - The request object for query testing. +type TestQuery struct { + // REQUIRED; Stream analytics job object which defines the input, output, and transformation for the query testing. + StreamingJob *StreamingJob `json:"streamingJob,omitempty"` + + // Diagnostics information related to query testing. + Diagnostics *TestQueryDiagnostics `json:"diagnostics,omitempty"` +} + +// TestQueryDiagnostics - Diagnostics information related to query testing. +type TestQueryDiagnostics struct { + // REQUIRED; The SAS URI to the container or directory. + WriteURI *string `json:"writeUri,omitempty"` + + // The path to the subdirectory. + Path *string `json:"path,omitempty"` +} + +// TrackedResource - The resource model definition for a ARM tracked top level resource +type TrackedResource struct { + Resource + // The geo-location where the resource lives + Location *string `json:"location,omitempty"` + + // Resource tags. + Tags map[string]*string `json:"tags,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type TrackedResource. +func (t TrackedResource) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.marshalInternal(objectMap) + return json.Marshal(objectMap) +} + +func (t TrackedResource) marshalInternal(objectMap map[string]interface{}) { + t.Resource.marshalInternal(objectMap) + populate(objectMap, "location", t.Location) + populate(objectMap, "tags", t.Tags) +} + +// Transformation - A transformation object, containing all information associated with the named transformation. All transformations are contained under +// a streaming job. +type Transformation struct { + SubResource + // The properties that are associated with a transformation. Required on PUT (CreateOrReplace) requests. + Properties *TransformationProperties `json:"properties,omitempty"` +} + +// MarshalJSON implements the json.Marshaller interface for type Transformation. +func (t Transformation) MarshalJSON() ([]byte, error) { + objectMap := make(map[string]interface{}) + t.SubResource.marshalInternal(objectMap) + populate(objectMap, "properties", t.Properties) + return json.Marshal(objectMap) +} + +// UnmarshalJSON implements the json.Unmarshaller interface for type Transformation. +func (t *Transformation) UnmarshalJSON(data []byte) error { + var rawMsg map[string]json.RawMessage + if err := json.Unmarshal(data, &rawMsg); err != nil { + return err + } + for key, val := range rawMsg { + var err error + switch key { + case "properties": + err = unpopulate(val, &t.Properties) + delete(rawMsg, key) + } + if err != nil { + return err + } + } + if err := t.SubResource.unmarshalInternal(rawMsg); err != nil { + return err + } + return nil +} + +// TransformationProperties - The properties that are associated with a transformation. +type TransformationProperties struct { + // Specifies the query that will be run in the streaming job. You can learn more about the Stream Analytics Query Language (SAQL) here: https://msdn.microsoft.com/library/azure/dn834998 + // . Required on PUT + // (CreateOrReplace) requests. + Query *string `json:"query,omitempty"` + + // Specifies the number of streaming units that the streaming job uses. + StreamingUnits *int32 `json:"streamingUnits,omitempty"` + + // READ-ONLY; The current entity tag for the transformation. This is an opaque string. You can use it to detect whether the resource has changed between + // requests. You can also use it in the If-Match or + // If-None-Match headers for write operations for optimistic concurrency. + Etag *string `json:"etag,omitempty" azure:"ro"` +} + +// TransformationsCreateOrReplaceOptions contains the optional parameters for the Transformations.CreateOrReplace method. +type TransformationsCreateOrReplaceOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current transformation. Specify the last-seen ETag value to prevent accidentally + // overwriting concurrent changes. + IfMatch *string + // Set to '*' to allow a new transformation to be created, but to prevent updating an existing transformation. Other values will result in a 412 Pre-condition + // Failed response. + IfNoneMatch *string +} + +// TransformationsGetOptions contains the optional parameters for the Transformations.Get method. +type TransformationsGetOptions struct { + // placeholder for future optional parameters +} + +// TransformationsUpdateOptions contains the optional parameters for the Transformations.Update method. +type TransformationsUpdateOptions struct { + // The ETag of the transformation. Omit this value to always overwrite the current transformation. Specify the last-seen ETag value to prevent accidentally + // overwriting concurrent changes. + IfMatch *string +} + +func populate(m map[string]interface{}, k string, v interface{}) { + if v == nil { + return + } else if azcore.IsNullValue(v) { + m[k] = nil + } else if !reflect.ValueOf(v).IsNil() { + m[k] = v + } +} + +func unpopulate(data json.RawMessage, v interface{}) error { + if data == nil { + return nil + } + return json.Unmarshal(data, v) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_operations_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_operations_client.go new file mode 100644 index 000000000000..e419e3ecc6ed --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_operations_client.go @@ -0,0 +1,81 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "fmt" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OperationsClient contains the methods for the Operations group. +// Don't use this type directly, use NewOperationsClient() instead. +type OperationsClient struct { + ep string + pl runtime.Pipeline +} + +// NewOperationsClient creates a new instance of OperationsClient with the specified values. +func NewOperationsClient(con *arm.Connection) *OperationsClient { + return &OperationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version)} +} + +// List - Lists all of the available Stream Analytics related operations. +// If the operation fails it returns the *Error error type. +func (client *OperationsClient) List(options *OperationsListOptions) *OperationsListPager { + return &OperationsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp OperationsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OperationListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *OperationsClient) listCreateRequest(ctx context.Context, options *OperationsListOptions) (*policy.Request, error) { + urlPath := "/providers/Microsoft.StreamAnalytics/operations" + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *OperationsClient) listHandleResponse(resp *http.Response) (OperationsListResponse, error) { + result := OperationsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OperationListResult); err != nil { + return OperationsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *OperationsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_outputs_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_outputs_client.go new file mode 100644 index 000000000000..61cc9e5d5b9c --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_outputs_client.go @@ -0,0 +1,470 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// OutputsClient contains the methods for the Outputs group. +// Don't use this type directly, use NewOutputsClient() instead. +type OutputsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewOutputsClient creates a new instance of OutputsClient with the specified values. +func NewOutputsClient(con *arm.Connection, subscriptionID string) *OutputsClient { + return &OutputsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrReplace - Creates an output or replaces an already existing output under an existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) CreateOrReplace(ctx context.Context, resourceGroupName string, jobName string, outputName string, output Output, options *OutputsCreateOrReplaceOptions) (OutputsCreateOrReplaceResponse, error) { + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, jobName, outputName, output, options) + if err != nil { + return OutputsCreateOrReplaceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OutputsCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return OutputsCreateOrReplaceResponse{}, client.createOrReplaceHandleError(resp) + } + return client.createOrReplaceHandleResponse(resp) +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *OutputsClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, jobName string, outputName string, output Output, options *OutputsCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs/{outputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if outputName == "" { + return nil, errors.New("parameter outputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outputName}", url.PathEscape(outputName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, output) +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *OutputsClient) createOrReplaceHandleResponse(resp *http.Response) (OutputsCreateOrReplaceResponse, error) { + result := OutputsCreateOrReplaceResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Output); err != nil { + return OutputsCreateOrReplaceResponse{}, err + } + return result, nil +} + +// createOrReplaceHandleError handles the CreateOrReplace error response. +func (client *OutputsClient) createOrReplaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Delete - Deletes an output from the streaming job. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) Delete(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsDeleteOptions) (OutputsDeleteResponse, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobName, outputName, options) + if err != nil { + return OutputsDeleteResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OutputsDeleteResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusNoContent) { + return OutputsDeleteResponse{}, client.deleteHandleError(resp) + } + return OutputsDeleteResponse{RawResponse: resp}, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *OutputsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs/{outputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if outputName == "" { + return nil, errors.New("parameter outputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outputName}", url.PathEscape(outputName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *OutputsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details about the specified output. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) Get(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsGetOptions) (OutputsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobName, outputName, options) + if err != nil { + return OutputsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OutputsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OutputsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *OutputsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs/{outputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if outputName == "" { + return nil, errors.New("parameter outputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outputName}", url.PathEscape(outputName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *OutputsClient) getHandleResponse(resp *http.Response) (OutputsGetResponse, error) { + result := OutputsGetResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Output); err != nil { + return OutputsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *OutputsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByStreamingJob - Lists all of the outputs under the specified streaming job. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) ListByStreamingJob(resourceGroupName string, jobName string, options *OutputsListByStreamingJobOptions) *OutputsListByStreamingJobPager { + return &OutputsListByStreamingJobPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByStreamingJobCreateRequest(ctx, resourceGroupName, jobName, options) + }, + advancer: func(ctx context.Context, resp OutputsListByStreamingJobResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.OutputListResult.NextLink) + }, + } +} + +// listByStreamingJobCreateRequest creates the ListByStreamingJob request. +func (client *OutputsClient) listByStreamingJobCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *OutputsListByStreamingJobOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Select != nil { + reqQP.Set("$select", *options.Select) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByStreamingJobHandleResponse handles the ListByStreamingJob response. +func (client *OutputsClient) listByStreamingJobHandleResponse(resp *http.Response) (OutputsListByStreamingJobResponse, error) { + result := OutputsListByStreamingJobResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.OutputListResult); err != nil { + return OutputsListByStreamingJobResponse{}, err + } + return result, nil +} + +// listByStreamingJobHandleError handles the ListByStreamingJob error response. +func (client *OutputsClient) listByStreamingJobHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTest - Tests whether an output’s datasource is reachable and usable by the Azure Stream Analytics service. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) BeginTest(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsBeginTestOptions) (OutputsTestPollerResponse, error) { + resp, err := client.test(ctx, resourceGroupName, jobName, outputName, options) + if err != nil { + return OutputsTestPollerResponse{}, err + } + result := OutputsTestPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("OutputsClient.Test", "", resp, client.pl, client.testHandleError) + if err != nil { + return OutputsTestPollerResponse{}, err + } + result.Poller = &OutputsTestPoller{ + pt: pt, + } + return result, nil +} + +// Test - Tests whether an output’s datasource is reachable and usable by the Azure Stream Analytics service. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) test(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsBeginTestOptions) (*http.Response, error) { + req, err := client.testCreateRequest(ctx, resourceGroupName, jobName, outputName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.testHandleError(resp) + } + return resp, nil +} + +// testCreateRequest creates the Test request. +func (client *OutputsClient) testCreateRequest(ctx context.Context, resourceGroupName string, jobName string, outputName string, options *OutputsBeginTestOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs/{outputName}/test" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if outputName == "" { + return nil, errors.New("parameter outputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outputName}", url.PathEscape(outputName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.Output != nil { + return req, runtime.MarshalAsJSON(req, *options.Output) + } + return req, nil +} + +// testHandleError handles the Test error response. +func (client *OutputsClient) testHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing output under an existing streaming job. This can be used to partially update (ie. update one or two properties) an output +// without affecting the rest the job or output definition. +// If the operation fails it returns the *Error error type. +func (client *OutputsClient) Update(ctx context.Context, resourceGroupName string, jobName string, outputName string, output Output, options *OutputsUpdateOptions) (OutputsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, jobName, outputName, output, options) + if err != nil { + return OutputsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return OutputsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return OutputsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *OutputsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, jobName string, outputName string, output Output, options *OutputsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/outputs/{outputName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if outputName == "" { + return nil, errors.New("parameter outputName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{outputName}", url.PathEscape(outputName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, output) +} + +// updateHandleResponse handles the Update response. +func (client *OutputsClient) updateHandleResponse(resp *http.Response) (OutputsUpdateResponse, error) { + result := OutputsUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Output); err != nil { + return OutputsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *OutputsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pagers.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pagers.go new file mode 100644 index 000000000000..6e68ffdd1798 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pagers.go @@ -0,0 +1,558 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "net/http" + "reflect" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// ClustersListByResourceGroupPager provides operations for iterating over paged responses. +type ClustersListByResourceGroupPager struct { + client *ClustersClient + current ClustersListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ClustersListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ClustersListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ClustersListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ClusterListResult.NextLink == nil || len(*p.current.ClusterListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ClustersListByResourceGroupResponse page. +func (p *ClustersListByResourceGroupPager) PageResponse() ClustersListByResourceGroupResponse { + return p.current +} + +// ClustersListBySubscriptionPager provides operations for iterating over paged responses. +type ClustersListBySubscriptionPager struct { + client *ClustersClient + current ClustersListBySubscriptionResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ClustersListBySubscriptionResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ClustersListBySubscriptionPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ClustersListBySubscriptionPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ClusterListResult.NextLink == nil || len(*p.current.ClusterListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listBySubscriptionHandleError(resp) + return false + } + result, err := p.client.listBySubscriptionHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ClustersListBySubscriptionResponse page. +func (p *ClustersListBySubscriptionPager) PageResponse() ClustersListBySubscriptionResponse { + return p.current +} + +// ClustersListStreamingJobsPager provides operations for iterating over paged responses. +type ClustersListStreamingJobsPager struct { + client *ClustersClient + current ClustersListStreamingJobsResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, ClustersListStreamingJobsResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *ClustersListStreamingJobsPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *ClustersListStreamingJobsPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.ClusterJobListResult.NextLink == nil || len(*p.current.ClusterJobListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listStreamingJobsHandleError(resp) + return false + } + result, err := p.client.listStreamingJobsHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current ClustersListStreamingJobsResponse page. +func (p *ClustersListStreamingJobsPager) PageResponse() ClustersListStreamingJobsResponse { + return p.current +} + +// FunctionsListByStreamingJobPager provides operations for iterating over paged responses. +type FunctionsListByStreamingJobPager struct { + client *FunctionsClient + current FunctionsListByStreamingJobResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, FunctionsListByStreamingJobResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *FunctionsListByStreamingJobPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *FunctionsListByStreamingJobPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.FunctionListResult.NextLink == nil || len(*p.current.FunctionListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByStreamingJobHandleError(resp) + return false + } + result, err := p.client.listByStreamingJobHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current FunctionsListByStreamingJobResponse page. +func (p *FunctionsListByStreamingJobPager) PageResponse() FunctionsListByStreamingJobResponse { + return p.current +} + +// InputsListByStreamingJobPager provides operations for iterating over paged responses. +type InputsListByStreamingJobPager struct { + client *InputsClient + current InputsListByStreamingJobResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, InputsListByStreamingJobResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *InputsListByStreamingJobPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *InputsListByStreamingJobPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.InputListResult.NextLink == nil || len(*p.current.InputListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByStreamingJobHandleError(resp) + return false + } + result, err := p.client.listByStreamingJobHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current InputsListByStreamingJobResponse page. +func (p *InputsListByStreamingJobPager) PageResponse() InputsListByStreamingJobResponse { + return p.current +} + +// OperationsListPager provides operations for iterating over paged responses. +type OperationsListPager struct { + client *OperationsClient + current OperationsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OperationsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OperationsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OperationsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OperationListResult.NextLink == nil || len(*p.current.OperationListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OperationsListResponse page. +func (p *OperationsListPager) PageResponse() OperationsListResponse { + return p.current +} + +// OutputsListByStreamingJobPager provides operations for iterating over paged responses. +type OutputsListByStreamingJobPager struct { + client *OutputsClient + current OutputsListByStreamingJobResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, OutputsListByStreamingJobResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *OutputsListByStreamingJobPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *OutputsListByStreamingJobPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.OutputListResult.NextLink == nil || len(*p.current.OutputListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByStreamingJobHandleError(resp) + return false + } + result, err := p.client.listByStreamingJobHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current OutputsListByStreamingJobResponse page. +func (p *OutputsListByStreamingJobPager) PageResponse() OutputsListByStreamingJobResponse { + return p.current +} + +// PrivateEndpointsListByClusterPager provides operations for iterating over paged responses. +type PrivateEndpointsListByClusterPager struct { + client *PrivateEndpointsClient + current PrivateEndpointsListByClusterResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, PrivateEndpointsListByClusterResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *PrivateEndpointsListByClusterPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *PrivateEndpointsListByClusterPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.PrivateEndpointListResult.NextLink == nil || len(*p.current.PrivateEndpointListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByClusterHandleError(resp) + return false + } + result, err := p.client.listByClusterHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current PrivateEndpointsListByClusterResponse page. +func (p *PrivateEndpointsListByClusterPager) PageResponse() PrivateEndpointsListByClusterResponse { + return p.current +} + +// StreamingJobsListByResourceGroupPager provides operations for iterating over paged responses. +type StreamingJobsListByResourceGroupPager struct { + client *StreamingJobsClient + current StreamingJobsListByResourceGroupResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StreamingJobsListByResourceGroupResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StreamingJobsListByResourceGroupPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StreamingJobsListByResourceGroupPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StreamingJobListResult.NextLink == nil || len(*p.current.StreamingJobListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listByResourceGroupHandleError(resp) + return false + } + result, err := p.client.listByResourceGroupHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StreamingJobsListByResourceGroupResponse page. +func (p *StreamingJobsListByResourceGroupPager) PageResponse() StreamingJobsListByResourceGroupResponse { + return p.current +} + +// StreamingJobsListPager provides operations for iterating over paged responses. +type StreamingJobsListPager struct { + client *StreamingJobsClient + current StreamingJobsListResponse + err error + requester func(context.Context) (*policy.Request, error) + advancer func(context.Context, StreamingJobsListResponse) (*policy.Request, error) +} + +// Err returns the last error encountered while paging. +func (p *StreamingJobsListPager) Err() error { + return p.err +} + +// NextPage returns true if the pager advanced to the next page. +// Returns false if there are no more pages or an error occurred. +func (p *StreamingJobsListPager) NextPage(ctx context.Context) bool { + var req *policy.Request + var err error + if !reflect.ValueOf(p.current).IsZero() { + if p.current.StreamingJobListResult.NextLink == nil || len(*p.current.StreamingJobListResult.NextLink) == 0 { + return false + } + req, err = p.advancer(ctx, p.current) + } else { + req, err = p.requester(ctx) + } + if err != nil { + p.err = err + return false + } + resp, err := p.client.pl.Do(req) + if err != nil { + p.err = err + return false + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + p.err = p.client.listHandleError(resp) + return false + } + result, err := p.client.listHandleResponse(resp) + if err != nil { + p.err = err + return false + } + p.current = result + return true +} + +// PageResponse returns the current StreamingJobsListResponse page. +func (p *StreamingJobsListPager) PageResponse() StreamingJobsListResponse { + return p.current +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pollers.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pollers.go new file mode 100644 index 000000000000..30c123173af9 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_pollers.go @@ -0,0 +1,661 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "net/http" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" +) + +// ClustersCreateOrUpdatePoller provides polling facilities until the operation reaches a terminal state. +type ClustersCreateOrUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ClustersCreateOrUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ClustersCreateOrUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ClustersCreateOrUpdateResponse will be returned. +func (p *ClustersCreateOrUpdatePoller) FinalResponse(ctx context.Context) (ClustersCreateOrUpdateResponse, error) { + respType := ClustersCreateOrUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Cluster) + if err != nil { + return ClustersCreateOrUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ClustersCreateOrUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// ClustersDeletePoller provides polling facilities until the operation reaches a terminal state. +type ClustersDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ClustersDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ClustersDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ClustersDeleteResponse will be returned. +func (p *ClustersDeletePoller) FinalResponse(ctx context.Context) (ClustersDeleteResponse, error) { + respType := ClustersDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return ClustersDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ClustersDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// ClustersUpdatePoller provides polling facilities until the operation reaches a terminal state. +type ClustersUpdatePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *ClustersUpdatePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *ClustersUpdatePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final ClustersUpdateResponse will be returned. +func (p *ClustersUpdatePoller) FinalResponse(ctx context.Context) (ClustersUpdateResponse, error) { + respType := ClustersUpdateResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.Cluster) + if err != nil { + return ClustersUpdateResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *ClustersUpdatePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// FunctionsTestPoller provides polling facilities until the operation reaches a terminal state. +type FunctionsTestPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *FunctionsTestPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *FunctionsTestPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final FunctionsTestResponse will be returned. +func (p *FunctionsTestPoller) FinalResponse(ctx context.Context) (FunctionsTestResponse, error) { + respType := FunctionsTestResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.ResourceTestStatus) + if err != nil { + return FunctionsTestResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *FunctionsTestPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// InputsTestPoller provides polling facilities until the operation reaches a terminal state. +type InputsTestPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *InputsTestPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *InputsTestPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final InputsTestResponse will be returned. +func (p *InputsTestPoller) FinalResponse(ctx context.Context) (InputsTestResponse, error) { + respType := InputsTestResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.ResourceTestStatus) + if err != nil { + return InputsTestResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *InputsTestPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// OutputsTestPoller provides polling facilities until the operation reaches a terminal state. +type OutputsTestPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *OutputsTestPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *OutputsTestPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final OutputsTestResponse will be returned. +func (p *OutputsTestPoller) FinalResponse(ctx context.Context) (OutputsTestResponse, error) { + respType := OutputsTestResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.ResourceTestStatus) + if err != nil { + return OutputsTestResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *OutputsTestPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// PrivateEndpointsDeletePoller provides polling facilities until the operation reaches a terminal state. +type PrivateEndpointsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *PrivateEndpointsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *PrivateEndpointsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final PrivateEndpointsDeleteResponse will be returned. +func (p *PrivateEndpointsDeletePoller) FinalResponse(ctx context.Context) (PrivateEndpointsDeleteResponse, error) { + respType := PrivateEndpointsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return PrivateEndpointsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *PrivateEndpointsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingJobsCreateOrReplacePoller provides polling facilities until the operation reaches a terminal state. +type StreamingJobsCreateOrReplacePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingJobsCreateOrReplacePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingJobsCreateOrReplacePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingJobsCreateOrReplaceResponse will be returned. +func (p *StreamingJobsCreateOrReplacePoller) FinalResponse(ctx context.Context) (StreamingJobsCreateOrReplaceResponse, error) { + respType := StreamingJobsCreateOrReplaceResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.StreamingJob) + if err != nil { + return StreamingJobsCreateOrReplaceResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingJobsCreateOrReplacePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingJobsDeletePoller provides polling facilities until the operation reaches a terminal state. +type StreamingJobsDeletePoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingJobsDeletePoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingJobsDeletePoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingJobsDeleteResponse will be returned. +func (p *StreamingJobsDeletePoller) FinalResponse(ctx context.Context) (StreamingJobsDeleteResponse, error) { + respType := StreamingJobsDeleteResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingJobsDeleteResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingJobsDeletePoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingJobsStartPoller provides polling facilities until the operation reaches a terminal state. +type StreamingJobsStartPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingJobsStartPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingJobsStartPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingJobsStartResponse will be returned. +func (p *StreamingJobsStartPoller) FinalResponse(ctx context.Context) (StreamingJobsStartResponse, error) { + respType := StreamingJobsStartResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingJobsStartResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingJobsStartPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// StreamingJobsStopPoller provides polling facilities until the operation reaches a terminal state. +type StreamingJobsStopPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *StreamingJobsStopPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *StreamingJobsStopPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final StreamingJobsStopResponse will be returned. +func (p *StreamingJobsStopPoller) FinalResponse(ctx context.Context) (StreamingJobsStopResponse, error) { + respType := StreamingJobsStopResponse{} + resp, err := p.pt.FinalResponse(ctx, nil) + if err != nil { + return StreamingJobsStopResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *StreamingJobsStopPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SubscriptionsSampleInputPoller provides polling facilities until the operation reaches a terminal state. +type SubscriptionsSampleInputPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SubscriptionsSampleInputPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SubscriptionsSampleInputPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SubscriptionsSampleInputResponse will be returned. +func (p *SubscriptionsSampleInputPoller) FinalResponse(ctx context.Context) (SubscriptionsSampleInputResponse, error) { + respType := SubscriptionsSampleInputResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.SampleInputResult) + if err != nil { + return SubscriptionsSampleInputResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SubscriptionsSampleInputPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SubscriptionsTestInputPoller provides polling facilities until the operation reaches a terminal state. +type SubscriptionsTestInputPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SubscriptionsTestInputPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SubscriptionsTestInputPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SubscriptionsTestInputResponse will be returned. +func (p *SubscriptionsTestInputPoller) FinalResponse(ctx context.Context) (SubscriptionsTestInputResponse, error) { + respType := SubscriptionsTestInputResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.TestDatasourceResult) + if err != nil { + return SubscriptionsTestInputResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SubscriptionsTestInputPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SubscriptionsTestOutputPoller provides polling facilities until the operation reaches a terminal state. +type SubscriptionsTestOutputPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SubscriptionsTestOutputPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SubscriptionsTestOutputPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SubscriptionsTestOutputResponse will be returned. +func (p *SubscriptionsTestOutputPoller) FinalResponse(ctx context.Context) (SubscriptionsTestOutputResponse, error) { + respType := SubscriptionsTestOutputResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.TestDatasourceResult) + if err != nil { + return SubscriptionsTestOutputResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SubscriptionsTestOutputPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} + +// SubscriptionsTestQueryPoller provides polling facilities until the operation reaches a terminal state. +type SubscriptionsTestQueryPoller struct { + pt *azcore.Poller +} + +// Done returns true if the LRO has reached a terminal state. +func (p *SubscriptionsTestQueryPoller) Done() bool { + return p.pt.Done() +} + +// Poll fetches the latest state of the LRO. It returns an HTTP response or error. +// If the LRO has completed successfully, the poller's state is updated and the HTTP +// response is returned. +// If the LRO has completed with failure or was cancelled, the poller's state is +// updated and the error is returned. +// If the LRO has not reached a terminal state, the poller's state is updated and +// the latest HTTP response is returned. +// If Poll fails, the poller's state is unmodified and the error is returned. +// Calling Poll on an LRO that has reached a terminal state will return the final +// HTTP response or error. +func (p *SubscriptionsTestQueryPoller) Poll(ctx context.Context) (*http.Response, error) { + return p.pt.Poll(ctx) +} + +// FinalResponse performs a final GET to the service and returns the final response +// for the polling operation. If there is an error performing the final GET then an error is returned. +// If the final GET succeeded then the final SubscriptionsTestQueryResponse will be returned. +func (p *SubscriptionsTestQueryPoller) FinalResponse(ctx context.Context) (SubscriptionsTestQueryResponse, error) { + respType := SubscriptionsTestQueryResponse{} + resp, err := p.pt.FinalResponse(ctx, &respType.QueryTestingResult) + if err != nil { + return SubscriptionsTestQueryResponse{}, err + } + respType.RawResponse = resp + return respType, nil +} + +// ResumeToken returns a value representing the poller that can be used to resume +// the LRO at a later time. ResumeTokens are unique per service operation. +func (p *SubscriptionsTestQueryPoller) ResumeToken() (string, error) { + return p.pt.ResumeToken() +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_polymorphic_helpers.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_polymorphic_helpers.go new file mode 100644 index 000000000000..639ea4cce8dc --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_polymorphic_helpers.go @@ -0,0 +1,367 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import "encoding/json" + +func unmarshalFunctionBindingClassification(rawMsg json.RawMessage) (FunctionBindingClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FunctionBindingClassification + switch m["type"] { + case "Microsoft.MachineLearning/WebService": + b = &AzureMachineLearningStudioFunctionBinding{} + case "Microsoft.MachineLearningServices": + b = &AzureMachineLearningServiceFunctionBinding{} + case "Microsoft.StreamAnalytics/CLRUdf": + b = &CSharpFunctionBinding{} + case "Microsoft.StreamAnalytics/JavascriptUdf": + b = &JavaScriptFunctionBinding{} + default: + b = &FunctionBinding{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalFunctionBindingClassificationArray(rawMsg json.RawMessage) ([]FunctionBindingClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FunctionBindingClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFunctionBindingClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalFunctionPropertiesClassification(rawMsg json.RawMessage) (FunctionPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FunctionPropertiesClassification + switch m["type"] { + case "Aggregate": + b = &AggregateFunctionProperties{} + case "Scalar": + b = &ScalarFunctionProperties{} + default: + b = &FunctionProperties{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalFunctionPropertiesClassificationArray(rawMsg json.RawMessage) ([]FunctionPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FunctionPropertiesClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFunctionPropertiesClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalFunctionRetrieveDefaultDefinitionParametersClassification(rawMsg json.RawMessage) (FunctionRetrieveDefaultDefinitionParametersClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b FunctionRetrieveDefaultDefinitionParametersClassification + switch m["bindingType"] { + case "Microsoft.MachineLearning/WebService": + b = &AzureMachineLearningStudioFunctionRetrieveDefaultDefinitionParameters{} + case "Microsoft.MachineLearningServices": + b = &AzureMachineLearningServiceFunctionRetrieveDefaultDefinitionParameters{} + case "Microsoft.StreamAnalytics/CLRUdf": + b = &CSharpFunctionRetrieveDefaultDefinitionParameters{} + case "Microsoft.StreamAnalytics/JavascriptUdf": + b = &JavaScriptFunctionRetrieveDefaultDefinitionParameters{} + default: + b = &FunctionRetrieveDefaultDefinitionParameters{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalFunctionRetrieveDefaultDefinitionParametersClassificationArray(rawMsg json.RawMessage) ([]FunctionRetrieveDefaultDefinitionParametersClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]FunctionRetrieveDefaultDefinitionParametersClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalFunctionRetrieveDefaultDefinitionParametersClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalInputPropertiesClassification(rawMsg json.RawMessage) (InputPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b InputPropertiesClassification + switch m["type"] { + case "Reference": + b = &ReferenceInputProperties{} + case "Stream": + b = &StreamInputProperties{} + default: + b = &InputProperties{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalInputPropertiesClassificationArray(rawMsg json.RawMessage) ([]InputPropertiesClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]InputPropertiesClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalInputPropertiesClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalOutputDataSourceClassification(rawMsg json.RawMessage) (OutputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b OutputDataSourceClassification + switch m["type"] { + case "Microsoft.AzureFunction": + b = &AzureFunctionOutputDataSource{} + case "Microsoft.DataLake/Accounts": + b = &AzureDataLakeStoreOutputDataSource{} + case "Microsoft.EventHub/EventHub": + b = &EventHubV2OutputDataSource{} + case "Microsoft.ServiceBus/EventHub": + b = &EventHubOutputDataSource{} + case "Microsoft.ServiceBus/Queue": + b = &ServiceBusQueueOutputDataSource{} + case "Microsoft.ServiceBus/Topic": + b = &ServiceBusTopicOutputDataSource{} + case "Microsoft.Sql/Server/DataWarehouse": + b = &AzureSynapseOutputDataSource{} + case "Microsoft.Sql/Server/Database": + b = &AzureSQLDatabaseOutputDataSource{} + case "Microsoft.Storage/Blob": + b = &BlobOutputDataSource{} + case "Microsoft.Storage/DocumentDB": + b = &DocumentDbOutputDataSource{} + case "Microsoft.Storage/Table": + b = &AzureTableOutputDataSource{} + case "PowerBI": + b = &PowerBIOutputDataSource{} + case "Raw": + b = &RawOutputDatasource{} + default: + b = &OutputDataSource{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalOutputDataSourceClassificationArray(rawMsg json.RawMessage) ([]OutputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]OutputDataSourceClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalOutputDataSourceClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalReferenceInputDataSourceClassification(rawMsg json.RawMessage) (ReferenceInputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b ReferenceInputDataSourceClassification + switch m["type"] { + case "Microsoft.Sql/Server/Database": + b = &AzureSQLReferenceInputDataSource{} + case "Microsoft.Storage/Blob": + b = &BlobReferenceInputDataSource{} + case "Raw": + b = &RawReferenceInputDataSource{} + default: + b = &ReferenceInputDataSource{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalReferenceInputDataSourceClassificationArray(rawMsg json.RawMessage) ([]ReferenceInputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]ReferenceInputDataSourceClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalReferenceInputDataSourceClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalSerializationClassification(rawMsg json.RawMessage) (SerializationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b SerializationClassification + switch m["type"] { + case string(EventSerializationTypeAvro): + b = &AvroSerialization{} + case string(EventSerializationTypeCSV): + b = &CSVSerialization{} + case string(EventSerializationTypeCustomClr): + b = &CustomClrSerialization{} + case string(EventSerializationTypeJSON): + b = &JSONSerialization{} + case string(EventSerializationTypeParquet): + b = &ParquetSerialization{} + default: + b = &Serialization{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalSerializationClassificationArray(rawMsg json.RawMessage) ([]SerializationClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]SerializationClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalSerializationClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} + +func unmarshalStreamInputDataSourceClassification(rawMsg json.RawMessage) (StreamInputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var m map[string]interface{} + if err := json.Unmarshal(rawMsg, &m); err != nil { + return nil, err + } + var b StreamInputDataSourceClassification + switch m["type"] { + case "Microsoft.Devices/IotHubs": + b = &IoTHubStreamInputDataSource{} + case "Microsoft.EventHub/EventHub": + b = &EventHubV2StreamInputDataSource{} + case "Microsoft.ServiceBus/EventHub": + b = &EventHubStreamInputDataSource{} + case "Microsoft.Storage/Blob": + b = &BlobStreamInputDataSource{} + case "Raw": + b = &RawStreamInputDataSource{} + default: + b = &StreamInputDataSource{} + } + return b, json.Unmarshal(rawMsg, b) +} + +func unmarshalStreamInputDataSourceClassificationArray(rawMsg json.RawMessage) ([]StreamInputDataSourceClassification, error) { + if rawMsg == nil { + return nil, nil + } + var rawMessages []json.RawMessage + if err := json.Unmarshal(rawMsg, &rawMessages); err != nil { + return nil, err + } + fArray := make([]StreamInputDataSourceClassification, len(rawMessages)) + for index, rawMessage := range rawMessages { + f, err := unmarshalStreamInputDataSourceClassification(rawMessage) + if err != nil { + return nil, err + } + fArray[index] = f + } + return fArray, nil +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_privateendpoints_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_privateendpoints_client.go new file mode 100644 index 000000000000..f2d7e0004111 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_privateendpoints_client.go @@ -0,0 +1,322 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// PrivateEndpointsClient contains the methods for the PrivateEndpoints group. +// Don't use this type directly, use NewPrivateEndpointsClient() instead. +type PrivateEndpointsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewPrivateEndpointsClient creates a new instance of PrivateEndpointsClient with the specified values. +func NewPrivateEndpointsClient(con *arm.Connection, subscriptionID string) *PrivateEndpointsClient { + return &PrivateEndpointsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrUpdate - Creates a Stream Analytics Private Endpoint or replaces an already existing Private Endpoint. +// If the operation fails it returns the *Error error type. +func (client *PrivateEndpointsClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, privateEndpoint PrivateEndpoint, options *PrivateEndpointsCreateOrUpdateOptions) (PrivateEndpointsCreateOrUpdateResponse, error) { + req, err := client.createOrUpdateCreateRequest(ctx, resourceGroupName, clusterName, privateEndpointName, privateEndpoint, options) + if err != nil { + return PrivateEndpointsCreateOrUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointsCreateOrUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return PrivateEndpointsCreateOrUpdateResponse{}, client.createOrUpdateHandleError(resp) + } + return client.createOrUpdateHandleResponse(resp) +} + +// createOrUpdateCreateRequest creates the CreateOrUpdate request. +func (client *PrivateEndpointsClient) createOrUpdateCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, privateEndpoint PrivateEndpoint, options *PrivateEndpointsCreateOrUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}/privateEndpoints/{privateEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, privateEndpoint) +} + +// createOrUpdateHandleResponse handles the CreateOrUpdate response. +func (client *PrivateEndpointsClient) createOrUpdateHandleResponse(resp *http.Response) (PrivateEndpointsCreateOrUpdateResponse, error) { + result := PrivateEndpointsCreateOrUpdateResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpoint); err != nil { + return PrivateEndpointsCreateOrUpdateResponse{}, err + } + return result, nil +} + +// createOrUpdateHandleError handles the CreateOrUpdate error response. +func (client *PrivateEndpointsClient) createOrUpdateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Delete the specified private endpoint. +// If the operation fails it returns the *Error error type. +func (client *PrivateEndpointsClient) BeginDelete(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, options *PrivateEndpointsBeginDeleteOptions) (PrivateEndpointsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, clusterName, privateEndpointName, options) + if err != nil { + return PrivateEndpointsDeletePollerResponse{}, err + } + result := PrivateEndpointsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("PrivateEndpointsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return PrivateEndpointsDeletePollerResponse{}, err + } + result.Poller = &PrivateEndpointsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Delete the specified private endpoint. +// If the operation fails it returns the *Error error type. +func (client *PrivateEndpointsClient) deleteOperation(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, options *PrivateEndpointsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, clusterName, privateEndpointName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *PrivateEndpointsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, options *PrivateEndpointsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}/privateEndpoints/{privateEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *PrivateEndpointsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets information about the specified Private Endpoint. +// If the operation fails it returns the *Error error type. +func (client *PrivateEndpointsClient) Get(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, options *PrivateEndpointsGetOptions) (PrivateEndpointsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, clusterName, privateEndpointName, options) + if err != nil { + return PrivateEndpointsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return PrivateEndpointsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return PrivateEndpointsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *PrivateEndpointsClient) getCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, privateEndpointName string, options *PrivateEndpointsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}/privateEndpoints/{privateEndpointName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + if privateEndpointName == "" { + return nil, errors.New("parameter privateEndpointName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{privateEndpointName}", url.PathEscape(privateEndpointName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *PrivateEndpointsClient) getHandleResponse(resp *http.Response) (PrivateEndpointsGetResponse, error) { + result := PrivateEndpointsGetResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpoint); err != nil { + return PrivateEndpointsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *PrivateEndpointsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByCluster - Lists the private endpoints in the cluster. +// If the operation fails it returns the *Error error type. +func (client *PrivateEndpointsClient) ListByCluster(resourceGroupName string, clusterName string, options *PrivateEndpointsListByClusterOptions) *PrivateEndpointsListByClusterPager { + return &PrivateEndpointsListByClusterPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByClusterCreateRequest(ctx, resourceGroupName, clusterName, options) + }, + advancer: func(ctx context.Context, resp PrivateEndpointsListByClusterResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.PrivateEndpointListResult.NextLink) + }, + } +} + +// listByClusterCreateRequest creates the ListByCluster request. +func (client *PrivateEndpointsClient) listByClusterCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, options *PrivateEndpointsListByClusterOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/clusters/{clusterName}/privateEndpoints" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if clusterName == "" { + return nil, errors.New("parameter clusterName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{clusterName}", url.PathEscape(clusterName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2020-03-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByClusterHandleResponse handles the ListByCluster response. +func (client *PrivateEndpointsClient) listByClusterHandleResponse(resp *http.Response) (PrivateEndpointsListByClusterResponse, error) { + result := PrivateEndpointsListByClusterResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.PrivateEndpointListResult); err != nil { + return PrivateEndpointsListByClusterResponse{}, err + } + return result, nil +} + +// listByClusterHandleError handles the ListByCluster error response. +func (client *PrivateEndpointsClient) listByClusterHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_response_types.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_response_types.go new file mode 100644 index 000000000000..e2f8d5b61598 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_response_types.go @@ -0,0 +1,1143 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "net/http" + "time" + + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" +) + +// ClustersCreateOrUpdatePollerResponse contains the response from method Clusters.CreateOrUpdate. +type ClustersCreateOrUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *ClustersCreateOrUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ClustersCreateOrUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ClustersCreateOrUpdateResponse, error) { + respType := ClustersCreateOrUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Cluster) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ClustersCreateOrUpdatePollerResponse from the provided client and resume token. +func (l *ClustersCreateOrUpdatePollerResponse) Resume(ctx context.Context, client *ClustersClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ClustersClient.CreateOrUpdate", token, client.pl, client.createOrUpdateHandleError) + if err != nil { + return err + } + poller := &ClustersCreateOrUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ClustersCreateOrUpdateResponse contains the response from method Clusters.CreateOrUpdate. +type ClustersCreateOrUpdateResponse struct { + ClustersCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersCreateOrUpdateResult contains the result from method Clusters.CreateOrUpdate. +type ClustersCreateOrUpdateResult struct { + Cluster +} + +// ClustersDeletePollerResponse contains the response from method Clusters.Delete. +type ClustersDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *ClustersDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ClustersDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ClustersDeleteResponse, error) { + respType := ClustersDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ClustersDeletePollerResponse from the provided client and resume token. +func (l *ClustersDeletePollerResponse) Resume(ctx context.Context, client *ClustersClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ClustersClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &ClustersDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ClustersDeleteResponse contains the response from method Clusters.Delete. +type ClustersDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersGetResponse contains the response from method Clusters.Get. +type ClustersGetResponse struct { + ClustersGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersGetResult contains the result from method Clusters.Get. +type ClustersGetResult struct { + Cluster +} + +// ClustersListByResourceGroupResponse contains the response from method Clusters.ListByResourceGroup. +type ClustersListByResourceGroupResponse struct { + ClustersListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersListByResourceGroupResult contains the result from method Clusters.ListByResourceGroup. +type ClustersListByResourceGroupResult struct { + ClusterListResult +} + +// ClustersListBySubscriptionResponse contains the response from method Clusters.ListBySubscription. +type ClustersListBySubscriptionResponse struct { + ClustersListBySubscriptionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersListBySubscriptionResult contains the result from method Clusters.ListBySubscription. +type ClustersListBySubscriptionResult struct { + ClusterListResult +} + +// ClustersListStreamingJobsResponse contains the response from method Clusters.ListStreamingJobs. +type ClustersListStreamingJobsResponse struct { + ClustersListStreamingJobsResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersListStreamingJobsResult contains the result from method Clusters.ListStreamingJobs. +type ClustersListStreamingJobsResult struct { + ClusterJobListResult +} + +// ClustersUpdatePollerResponse contains the response from method Clusters.Update. +type ClustersUpdatePollerResponse struct { + // Poller contains an initialized poller. + Poller *ClustersUpdatePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l ClustersUpdatePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (ClustersUpdateResponse, error) { + respType := ClustersUpdateResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.Cluster) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a ClustersUpdatePollerResponse from the provided client and resume token. +func (l *ClustersUpdatePollerResponse) Resume(ctx context.Context, client *ClustersClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("ClustersClient.Update", token, client.pl, client.updateHandleError) + if err != nil { + return err + } + poller := &ClustersUpdatePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// ClustersUpdateResponse contains the response from method Clusters.Update. +type ClustersUpdateResponse struct { + ClustersUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// ClustersUpdateResult contains the result from method Clusters.Update. +type ClustersUpdateResult struct { + Cluster +} + +// FunctionsCreateOrReplaceResponse contains the response from method Functions.CreateOrReplace. +type FunctionsCreateOrReplaceResponse struct { + FunctionsCreateOrReplaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsCreateOrReplaceResult contains the result from method Functions.CreateOrReplace. +type FunctionsCreateOrReplaceResult struct { + Function + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// FunctionsDeleteResponse contains the response from method Functions.Delete. +type FunctionsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsGetResponse contains the response from method Functions.Get. +type FunctionsGetResponse struct { + FunctionsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsGetResult contains the result from method Functions.Get. +type FunctionsGetResult struct { + Function + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// FunctionsListByStreamingJobResponse contains the response from method Functions.ListByStreamingJob. +type FunctionsListByStreamingJobResponse struct { + FunctionsListByStreamingJobResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsListByStreamingJobResult contains the result from method Functions.ListByStreamingJob. +type FunctionsListByStreamingJobResult struct { + FunctionListResult +} + +// FunctionsRetrieveDefaultDefinitionResponse contains the response from method Functions.RetrieveDefaultDefinition. +type FunctionsRetrieveDefaultDefinitionResponse struct { + FunctionsRetrieveDefaultDefinitionResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsRetrieveDefaultDefinitionResult contains the result from method Functions.RetrieveDefaultDefinition. +type FunctionsRetrieveDefaultDefinitionResult struct { + Function +} + +// FunctionsTestPollerResponse contains the response from method Functions.Test. +type FunctionsTestPollerResponse struct { + // Poller contains an initialized poller. + Poller *FunctionsTestPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l FunctionsTestPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (FunctionsTestResponse, error) { + respType := FunctionsTestResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.ResourceTestStatus) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a FunctionsTestPollerResponse from the provided client and resume token. +func (l *FunctionsTestPollerResponse) Resume(ctx context.Context, client *FunctionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("FunctionsClient.Test", token, client.pl, client.testHandleError) + if err != nil { + return err + } + poller := &FunctionsTestPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// FunctionsTestResponse contains the response from method Functions.Test. +type FunctionsTestResponse struct { + FunctionsTestResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsTestResult contains the result from method Functions.Test. +type FunctionsTestResult struct { + ResourceTestStatus +} + +// FunctionsUpdateResponse contains the response from method Functions.Update. +type FunctionsUpdateResponse struct { + FunctionsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// FunctionsUpdateResult contains the result from method Functions.Update. +type FunctionsUpdateResult struct { + Function + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// InputsCreateOrReplaceResponse contains the response from method Inputs.CreateOrReplace. +type InputsCreateOrReplaceResponse struct { + InputsCreateOrReplaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsCreateOrReplaceResult contains the result from method Inputs.CreateOrReplace. +type InputsCreateOrReplaceResult struct { + Input + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// InputsDeleteResponse contains the response from method Inputs.Delete. +type InputsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsGetResponse contains the response from method Inputs.Get. +type InputsGetResponse struct { + InputsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsGetResult contains the result from method Inputs.Get. +type InputsGetResult struct { + Input + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// InputsListByStreamingJobResponse contains the response from method Inputs.ListByStreamingJob. +type InputsListByStreamingJobResponse struct { + InputsListByStreamingJobResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsListByStreamingJobResult contains the result from method Inputs.ListByStreamingJob. +type InputsListByStreamingJobResult struct { + InputListResult +} + +// InputsTestPollerResponse contains the response from method Inputs.Test. +type InputsTestPollerResponse struct { + // Poller contains an initialized poller. + Poller *InputsTestPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l InputsTestPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (InputsTestResponse, error) { + respType := InputsTestResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.ResourceTestStatus) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a InputsTestPollerResponse from the provided client and resume token. +func (l *InputsTestPollerResponse) Resume(ctx context.Context, client *InputsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("InputsClient.Test", token, client.pl, client.testHandleError) + if err != nil { + return err + } + poller := &InputsTestPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// InputsTestResponse contains the response from method Inputs.Test. +type InputsTestResponse struct { + InputsTestResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsTestResult contains the result from method Inputs.Test. +type InputsTestResult struct { + ResourceTestStatus +} + +// InputsUpdateResponse contains the response from method Inputs.Update. +type InputsUpdateResponse struct { + InputsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// InputsUpdateResult contains the result from method Inputs.Update. +type InputsUpdateResult struct { + Input + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// OperationsListResponse contains the response from method Operations.List. +type OperationsListResponse struct { + OperationsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OperationsListResult contains the result from method Operations.List. +type OperationsListResult struct { + OperationListResult +} + +// OutputsCreateOrReplaceResponse contains the response from method Outputs.CreateOrReplace. +type OutputsCreateOrReplaceResponse struct { + OutputsCreateOrReplaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsCreateOrReplaceResult contains the result from method Outputs.CreateOrReplace. +type OutputsCreateOrReplaceResult struct { + Output + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// OutputsDeleteResponse contains the response from method Outputs.Delete. +type OutputsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsGetResponse contains the response from method Outputs.Get. +type OutputsGetResponse struct { + OutputsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsGetResult contains the result from method Outputs.Get. +type OutputsGetResult struct { + Output + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// OutputsListByStreamingJobResponse contains the response from method Outputs.ListByStreamingJob. +type OutputsListByStreamingJobResponse struct { + OutputsListByStreamingJobResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsListByStreamingJobResult contains the result from method Outputs.ListByStreamingJob. +type OutputsListByStreamingJobResult struct { + OutputListResult +} + +// OutputsTestPollerResponse contains the response from method Outputs.Test. +type OutputsTestPollerResponse struct { + // Poller contains an initialized poller. + Poller *OutputsTestPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l OutputsTestPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (OutputsTestResponse, error) { + respType := OutputsTestResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.ResourceTestStatus) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a OutputsTestPollerResponse from the provided client and resume token. +func (l *OutputsTestPollerResponse) Resume(ctx context.Context, client *OutputsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("OutputsClient.Test", token, client.pl, client.testHandleError) + if err != nil { + return err + } + poller := &OutputsTestPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// OutputsTestResponse contains the response from method Outputs.Test. +type OutputsTestResponse struct { + OutputsTestResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsTestResult contains the result from method Outputs.Test. +type OutputsTestResult struct { + ResourceTestStatus +} + +// OutputsUpdateResponse contains the response from method Outputs.Update. +type OutputsUpdateResponse struct { + OutputsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// OutputsUpdateResult contains the result from method Outputs.Update. +type OutputsUpdateResult struct { + Output + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// PrivateEndpointsCreateOrUpdateResponse contains the response from method PrivateEndpoints.CreateOrUpdate. +type PrivateEndpointsCreateOrUpdateResponse struct { + PrivateEndpointsCreateOrUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointsCreateOrUpdateResult contains the result from method PrivateEndpoints.CreateOrUpdate. +type PrivateEndpointsCreateOrUpdateResult struct { + PrivateEndpoint +} + +// PrivateEndpointsDeletePollerResponse contains the response from method PrivateEndpoints.Delete. +type PrivateEndpointsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *PrivateEndpointsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l PrivateEndpointsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (PrivateEndpointsDeleteResponse, error) { + respType := PrivateEndpointsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a PrivateEndpointsDeletePollerResponse from the provided client and resume token. +func (l *PrivateEndpointsDeletePollerResponse) Resume(ctx context.Context, client *PrivateEndpointsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("PrivateEndpointsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &PrivateEndpointsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// PrivateEndpointsDeleteResponse contains the response from method PrivateEndpoints.Delete. +type PrivateEndpointsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointsGetResponse contains the response from method PrivateEndpoints.Get. +type PrivateEndpointsGetResponse struct { + PrivateEndpointsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointsGetResult contains the result from method PrivateEndpoints.Get. +type PrivateEndpointsGetResult struct { + PrivateEndpoint +} + +// PrivateEndpointsListByClusterResponse contains the response from method PrivateEndpoints.ListByCluster. +type PrivateEndpointsListByClusterResponse struct { + PrivateEndpointsListByClusterResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PrivateEndpointsListByClusterResult contains the result from method PrivateEndpoints.ListByCluster. +type PrivateEndpointsListByClusterResult struct { + PrivateEndpointListResult +} + +// StreamingJobsCreateOrReplacePollerResponse contains the response from method StreamingJobs.CreateOrReplace. +type StreamingJobsCreateOrReplacePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingJobsCreateOrReplacePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingJobsCreateOrReplacePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingJobsCreateOrReplaceResponse, error) { + respType := StreamingJobsCreateOrReplaceResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.StreamingJob) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingJobsCreateOrReplacePollerResponse from the provided client and resume token. +func (l *StreamingJobsCreateOrReplacePollerResponse) Resume(ctx context.Context, client *StreamingJobsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingJobsClient.CreateOrReplace", token, client.pl, client.createOrReplaceHandleError) + if err != nil { + return err + } + poller := &StreamingJobsCreateOrReplacePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingJobsCreateOrReplaceResponse contains the response from method StreamingJobs.CreateOrReplace. +type StreamingJobsCreateOrReplaceResponse struct { + StreamingJobsCreateOrReplaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsCreateOrReplaceResult contains the result from method StreamingJobs.CreateOrReplace. +type StreamingJobsCreateOrReplaceResult struct { + StreamingJob +} + +// StreamingJobsDeletePollerResponse contains the response from method StreamingJobs.Delete. +type StreamingJobsDeletePollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingJobsDeletePoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingJobsDeletePollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingJobsDeleteResponse, error) { + respType := StreamingJobsDeleteResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingJobsDeletePollerResponse from the provided client and resume token. +func (l *StreamingJobsDeletePollerResponse) Resume(ctx context.Context, client *StreamingJobsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingJobsClient.Delete", token, client.pl, client.deleteHandleError) + if err != nil { + return err + } + poller := &StreamingJobsDeletePoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingJobsDeleteResponse contains the response from method StreamingJobs.Delete. +type StreamingJobsDeleteResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsGetResponse contains the response from method StreamingJobs.Get. +type StreamingJobsGetResponse struct { + StreamingJobsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsGetResult contains the result from method StreamingJobs.Get. +type StreamingJobsGetResult struct { + StreamingJob + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// StreamingJobsListByResourceGroupResponse contains the response from method StreamingJobs.ListByResourceGroup. +type StreamingJobsListByResourceGroupResponse struct { + StreamingJobsListByResourceGroupResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsListByResourceGroupResult contains the result from method StreamingJobs.ListByResourceGroup. +type StreamingJobsListByResourceGroupResult struct { + StreamingJobListResult +} + +// StreamingJobsListResponse contains the response from method StreamingJobs.List. +type StreamingJobsListResponse struct { + StreamingJobsListResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsListResult contains the result from method StreamingJobs.List. +type StreamingJobsListResult struct { + StreamingJobListResult +} + +// StreamingJobsStartPollerResponse contains the response from method StreamingJobs.Start. +type StreamingJobsStartPollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingJobsStartPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingJobsStartPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingJobsStartResponse, error) { + respType := StreamingJobsStartResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingJobsStartPollerResponse from the provided client and resume token. +func (l *StreamingJobsStartPollerResponse) Resume(ctx context.Context, client *StreamingJobsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingJobsClient.Start", token, client.pl, client.startHandleError) + if err != nil { + return err + } + poller := &StreamingJobsStartPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingJobsStartResponse contains the response from method StreamingJobs.Start. +type StreamingJobsStartResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsStopPollerResponse contains the response from method StreamingJobs.Stop. +type StreamingJobsStopPollerResponse struct { + // Poller contains an initialized poller. + Poller *StreamingJobsStopPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l StreamingJobsStopPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (StreamingJobsStopResponse, error) { + respType := StreamingJobsStopResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, nil) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a StreamingJobsStopPollerResponse from the provided client and resume token. +func (l *StreamingJobsStopPollerResponse) Resume(ctx context.Context, client *StreamingJobsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("StreamingJobsClient.Stop", token, client.pl, client.stopHandleError) + if err != nil { + return err + } + poller := &StreamingJobsStopPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// StreamingJobsStopResponse contains the response from method StreamingJobs.Stop. +type StreamingJobsStopResponse struct { + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsUpdateResponse contains the response from method StreamingJobs.Update. +type StreamingJobsUpdateResponse struct { + StreamingJobsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// StreamingJobsUpdateResult contains the result from method StreamingJobs.Update. +type StreamingJobsUpdateResult struct { + StreamingJob + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// SubscriptionsCompileQueryResponse contains the response from method Subscriptions.CompileQuery. +type SubscriptionsCompileQueryResponse struct { + SubscriptionsCompileQueryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsCompileQueryResult contains the result from method Subscriptions.CompileQuery. +type SubscriptionsCompileQueryResult struct { + QueryCompilationResult +} + +// SubscriptionsListQuotasResponse contains the response from method Subscriptions.ListQuotas. +type SubscriptionsListQuotasResponse struct { + SubscriptionsListQuotasResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsListQuotasResult contains the result from method Subscriptions.ListQuotas. +type SubscriptionsListQuotasResult struct { + SubscriptionQuotasListResult +} + +// SubscriptionsSampleInputPollerResponse contains the response from method Subscriptions.SampleInput. +type SubscriptionsSampleInputPollerResponse struct { + // Poller contains an initialized poller. + Poller *SubscriptionsSampleInputPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SubscriptionsSampleInputPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SubscriptionsSampleInputResponse, error) { + respType := SubscriptionsSampleInputResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.SampleInputResult) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SubscriptionsSampleInputPollerResponse from the provided client and resume token. +func (l *SubscriptionsSampleInputPollerResponse) Resume(ctx context.Context, client *SubscriptionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SubscriptionsClient.SampleInput", token, client.pl, client.sampleInputHandleError) + if err != nil { + return err + } + poller := &SubscriptionsSampleInputPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SubscriptionsSampleInputResponse contains the response from method Subscriptions.SampleInput. +type SubscriptionsSampleInputResponse struct { + SubscriptionsSampleInputResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsSampleInputResult contains the result from method Subscriptions.SampleInput. +type SubscriptionsSampleInputResult struct { + SampleInputResult +} + +// SubscriptionsTestInputPollerResponse contains the response from method Subscriptions.TestInput. +type SubscriptionsTestInputPollerResponse struct { + // Poller contains an initialized poller. + Poller *SubscriptionsTestInputPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SubscriptionsTestInputPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SubscriptionsTestInputResponse, error) { + respType := SubscriptionsTestInputResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.TestDatasourceResult) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SubscriptionsTestInputPollerResponse from the provided client and resume token. +func (l *SubscriptionsTestInputPollerResponse) Resume(ctx context.Context, client *SubscriptionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SubscriptionsClient.TestInput", token, client.pl, client.testInputHandleError) + if err != nil { + return err + } + poller := &SubscriptionsTestInputPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SubscriptionsTestInputResponse contains the response from method Subscriptions.TestInput. +type SubscriptionsTestInputResponse struct { + SubscriptionsTestInputResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsTestInputResult contains the result from method Subscriptions.TestInput. +type SubscriptionsTestInputResult struct { + TestDatasourceResult +} + +// SubscriptionsTestOutputPollerResponse contains the response from method Subscriptions.TestOutput. +type SubscriptionsTestOutputPollerResponse struct { + // Poller contains an initialized poller. + Poller *SubscriptionsTestOutputPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SubscriptionsTestOutputPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SubscriptionsTestOutputResponse, error) { + respType := SubscriptionsTestOutputResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.TestDatasourceResult) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SubscriptionsTestOutputPollerResponse from the provided client and resume token. +func (l *SubscriptionsTestOutputPollerResponse) Resume(ctx context.Context, client *SubscriptionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SubscriptionsClient.TestOutput", token, client.pl, client.testOutputHandleError) + if err != nil { + return err + } + poller := &SubscriptionsTestOutputPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SubscriptionsTestOutputResponse contains the response from method Subscriptions.TestOutput. +type SubscriptionsTestOutputResponse struct { + SubscriptionsTestOutputResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsTestOutputResult contains the result from method Subscriptions.TestOutput. +type SubscriptionsTestOutputResult struct { + TestDatasourceResult +} + +// SubscriptionsTestQueryPollerResponse contains the response from method Subscriptions.TestQuery. +type SubscriptionsTestQueryPollerResponse struct { + // Poller contains an initialized poller. + Poller *SubscriptionsTestQueryPoller + + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// PollUntilDone will poll the service endpoint until a terminal state is reached or an error is received. +func (l SubscriptionsTestQueryPollerResponse) PollUntilDone(ctx context.Context, freq time.Duration) (SubscriptionsTestQueryResponse, error) { + respType := SubscriptionsTestQueryResponse{} + resp, err := l.Poller.pt.PollUntilDone(ctx, freq, &respType.QueryTestingResult) + if err != nil { + return respType, err + } + respType.RawResponse = resp + return respType, nil +} + +// Resume rehydrates a SubscriptionsTestQueryPollerResponse from the provided client and resume token. +func (l *SubscriptionsTestQueryPollerResponse) Resume(ctx context.Context, client *SubscriptionsClient, token string) error { + pt, err := armruntime.NewPollerFromResumeToken("SubscriptionsClient.TestQuery", token, client.pl, client.testQueryHandleError) + if err != nil { + return err + } + poller := &SubscriptionsTestQueryPoller{ + pt: pt, + } + resp, err := poller.Poll(ctx) + if err != nil { + return err + } + l.Poller = poller + l.RawResponse = resp + return nil +} + +// SubscriptionsTestQueryResponse contains the response from method Subscriptions.TestQuery. +type SubscriptionsTestQueryResponse struct { + SubscriptionsTestQueryResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// SubscriptionsTestQueryResult contains the result from method Subscriptions.TestQuery. +type SubscriptionsTestQueryResult struct { + QueryTestingResult +} + +// TransformationsCreateOrReplaceResponse contains the response from method Transformations.CreateOrReplace. +type TransformationsCreateOrReplaceResponse struct { + TransformationsCreateOrReplaceResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformationsCreateOrReplaceResult contains the result from method Transformations.CreateOrReplace. +type TransformationsCreateOrReplaceResult struct { + Transformation + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// TransformationsGetResponse contains the response from method Transformations.Get. +type TransformationsGetResponse struct { + TransformationsGetResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformationsGetResult contains the result from method Transformations.Get. +type TransformationsGetResult struct { + Transformation + // ETag contains the information returned from the ETag header response. + ETag *string +} + +// TransformationsUpdateResponse contains the response from method Transformations.Update. +type TransformationsUpdateResponse struct { + TransformationsUpdateResult + // RawResponse contains the underlying HTTP response. + RawResponse *http.Response +} + +// TransformationsUpdateResult contains the result from method Transformations.Update. +type TransformationsUpdateResult struct { + Transformation + // ETag contains the information returned from the ETag header response. + ETag *string +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_streamingjobs_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_streamingjobs_client.go new file mode 100644 index 000000000000..9866dd196cc0 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_streamingjobs_client.go @@ -0,0 +1,610 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// StreamingJobsClient contains the methods for the StreamingJobs group. +// Don't use this type directly, use NewStreamingJobsClient() instead. +type StreamingJobsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewStreamingJobsClient creates a new instance of StreamingJobsClient with the specified values. +func NewStreamingJobsClient(con *arm.Connection, subscriptionID string) *StreamingJobsClient { + return &StreamingJobsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// BeginCreateOrReplace - Creates a streaming job or replaces an already existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) BeginCreateOrReplace(ctx context.Context, resourceGroupName string, jobName string, streamingJob StreamingJob, options *StreamingJobsBeginCreateOrReplaceOptions) (StreamingJobsCreateOrReplacePollerResponse, error) { + resp, err := client.createOrReplace(ctx, resourceGroupName, jobName, streamingJob, options) + if err != nil { + return StreamingJobsCreateOrReplacePollerResponse{}, err + } + result := StreamingJobsCreateOrReplacePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingJobsClient.CreateOrReplace", "", resp, client.pl, client.createOrReplaceHandleError) + if err != nil { + return StreamingJobsCreateOrReplacePollerResponse{}, err + } + result.Poller = &StreamingJobsCreateOrReplacePoller{ + pt: pt, + } + return result, nil +} + +// CreateOrReplace - Creates a streaming job or replaces an already existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) createOrReplace(ctx context.Context, resourceGroupName string, jobName string, streamingJob StreamingJob, options *StreamingJobsBeginCreateOrReplaceOptions) (*http.Response, error) { + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, jobName, streamingJob, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return nil, client.createOrReplaceHandleError(resp) + } + return resp, nil +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *StreamingJobsClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, jobName string, streamingJob StreamingJob, options *StreamingJobsBeginCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, streamingJob) +} + +// createOrReplaceHandleError handles the CreateOrReplace error response. +func (client *StreamingJobsClient) createOrReplaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginDelete - Deletes a streaming job. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) BeginDelete(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginDeleteOptions) (StreamingJobsDeletePollerResponse, error) { + resp, err := client.deleteOperation(ctx, resourceGroupName, jobName, options) + if err != nil { + return StreamingJobsDeletePollerResponse{}, err + } + result := StreamingJobsDeletePollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingJobsClient.Delete", "", resp, client.pl, client.deleteHandleError) + if err != nil { + return StreamingJobsDeletePollerResponse{}, err + } + result.Poller = &StreamingJobsDeletePoller{ + pt: pt, + } + return result, nil +} + +// Delete - Deletes a streaming job. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) deleteOperation(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginDeleteOptions) (*http.Response, error) { + req, err := client.deleteCreateRequest(ctx, resourceGroupName, jobName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted, http.StatusNoContent) { + return nil, client.deleteHandleError(resp) + } + return resp, nil +} + +// deleteCreateRequest creates the Delete request. +func (client *StreamingJobsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginDeleteOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// deleteHandleError handles the Delete error response. +func (client *StreamingJobsClient) deleteHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details about the specified streaming job. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) Get(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsGetOptions) (StreamingJobsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobName, options) + if err != nil { + return StreamingJobsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingJobsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingJobsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *StreamingJobsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *StreamingJobsClient) getHandleResponse(resp *http.Response) (StreamingJobsGetResponse, error) { + result := StreamingJobsGetResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingJob); err != nil { + return StreamingJobsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *StreamingJobsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// List - Lists all of the streaming jobs in the given subscription. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) List(options *StreamingJobsListOptions) *StreamingJobsListPager { + return &StreamingJobsListPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listCreateRequest(ctx, options) + }, + advancer: func(ctx context.Context, resp StreamingJobsListResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StreamingJobListResult.NextLink) + }, + } +} + +// listCreateRequest creates the List request. +func (client *StreamingJobsClient) listCreateRequest(ctx context.Context, options *StreamingJobsListOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/streamingjobs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listHandleResponse handles the List response. +func (client *StreamingJobsClient) listHandleResponse(resp *http.Response) (StreamingJobsListResponse, error) { + result := StreamingJobsListResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingJobListResult); err != nil { + return StreamingJobsListResponse{}, err + } + return result, nil +} + +// listHandleError handles the List error response. +func (client *StreamingJobsClient) listHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListByResourceGroup - Lists all of the streaming jobs in the specified resource group. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) ListByResourceGroup(resourceGroupName string, options *StreamingJobsListByResourceGroupOptions) *StreamingJobsListByResourceGroupPager { + return &StreamingJobsListByResourceGroupPager{ + client: client, + requester: func(ctx context.Context) (*policy.Request, error) { + return client.listByResourceGroupCreateRequest(ctx, resourceGroupName, options) + }, + advancer: func(ctx context.Context, resp StreamingJobsListByResourceGroupResponse) (*policy.Request, error) { + return runtime.NewRequest(ctx, http.MethodGet, *resp.StreamingJobListResult.NextLink) + }, + } +} + +// listByResourceGroupCreateRequest creates the ListByResourceGroup request. +func (client *StreamingJobsClient) listByResourceGroupCreateRequest(ctx context.Context, resourceGroupName string, options *StreamingJobsListByResourceGroupOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + if options != nil && options.Expand != nil { + reqQP.Set("$expand", *options.Expand) + } + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listByResourceGroupHandleResponse handles the ListByResourceGroup response. +func (client *StreamingJobsClient) listByResourceGroupHandleResponse(resp *http.Response) (StreamingJobsListByResourceGroupResponse, error) { + result := StreamingJobsListByResourceGroupResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingJobListResult); err != nil { + return StreamingJobsListByResourceGroupResponse{}, err + } + return result, nil +} + +// listByResourceGroupHandleError handles the ListByResourceGroup error response. +func (client *StreamingJobsClient) listByResourceGroupHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStart - Starts a streaming job. Once a job is started it will start processing input events and produce output. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) BeginStart(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStartOptions) (StreamingJobsStartPollerResponse, error) { + resp, err := client.start(ctx, resourceGroupName, jobName, options) + if err != nil { + return StreamingJobsStartPollerResponse{}, err + } + result := StreamingJobsStartPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingJobsClient.Start", "", resp, client.pl, client.startHandleError) + if err != nil { + return StreamingJobsStartPollerResponse{}, err + } + result.Poller = &StreamingJobsStartPoller{ + pt: pt, + } + return result, nil +} + +// Start - Starts a streaming job. Once a job is started it will start processing input events and produce output. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) start(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStartOptions) (*http.Response, error) { + req, err := client.startCreateRequest(ctx, resourceGroupName, jobName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.startHandleError(resp) + } + return resp, nil +} + +// startCreateRequest creates the Start request. +func (client *StreamingJobsClient) startCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStartOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/start" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + if options != nil && options.StartJobParameters != nil { + return req, runtime.MarshalAsJSON(req, *options.StartJobParameters) + } + return req, nil +} + +// startHandleError handles the Start error response. +func (client *StreamingJobsClient) startHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginStop - Stops a running streaming job. This will cause a running streaming job to stop processing input events and producing output. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) BeginStop(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStopOptions) (StreamingJobsStopPollerResponse, error) { + resp, err := client.stop(ctx, resourceGroupName, jobName, options) + if err != nil { + return StreamingJobsStopPollerResponse{}, err + } + result := StreamingJobsStopPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("StreamingJobsClient.Stop", "", resp, client.pl, client.stopHandleError) + if err != nil { + return StreamingJobsStopPollerResponse{}, err + } + result.Poller = &StreamingJobsStopPoller{ + pt: pt, + } + return result, nil +} + +// Stop - Stops a running streaming job. This will cause a running streaming job to stop processing input events and producing output. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) stop(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStopOptions) (*http.Response, error) { + req, err := client.stopCreateRequest(ctx, resourceGroupName, jobName, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.stopHandleError(resp) + } + return resp, nil +} + +// stopCreateRequest creates the Stop request. +func (client *StreamingJobsClient) stopCreateRequest(ctx context.Context, resourceGroupName string, jobName string, options *StreamingJobsBeginStopOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/stop" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// stopHandleError handles the Stop error response. +func (client *StreamingJobsClient) stopHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing streaming job. This can be used to partially update (ie. update one or two properties) a streaming job without affecting +// the rest the job definition. +// If the operation fails it returns the *Error error type. +func (client *StreamingJobsClient) Update(ctx context.Context, resourceGroupName string, jobName string, streamingJob StreamingJob, options *StreamingJobsUpdateOptions) (StreamingJobsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, jobName, streamingJob, options) + if err != nil { + return StreamingJobsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return StreamingJobsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return StreamingJobsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *StreamingJobsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, jobName string, streamingJob StreamingJob, options *StreamingJobsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, streamingJob) +} + +// updateHandleResponse handles the Update response. +func (client *StreamingJobsClient) updateHandleResponse(resp *http.Response) (StreamingJobsUpdateResponse, error) { + result := StreamingJobsUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.StreamingJob); err != nil { + return StreamingJobsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *StreamingJobsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_subscriptions_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_subscriptions_client.go new file mode 100644 index 000000000000..d1355732818e --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_subscriptions_client.go @@ -0,0 +1,446 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + armruntime "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm/runtime" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// SubscriptionsClient contains the methods for the Subscriptions group. +// Don't use this type directly, use NewSubscriptionsClient() instead. +type SubscriptionsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewSubscriptionsClient creates a new instance of SubscriptionsClient with the specified values. +func NewSubscriptionsClient(con *arm.Connection, subscriptionID string) *SubscriptionsClient { + return &SubscriptionsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CompileQuery - Compile the Stream Analytics query. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) CompileQuery(ctx context.Context, location string, compileQuery CompileQuery, options *SubscriptionsCompileQueryOptions) (SubscriptionsCompileQueryResponse, error) { + req, err := client.compileQueryCreateRequest(ctx, location, compileQuery, options) + if err != nil { + return SubscriptionsCompileQueryResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SubscriptionsCompileQueryResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SubscriptionsCompileQueryResponse{}, client.compileQueryHandleError(resp) + } + return client.compileQueryHandleResponse(resp) +} + +// compileQueryCreateRequest creates the CompileQuery request. +func (client *SubscriptionsClient) compileQueryCreateRequest(ctx context.Context, location string, compileQuery CompileQuery, options *SubscriptionsCompileQueryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/compileQuery" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, compileQuery) +} + +// compileQueryHandleResponse handles the CompileQuery response. +func (client *SubscriptionsClient) compileQueryHandleResponse(resp *http.Response) (SubscriptionsCompileQueryResponse, error) { + result := SubscriptionsCompileQueryResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.QueryCompilationResult); err != nil { + return SubscriptionsCompileQueryResponse{}, err + } + return result, nil +} + +// compileQueryHandleError handles the CompileQuery error response. +func (client *SubscriptionsClient) compileQueryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// ListQuotas - Retrieves the subscription's current quota information in a particular region. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) ListQuotas(ctx context.Context, location string, options *SubscriptionsListQuotasOptions) (SubscriptionsListQuotasResponse, error) { + req, err := client.listQuotasCreateRequest(ctx, location, options) + if err != nil { + return SubscriptionsListQuotasResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return SubscriptionsListQuotasResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return SubscriptionsListQuotasResponse{}, client.listQuotasHandleError(resp) + } + return client.listQuotasHandleResponse(resp) +} + +// listQuotasCreateRequest creates the ListQuotas request. +func (client *SubscriptionsClient) listQuotasCreateRequest(ctx context.Context, location string, options *SubscriptionsListQuotasOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/quotas" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// listQuotasHandleResponse handles the ListQuotas response. +func (client *SubscriptionsClient) listQuotasHandleResponse(resp *http.Response) (SubscriptionsListQuotasResponse, error) { + result := SubscriptionsListQuotasResponse{RawResponse: resp} + if err := runtime.UnmarshalAsJSON(resp, &result.SubscriptionQuotasListResult); err != nil { + return SubscriptionsListQuotasResponse{}, err + } + return result, nil +} + +// listQuotasHandleError handles the ListQuotas error response. +func (client *SubscriptionsClient) listQuotasHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginSampleInput - Sample the Stream Analytics input data. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) BeginSampleInput(ctx context.Context, location string, sampleInput SampleInput, options *SubscriptionsBeginSampleInputOptions) (SubscriptionsSampleInputPollerResponse, error) { + resp, err := client.sampleInput(ctx, location, sampleInput, options) + if err != nil { + return SubscriptionsSampleInputPollerResponse{}, err + } + result := SubscriptionsSampleInputPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SubscriptionsClient.SampleInput", "location", resp, client.pl, client.sampleInputHandleError) + if err != nil { + return SubscriptionsSampleInputPollerResponse{}, err + } + result.Poller = &SubscriptionsSampleInputPoller{ + pt: pt, + } + return result, nil +} + +// SampleInput - Sample the Stream Analytics input data. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) sampleInput(ctx context.Context, location string, sampleInput SampleInput, options *SubscriptionsBeginSampleInputOptions) (*http.Response, error) { + req, err := client.sampleInputCreateRequest(ctx, location, sampleInput, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusAccepted) { + return nil, client.sampleInputHandleError(resp) + } + return resp, nil +} + +// sampleInputCreateRequest creates the SampleInput request. +func (client *SubscriptionsClient) sampleInputCreateRequest(ctx context.Context, location string, sampleInput SampleInput, options *SubscriptionsBeginSampleInputOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/sampleInput" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, sampleInput) +} + +// sampleInputHandleError handles the SampleInput error response. +func (client *SubscriptionsClient) sampleInputHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTestInput - Test the Stream Analytics input. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) BeginTestInput(ctx context.Context, location string, testInput TestInput, options *SubscriptionsBeginTestInputOptions) (SubscriptionsTestInputPollerResponse, error) { + resp, err := client.testInput(ctx, location, testInput, options) + if err != nil { + return SubscriptionsTestInputPollerResponse{}, err + } + result := SubscriptionsTestInputPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SubscriptionsClient.TestInput", "location", resp, client.pl, client.testInputHandleError) + if err != nil { + return SubscriptionsTestInputPollerResponse{}, err + } + result.Poller = &SubscriptionsTestInputPoller{ + pt: pt, + } + return result, nil +} + +// TestInput - Test the Stream Analytics input. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) testInput(ctx context.Context, location string, testInput TestInput, options *SubscriptionsBeginTestInputOptions) (*http.Response, error) { + req, err := client.testInputCreateRequest(ctx, location, testInput, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusAccepted) { + return nil, client.testInputHandleError(resp) + } + return resp, nil +} + +// testInputCreateRequest creates the TestInput request. +func (client *SubscriptionsClient) testInputCreateRequest(ctx context.Context, location string, testInput TestInput, options *SubscriptionsBeginTestInputOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/testInput" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, testInput) +} + +// testInputHandleError handles the TestInput error response. +func (client *SubscriptionsClient) testInputHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTestOutput - Test the Stream Analytics output. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) BeginTestOutput(ctx context.Context, location string, testOutput TestOutput, options *SubscriptionsBeginTestOutputOptions) (SubscriptionsTestOutputPollerResponse, error) { + resp, err := client.testOutput(ctx, location, testOutput, options) + if err != nil { + return SubscriptionsTestOutputPollerResponse{}, err + } + result := SubscriptionsTestOutputPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SubscriptionsClient.TestOutput", "location", resp, client.pl, client.testOutputHandleError) + if err != nil { + return SubscriptionsTestOutputPollerResponse{}, err + } + result.Poller = &SubscriptionsTestOutputPoller{ + pt: pt, + } + return result, nil +} + +// TestOutput - Test the Stream Analytics output. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) testOutput(ctx context.Context, location string, testOutput TestOutput, options *SubscriptionsBeginTestOutputOptions) (*http.Response, error) { + req, err := client.testOutputCreateRequest(ctx, location, testOutput, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusAccepted) { + return nil, client.testOutputHandleError(resp) + } + return resp, nil +} + +// testOutputCreateRequest creates the TestOutput request. +func (client *SubscriptionsClient) testOutputCreateRequest(ctx context.Context, location string, testOutput TestOutput, options *SubscriptionsBeginTestOutputOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/testOutput" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, testOutput) +} + +// testOutputHandleError handles the TestOutput error response. +func (client *SubscriptionsClient) testOutputHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// BeginTestQuery - Test the Stream Analytics query on a sample input. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) BeginTestQuery(ctx context.Context, location string, testQuery TestQuery, options *SubscriptionsBeginTestQueryOptions) (SubscriptionsTestQueryPollerResponse, error) { + resp, err := client.testQuery(ctx, location, testQuery, options) + if err != nil { + return SubscriptionsTestQueryPollerResponse{}, err + } + result := SubscriptionsTestQueryPollerResponse{ + RawResponse: resp, + } + pt, err := armruntime.NewPoller("SubscriptionsClient.TestQuery", "location", resp, client.pl, client.testQueryHandleError) + if err != nil { + return SubscriptionsTestQueryPollerResponse{}, err + } + result.Poller = &SubscriptionsTestQueryPoller{ + pt: pt, + } + return result, nil +} + +// TestQuery - Test the Stream Analytics query on a sample input. +// If the operation fails it returns the *Error error type. +func (client *SubscriptionsClient) testQuery(ctx context.Context, location string, testQuery TestQuery, options *SubscriptionsBeginTestQueryOptions) (*http.Response, error) { + req, err := client.testQueryCreateRequest(ctx, location, testQuery, options) + if err != nil { + return nil, err + } + resp, err := client.pl.Do(req) + if err != nil { + return nil, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) { + return nil, client.testQueryHandleError(resp) + } + return resp, nil +} + +// testQueryCreateRequest creates the TestQuery request. +func (client *SubscriptionsClient) testQueryCreateRequest(ctx context.Context, location string, testQuery TestQuery, options *SubscriptionsBeginTestQueryOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/providers/Microsoft.StreamAnalytics/locations/{location}/testQuery" + if location == "" { + return nil, errors.New("parameter location cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{location}", url.PathEscape(location)) + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + req, err := runtime.NewRequest(ctx, http.MethodPost, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, testQuery) +} + +// testQueryHandleError handles the TestQuery error response. +func (client *SubscriptionsClient) testQueryHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_time_rfc3339.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_time_rfc3339.go new file mode 100644 index 000000000000..b740116f1050 --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_time_rfc3339.go @@ -0,0 +1,58 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "regexp" + "strings" + "time" +) + +const ( + utcLayoutJSON = `"2006-01-02T15:04:05.999999999"` + utcLayout = "2006-01-02T15:04:05.999999999" + rfc3339JSON = `"` + time.RFC3339Nano + `"` +) + +// Azure reports time in UTC but it doesn't include the 'Z' time zone suffix in some cases. +var tzOffsetRegex = regexp.MustCompile(`(Z|z|\+|-)(\d+:\d+)*"*$`) + +type timeRFC3339 time.Time + +func (t timeRFC3339) MarshalJSON() (json []byte, err error) { + tt := time.Time(t) + return tt.MarshalJSON() +} + +func (t timeRFC3339) MarshalText() (text []byte, err error) { + tt := time.Time(t) + return tt.MarshalText() +} + +func (t *timeRFC3339) UnmarshalJSON(data []byte) error { + layout := utcLayoutJSON + if tzOffsetRegex.Match(data) { + layout = rfc3339JSON + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) UnmarshalText(data []byte) (err error) { + layout := utcLayout + if tzOffsetRegex.Match(data) { + layout = time.RFC3339Nano + } + return t.Parse(layout, string(data)) +} + +func (t *timeRFC3339) Parse(layout, value string) error { + p, err := time.Parse(layout, strings.ToUpper(value)) + *t = timeRFC3339(p) + return err +} diff --git a/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_transformations_client.go b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_transformations_client.go new file mode 100644 index 000000000000..76337fd06b0d --- /dev/null +++ b/sdk/resourcemanager/streamanalytics/armstreamanalytics/zz_generated_transformations_client.go @@ -0,0 +1,262 @@ +//go:build go1.16 +// +build go1.16 + +// 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. +// Changes may cause incorrect behavior and will be lost if the code is regenerated. + +package armstreamanalytics + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/url" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/arm" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/runtime" +) + +// TransformationsClient contains the methods for the Transformations group. +// Don't use this type directly, use NewTransformationsClient() instead. +type TransformationsClient struct { + ep string + pl runtime.Pipeline + subscriptionID string +} + +// NewTransformationsClient creates a new instance of TransformationsClient with the specified values. +func NewTransformationsClient(con *arm.Connection, subscriptionID string) *TransformationsClient { + return &TransformationsClient{ep: con.Endpoint(), pl: con.NewPipeline(module, version), subscriptionID: subscriptionID} +} + +// CreateOrReplace - Creates a transformation or replaces an already existing transformation under an existing streaming job. +// If the operation fails it returns the *Error error type. +func (client *TransformationsClient) CreateOrReplace(ctx context.Context, resourceGroupName string, jobName string, transformationName string, transformation Transformation, options *TransformationsCreateOrReplaceOptions) (TransformationsCreateOrReplaceResponse, error) { + req, err := client.createOrReplaceCreateRequest(ctx, resourceGroupName, jobName, transformationName, transformation, options) + if err != nil { + return TransformationsCreateOrReplaceResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformationsCreateOrReplaceResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK, http.StatusCreated) { + return TransformationsCreateOrReplaceResponse{}, client.createOrReplaceHandleError(resp) + } + return client.createOrReplaceHandleResponse(resp) +} + +// createOrReplaceCreateRequest creates the CreateOrReplace request. +func (client *TransformationsClient) createOrReplaceCreateRequest(ctx context.Context, resourceGroupName string, jobName string, transformationName string, transformation Transformation, options *TransformationsCreateOrReplaceOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if transformationName == "" { + return nil, errors.New("parameter transformationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformationName}", url.PathEscape(transformationName)) + req, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + if options != nil && options.IfNoneMatch != nil { + req.Raw().Header.Set("If-None-Match", *options.IfNoneMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, transformation) +} + +// createOrReplaceHandleResponse handles the CreateOrReplace response. +func (client *TransformationsClient) createOrReplaceHandleResponse(resp *http.Response) (TransformationsCreateOrReplaceResponse, error) { + result := TransformationsCreateOrReplaceResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Transformation); err != nil { + return TransformationsCreateOrReplaceResponse{}, err + } + return result, nil +} + +// createOrReplaceHandleError handles the CreateOrReplace error response. +func (client *TransformationsClient) createOrReplaceHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Get - Gets details about the specified transformation. +// If the operation fails it returns the *Error error type. +func (client *TransformationsClient) Get(ctx context.Context, resourceGroupName string, jobName string, transformationName string, options *TransformationsGetOptions) (TransformationsGetResponse, error) { + req, err := client.getCreateRequest(ctx, resourceGroupName, jobName, transformationName, options) + if err != nil { + return TransformationsGetResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformationsGetResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return TransformationsGetResponse{}, client.getHandleError(resp) + } + return client.getHandleResponse(resp) +} + +// getCreateRequest creates the Get request. +func (client *TransformationsClient) getCreateRequest(ctx context.Context, resourceGroupName string, jobName string, transformationName string, options *TransformationsGetOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if transformationName == "" { + return nil, errors.New("parameter transformationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformationName}", url.PathEscape(transformationName)) + req, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + req.Raw().Header.Set("Accept", "application/json") + return req, nil +} + +// getHandleResponse handles the Get response. +func (client *TransformationsClient) getHandleResponse(resp *http.Response) (TransformationsGetResponse, error) { + result := TransformationsGetResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Transformation); err != nil { + return TransformationsGetResponse{}, err + } + return result, nil +} + +// getHandleError handles the Get error response. +func (client *TransformationsClient) getHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} + +// Update - Updates an existing transformation under an existing streaming job. This can be used to partially update (ie. update one or two properties) +// a transformation without affecting the rest the job or +// transformation definition. +// If the operation fails it returns the *Error error type. +func (client *TransformationsClient) Update(ctx context.Context, resourceGroupName string, jobName string, transformationName string, transformation Transformation, options *TransformationsUpdateOptions) (TransformationsUpdateResponse, error) { + req, err := client.updateCreateRequest(ctx, resourceGroupName, jobName, transformationName, transformation, options) + if err != nil { + return TransformationsUpdateResponse{}, err + } + resp, err := client.pl.Do(req) + if err != nil { + return TransformationsUpdateResponse{}, err + } + if !runtime.HasStatusCode(resp, http.StatusOK) { + return TransformationsUpdateResponse{}, client.updateHandleError(resp) + } + return client.updateHandleResponse(resp) +} + +// updateCreateRequest creates the Update request. +func (client *TransformationsClient) updateCreateRequest(ctx context.Context, resourceGroupName string, jobName string, transformationName string, transformation Transformation, options *TransformationsUpdateOptions) (*policy.Request, error) { + urlPath := "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.StreamAnalytics/streamingjobs/{jobName}/transformations/{transformationName}" + if client.subscriptionID == "" { + return nil, errors.New("parameter client.subscriptionID cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{subscriptionId}", url.PathEscape(client.subscriptionID)) + if resourceGroupName == "" { + return nil, errors.New("parameter resourceGroupName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{resourceGroupName}", url.PathEscape(resourceGroupName)) + if jobName == "" { + return nil, errors.New("parameter jobName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{jobName}", url.PathEscape(jobName)) + if transformationName == "" { + return nil, errors.New("parameter transformationName cannot be empty") + } + urlPath = strings.ReplaceAll(urlPath, "{transformationName}", url.PathEscape(transformationName)) + req, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.ep, urlPath)) + if err != nil { + return nil, err + } + reqQP := req.Raw().URL.Query() + reqQP.Set("api-version", "2017-04-01-preview") + req.Raw().URL.RawQuery = reqQP.Encode() + if options != nil && options.IfMatch != nil { + req.Raw().Header.Set("If-Match", *options.IfMatch) + } + req.Raw().Header.Set("Accept", "application/json") + return req, runtime.MarshalAsJSON(req, transformation) +} + +// updateHandleResponse handles the Update response. +func (client *TransformationsClient) updateHandleResponse(resp *http.Response) (TransformationsUpdateResponse, error) { + result := TransformationsUpdateResponse{RawResponse: resp} + if val := resp.Header.Get("ETag"); val != "" { + result.ETag = &val + } + if err := runtime.UnmarshalAsJSON(resp, &result.Transformation); err != nil { + return TransformationsUpdateResponse{}, err + } + return result, nil +} + +// updateHandleError handles the Update error response. +func (client *TransformationsClient) updateHandleError(resp *http.Response) error { + body, err := runtime.Payload(resp) + if err != nil { + return runtime.NewResponseError(err, resp) + } + errType := Error{raw: string(body)} + if err := runtime.UnmarshalAsJSON(resp, &errType); err != nil { + return runtime.NewResponseError(fmt.Errorf("%s\n%s", string(body), err), resp) + } + return runtime.NewResponseError(&errType, resp) +} diff --git a/swagger_to_sdk_config.json b/swagger_to_sdk_config.json index 428fd938f057..8aedf50a0ecb 100644 --- a/swagger_to_sdk_config.json +++ b/swagger_to_sdk_config.json @@ -16,7 +16,7 @@ }, "initOptions": { "initScript": { - "path": "sh ./initScript.sh", + "path": "sh ./eng/initScript.sh", "stderr": { "scriptWarning": false }