From 9a74095c70e72b895369259edb7bf7d12f41e6d5 Mon Sep 17 00:00:00 2001 From: Azure-Fluent Date: Mon, 26 Oct 2020 12:59:18 +0800 Subject: [PATCH] Release azure-resourcemanager 2.0.0 --- README.md | 8 +- pom.xml | 36 +- .../ManageFunctionAppWithAuthentication.java | 137 +- .../resourcemanager}/samples/Utils.java | 2944 +++++++++-------- 4 files changed, 1670 insertions(+), 1455 deletions(-) rename src/main/java/com/{microsoft/azure/management => azure/resourcemanager}/appservice/samples/ManageFunctionAppWithAuthentication.java (65%) rename src/main/java/com/{microsoft/azure/management => azure/resourcemanager}/samples/Utils.java (50%) diff --git a/README.md b/README.md index 0694301..6b2eecc 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ extensions: To run this sample: -Set the environment variable `AZURE_AUTH_LOCATION` with the full path for an auth file. See [how to create an auth file](https://github.com/Azure/azure-libraries-for-java/blob/master/AUTH.md). +See [DefaultAzureCredential](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity#defaultazurecredential) and prepare the authentication works best for you. For more details on authentication, please refer to [AUTH.md](https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/resourcemanager/docs/AUTH.md). git clone https://github.com/Azure-Samples/app-service-java-manage-authentication-for-functions.git @@ -38,9 +38,11 @@ Set the environment variable `AZURE_AUTH_LOCATION` with the full path for an aut ## More information ## -[http://azure.com/java](http://azure.com/java) +For general documentation as well as quickstarts on how to use Azure Management Libraries for Java, please see [here](https://aka.ms/azsdk/java/mgmt). -If you don't have a Microsoft Azure subscription you can get a FREE trial account [here](http://go.microsoft.com/fwlink/?LinkId=330212) +Start to develop applications with Java on Azure [here](http://azure.com/java). + +If you don't have a Microsoft Azure subscription you can get a FREE trial account [here](http://go.microsoft.com/fwlink/?LinkId=330212). --- diff --git a/pom.xml b/pom.xml index 77e99cb..7e5800c 100644 --- a/pom.xml +++ b/pom.xml @@ -15,15 +15,16 @@ exec-maven-plugin 1.4.0 - com.microsoft.azure.management.appservice.samples.ManageFunctionAppWithAuthentication + com.azure.resourcemanager.appservice.samples.ManageFunctionAppWithAuthentication + false maven-compiler-plugin - 3.0 + 3.8.1 - 1.7 - 1.7 + 1.8 + 1.8 @@ -40,7 +41,7 @@ - com.microsoft.azure.management.appservice.samples.ManageFunctionAppWithAuthentication.java + com.azure.resourcemanager.appservice.samples.ManageFunctionAppWithAuthentication.java @@ -51,29 +52,24 @@ - com.microsoft.azure - azure - 1.36.3 + com.azure.resourcemanager + azure-resourcemanager + 2.0.0 + + + com.azure + azure-identity + 1.1.3 commons-net commons-net - 3.3 + 3.6 org.eclipse.jgit org.eclipse.jgit - 4.5.0.201609210915-r - - - commons-lang - commons-lang - 2.6 - - - org.apache.commons - commons-lang3 - 3.7 + 4.5.7.201904151645-r diff --git a/src/main/java/com/microsoft/azure/management/appservice/samples/ManageFunctionAppWithAuthentication.java b/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithAuthentication.java similarity index 65% rename from src/main/java/com/microsoft/azure/management/appservice/samples/ManageFunctionAppWithAuthentication.java rename to src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithAuthentication.java index 9c05400..27678ca 100644 --- a/src/main/java/com/microsoft/azure/management/appservice/samples/ManageFunctionAppWithAuthentication.java +++ b/src/main/java/com/azure/resourcemanager/appservice/samples/ManageFunctionAppWithAuthentication.java @@ -1,34 +1,30 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - */ - -package com.microsoft.azure.management.appservice.samples; - -import com.microsoft.azure.management.Azure; -import com.microsoft.azure.management.appservice.AppServicePlan; -import com.microsoft.azure.management.appservice.FunctionApp; -import com.microsoft.azure.management.appservice.NameValuePair; -import com.microsoft.azure.management.appservice.PublishingProfile; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; -import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; -import com.microsoft.azure.management.samples.Utils; -import com.microsoft.rest.LogLevel; -import okhttp3.Headers; -import okhttp3.MediaType; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import okhttp3.RequestBody; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.resourcemanager.appservice.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServicePlan; +import com.azure.resourcemanager.appservice.models.FunctionApp; +import com.azure.resourcemanager.appservice.models.NameValuePair; +import com.azure.resourcemanager.appservice.models.PublishingProfile; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; +import com.azure.resourcemanager.samples.Utils; +import com.azure.core.http.policy.HttpLogDetailLevel; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.PushCommand; +import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.concurrent.TimeUnit; +import java.time.Duration; + /** * Azure App Service basic sample for managing function apps. @@ -44,23 +40,21 @@ */ public final class ManageFunctionAppWithAuthentication { - private static OkHttpClient httpClient; - /** * Main function which runs the actual sample. - * @param azure instance of the azure client + * @param azureResourceManager instance of the azure client * @return true if sample runs successfully */ - public static boolean runSample(Azure azure) { + public static boolean runSample(AzureResourceManager azureResourceManager) throws GitAPIException { // New resources final String suffix = ".azurewebsites.net"; - final String app1Name = SdkContext.randomResourceName("webapp1-", 20); - final String app2Name = SdkContext.randomResourceName("webapp2-", 20); - final String app3Name = SdkContext.randomResourceName("webapp3-", 20); + final String app1Name = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String app2Name = Utils.randomResourceName(azureResourceManager, "webapp2-", 20); + final String app3Name = Utils.randomResourceName(azureResourceManager, "webapp3-", 20); final String app1Url = app1Name + suffix; final String app2Url = app2Name + suffix; final String app3Url = app3Name + suffix; - final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); try { @@ -70,7 +64,7 @@ public static boolean runSample(Azure azure) { System.out.println("Creating function app " + app1Name + " in resource group " + rgName + " with admin level auth..."); - FunctionApp app1 = azure.appServices().functionApps().define(app1Name) + FunctionApp app1 = azureResourceManager.functionApps().define(app1Name) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withLocalGitSourceControl() @@ -83,8 +77,8 @@ public static boolean runSample(Azure azure) { // Create a second function app with function level auth System.out.println("Creating another function app " + app2Name + " in resource group " + rgName + " with function level auth..."); - AppServicePlan plan = azure.appServices().appServicePlans().getById(app1.appServicePlanId()); - FunctionApp app2 = azure.appServices().functionApps().define(app2Name) + AppServicePlan plan = azureResourceManager.appServicePlans().getById(app1.appServicePlanId()); + FunctionApp app2 = azureResourceManager.functionApps().define(app2Name) .withExistingAppServicePlan(plan) .withExistingResourceGroup(rgName) .withExistingStorageAccount(app1.storageAccount()) @@ -98,7 +92,7 @@ public static boolean runSample(Azure azure) { // Create a thrid function app with function level auth System.out.println("Creating another function app " + app3Name + " in resource group " + rgName + " with function level auth..."); - FunctionApp app3 = azure.appServices().functionApps().define(app3Name) + FunctionApp app3 = azureResourceManager.functionApps().define(app3Name) .withExistingAppServicePlan(plan) .withExistingResourceGroup(rgName) .withExistingStorageAccount(app1.storageAccount()) @@ -132,10 +126,10 @@ public static boolean runSample(Azure azure) { // warm up System.out.println("Warming up " + app1Url + "/api/square..."); - post("http://" + app1Url + "/api/square", "625"); - SdkContext.sleep(5000); + Utils.sendPostRequest("http://" + app1Url + "/api/square", "625"); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); System.out.println("CURLing " + app1Url + "/api/square..."); - System.out.println("Square of 625 is " + post("http://" + app1Url + "/api/square?code=" + app1.getMasterKey(), "625")); + System.out.println("Square of 625 is " + Utils.sendPostRequest("http://" + app1Url + "/api/square?code=" + app1.getMasterKey(), "625")); //============================================================ // Deploy to app 2 through Git @@ -164,17 +158,17 @@ public static boolean runSample(Azure azure) { // warm up System.out.println("Warming up " + app2Url + "/api/square..."); - post("http://" + app2Url + "/api/square", "725"); - SdkContext.sleep(5000); + Utils.sendPostRequest("http://" + app2Url + "/api/square", "725"); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); System.out.println("CURLing " + app2Url + "/api/square..."); - System.out.println("Square of 725 is " + post("http://" + app2Url + "/api/square?code=" + functionKey, "725")); + System.out.println("Square of 725 is " + Utils.sendPostRequest("http://" + app2Url + "/api/square?code=" + functionKey, "725")); System.out.println("Adding a new key to function app " + app2.name() + "..."); NameValuePair newKey = app2.addFunctionKey("square", "newkey", null); System.out.println("CURLing " + app2Url + "/api/square..."); - System.out.println("Square of 825 is " + post("http://" + app2Url + "/api/square?code=" + newKey.value(), "825")); + System.out.println("Square of 825 is " + Utils.sendPostRequest("http://" + app2Url + "/api/square?code=" + newKey.value(), "825")); //============================================================ // Deploy to app 3 through Git @@ -182,7 +176,7 @@ public static boolean runSample(Azure azure) { System.out.println("Deploying a local function app to " + app3Name + " through web deploy..."); app3.deploy() - .withPackageUri("https://github.com/Azure/azure-libraries-for-java/raw/master/azure-samples/src/main/resources/square-function-app-function-auth.zip") + .withPackageUri("https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/square-function-app-function-auth.zip") .withExistingDeploymentsDeleted(false) .execute(); @@ -195,19 +189,16 @@ public static boolean runSample(Azure azure) { // warm up System.out.println("Warming up " + app3Url + "/api/square..."); - post("http://" + app3Url + "/api/square", "925"); - SdkContext.sleep(5000); + Utils.sendPostRequest("http://" + app3Url + "/api/square", "925"); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); System.out.println("CURLing " + app3Url + "/api/square..."); - System.out.println("Square of 925 is " + post("http://" + app3Url + "/api/square?code=mysecretkey", "925")); + System.out.println("Square of 925 is " + Utils.sendPostRequest("http://" + app3Url + "/api/square?code=mysecretkey", "925")); return true; - } catch (Exception e) { - System.err.println(e.getMessage()); - e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); - azure.resourceGroups().beginDeleteByName(rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); @@ -215,7 +206,6 @@ public static boolean runSample(Azure azure) { g.printStackTrace(); } } - return false; } /** * Main entry point. @@ -227,43 +217,24 @@ public static void main(String[] args) { //============================================================= // Authenticate - final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); - Azure azure = Azure - .configure() - .withLogLevel(LogLevel.BASIC) - .authenticate(credFile) - .withDefaultSubscription(); + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); // Print selected subscription - System.out.println("Selected subscription: " + azure.subscriptionId()); + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); - runSample(azure); + runSample(azureResourceManager); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } - - private static String curl(String url, Map headers) { - Request request = new Request.Builder().url(url).headers(Headers.of(headers)).get().build(); - try { - return httpClient.newCall(request).execute().body().string(); - } catch (IOException e) { - return null; - } - } - - private static String post(String url, String body) { - Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("text/plain"), body)).build(); - try { - return httpClient.newCall(request).execute().body().string(); - } catch (IOException e) { - return null; - } - } - - static { - httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build(); - } } diff --git a/src/main/java/com/microsoft/azure/management/samples/Utils.java b/src/main/java/com/azure/resourcemanager/samples/Utils.java similarity index 50% rename from src/main/java/com/microsoft/azure/management/samples/Utils.java rename to src/main/java/com/azure/resourcemanager/samples/Utils.java index a385709..f4e3e40 100644 --- a/src/main/java/com/microsoft/azure/management/samples/Utils.java +++ b/src/main/java/com/azure/resourcemanager/samples/Utils.java @@ -1,192 +1,156 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - */ - -package com.microsoft.azure.management.samples; - -import com.google.common.base.Joiner; -import com.microsoft.azure.CloudException; -import com.microsoft.azure.PagedList; -import com.microsoft.azure.management.appservice.AppServiceCertificateOrder; -import com.microsoft.azure.management.appservice.AppServiceDomain; -import com.microsoft.azure.management.appservice.AppServicePlan; -import com.microsoft.azure.management.appservice.AppSetting; -import com.microsoft.azure.management.appservice.ConnectionString; -import com.microsoft.azure.management.appservice.Contact; -import com.microsoft.azure.management.appservice.HostNameBinding; -import com.microsoft.azure.management.appservice.HostNameSslState; -import com.microsoft.azure.management.appservice.PublishingProfile; -import com.microsoft.azure.management.appservice.SslState; -import com.microsoft.azure.management.appservice.WebAppBase; -import com.microsoft.azure.management.batch.Application; -import com.microsoft.azure.management.batch.ApplicationPackage; -import com.microsoft.azure.management.batch.BatchAccount; -import com.microsoft.azure.management.batch.BatchAccountKeys; -import com.microsoft.azure.management.batchai.AzureFileShareReference; -import com.microsoft.azure.management.batchai.BatchAICluster; -import com.microsoft.azure.management.batchai.BatchAIJob; -import com.microsoft.azure.management.compute.AvailabilitySet; -import com.microsoft.azure.management.compute.DataDisk; -import com.microsoft.azure.management.compute.ImageDataDisk; -import com.microsoft.azure.management.compute.VirtualMachine; -import com.microsoft.azure.management.compute.VirtualMachineCustomImage; -import com.microsoft.azure.management.compute.VirtualMachineExtension; -import com.microsoft.azure.management.containerinstance.Container; -import com.microsoft.azure.management.containerinstance.ContainerGroup; -import com.microsoft.azure.management.containerinstance.ContainerPort; -import com.microsoft.azure.management.containerinstance.EnvironmentVariable; -import com.microsoft.azure.management.containerinstance.Volume; -import com.microsoft.azure.management.containerinstance.VolumeMount; -import com.microsoft.azure.management.containerregistry.AccessKeyType; -import com.microsoft.azure.management.containerregistry.Registry; -import com.microsoft.azure.management.containerregistry.RegistryCredentials; -import com.microsoft.azure.management.containerservice.ContainerService; -import com.microsoft.azure.management.containerservice.ContainerServiceOrchestratorTypes; -import com.microsoft.azure.management.containerservice.KubernetesCluster; -import com.microsoft.azure.management.cosmosdb.CosmosDBAccount; -import com.microsoft.azure.management.cosmosdb.DatabaseAccountListKeysResult; -import com.microsoft.azure.management.cosmosdb.DatabaseAccountListReadOnlyKeysResult; -import com.microsoft.azure.management.dns.ARecordSet; -import com.microsoft.azure.management.dns.AaaaRecordSet; -import com.microsoft.azure.management.dns.CNameRecordSet; -import com.microsoft.azure.management.dns.DnsZone; -import com.microsoft.azure.management.dns.MXRecordSet; -import com.microsoft.azure.management.dns.MxRecord; -import com.microsoft.azure.management.dns.NSRecordSet; -import com.microsoft.azure.management.dns.PtrRecordSet; -import com.microsoft.azure.management.dns.SoaRecord; -import com.microsoft.azure.management.dns.SoaRecordSet; -import com.microsoft.azure.management.dns.SrvRecord; -import com.microsoft.azure.management.dns.SrvRecordSet; -import com.microsoft.azure.management.dns.TxtRecord; -import com.microsoft.azure.management.dns.TxtRecordSet; -import com.microsoft.azure.management.eventhub.EventHubDisasterRecoveryPairing; -import com.microsoft.azure.management.eventhub.EventHubNamespace; -import com.microsoft.azure.management.eventhub.EventHub; -import com.microsoft.azure.management.eventhub.DisasterRecoveryPairingAuthorizationRule; -import com.microsoft.azure.management.eventhub.DisasterRecoveryPairingAuthorizationKey; -import com.microsoft.azure.management.eventhub.EventHubConsumerGroup; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryApplication; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryGroup; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryObject; -import com.microsoft.azure.management.graphrbac.ActiveDirectoryUser; -import com.microsoft.azure.management.graphrbac.RoleAssignment; -import com.microsoft.azure.management.graphrbac.RoleDefinition; -import com.microsoft.azure.management.graphrbac.ServicePrincipal; -import com.microsoft.azure.management.graphrbac.Permission; -import com.microsoft.azure.management.keyvault.AccessPolicy; -import com.microsoft.azure.management.keyvault.Vault; -import com.microsoft.azure.management.locks.ManagementLock; -import com.microsoft.azure.management.monitor.ActionGroup; -import com.microsoft.azure.management.monitor.ActivityLogAlert; -import com.microsoft.azure.management.monitor.AutomationRunbookReceiver; -import com.microsoft.azure.management.monitor.AzureAppPushReceiver; -import com.microsoft.azure.management.monitor.AzureFunctionReceiver; -import com.microsoft.azure.management.monitor.DiagnosticSetting; -import com.microsoft.azure.management.monitor.EmailReceiver; -import com.microsoft.azure.management.monitor.ItsmReceiver; -import com.microsoft.azure.management.monitor.LogSettings; -import com.microsoft.azure.management.monitor.LogicAppReceiver; -import com.microsoft.azure.management.monitor.MetricAlert; -import com.microsoft.azure.management.monitor.MetricAlertCondition; -import com.microsoft.azure.management.monitor.MetricDimension; -import com.microsoft.azure.management.monitor.MetricSettings; -import com.microsoft.azure.management.monitor.SmsReceiver; -import com.microsoft.azure.management.monitor.VoiceReceiver; -import com.microsoft.azure.management.monitor.WebhookReceiver; -import com.microsoft.azure.management.msi.Identity; -import com.microsoft.azure.management.network.ApplicationGateway; -import com.microsoft.azure.management.network.ApplicationGatewayBackend; -import com.microsoft.azure.management.network.ApplicationGatewayBackendAddress; -import com.microsoft.azure.management.network.ApplicationGatewayBackendHttpConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayFrontend; -import com.microsoft.azure.management.network.ApplicationGatewayIPConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayListener; -import com.microsoft.azure.management.network.ApplicationGatewayProbe; -import com.microsoft.azure.management.network.ApplicationGatewayRedirectConfiguration; -import com.microsoft.azure.management.network.ApplicationGatewayRequestRoutingRule; -import com.microsoft.azure.management.network.ApplicationGatewaySslCertificate; -import com.microsoft.azure.management.network.EffectiveNetworkSecurityRule; -import com.microsoft.azure.management.network.FlowLogSettings; -import com.microsoft.azure.management.network.LoadBalancer; -import com.microsoft.azure.management.network.LoadBalancerBackend; -import com.microsoft.azure.management.network.LoadBalancerFrontend; -import com.microsoft.azure.management.network.LoadBalancerHttpProbe; -import com.microsoft.azure.management.network.LoadBalancerInboundNatPool; -import com.microsoft.azure.management.network.LoadBalancerInboundNatRule; -import com.microsoft.azure.management.network.LoadBalancerPrivateFrontend; -import com.microsoft.azure.management.network.LoadBalancerProbe; -import com.microsoft.azure.management.network.LoadBalancerPublicFrontend; -import com.microsoft.azure.management.network.LoadBalancerTcpProbe; -import com.microsoft.azure.management.network.LoadBalancingRule; -import com.microsoft.azure.management.network.Network; -import com.microsoft.azure.management.network.NetworkInterface; -import com.microsoft.azure.management.network.NetworkPeering; -import com.microsoft.azure.management.network.NetworkSecurityGroup; -import com.microsoft.azure.management.network.NetworkSecurityRule; -import com.microsoft.azure.management.network.NetworkWatcher; -import com.microsoft.azure.management.network.NextHop; -import com.microsoft.azure.management.network.PacketCapture; -import com.microsoft.azure.management.network.PacketCaptureFilter; -import com.microsoft.azure.management.network.PublicIPAddress; -import com.microsoft.azure.management.network.RouteTable; -import com.microsoft.azure.management.network.SecurityGroupNetworkInterface; -import com.microsoft.azure.management.network.SecurityGroupView; -import com.microsoft.azure.management.network.ServiceEndpointType; -import com.microsoft.azure.management.network.Subnet; -import com.microsoft.azure.management.network.Topology; -import com.microsoft.azure.management.network.TopologyAssociation; -import com.microsoft.azure.management.network.TopologyResource; -import com.microsoft.azure.management.network.VerificationIPFlow; -import com.microsoft.azure.management.network.implementation.SecurityRuleInner; -import com.microsoft.azure.management.redis.RedisAccessKeys; -import com.microsoft.azure.management.redis.RedisCache; -import com.microsoft.azure.management.redis.RedisCachePremium; -import com.microsoft.azure.management.redis.ScheduleEntry; -import com.microsoft.azure.management.resources.ResourceGroup; -import com.microsoft.azure.management.resources.fluentcore.arm.Region; -import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; -import com.microsoft.azure.management.search.AdminKeys; -import com.microsoft.azure.management.search.QueryKey; -import com.microsoft.azure.management.search.SearchService; -import com.microsoft.azure.management.servicebus.AccessRights; -import com.microsoft.azure.management.servicebus.AuthorizationKeys; -import com.microsoft.azure.management.servicebus.NamespaceAuthorizationRule; -import com.microsoft.azure.management.servicebus.Queue; -import com.microsoft.azure.management.servicebus.QueueAuthorizationRule; -import com.microsoft.azure.management.servicebus.ServiceBusNamespace; -import com.microsoft.azure.management.servicebus.ServiceBusSubscription; -import com.microsoft.azure.management.servicebus.Topic; -import com.microsoft.azure.management.servicebus.TopicAuthorizationRule; -import com.microsoft.azure.management.sql.ElasticPoolActivity; -import com.microsoft.azure.management.sql.ElasticPoolDatabaseActivity; -import com.microsoft.azure.management.sql.PartnerInfo; -import com.microsoft.azure.management.sql.SqlDatabase; -import com.microsoft.azure.management.sql.SqlDatabaseMetric; -import com.microsoft.azure.management.sql.SqlDatabaseMetricValue; -import com.microsoft.azure.management.sql.SqlDatabaseUsageMetric; -import com.microsoft.azure.management.sql.SqlElasticPool; -import com.microsoft.azure.management.sql.SqlFailoverGroup; -import com.microsoft.azure.management.sql.SqlFirewallRule; -import com.microsoft.azure.management.sql.SqlServer; -import com.microsoft.azure.management.sql.SqlServerKey; -import com.microsoft.azure.management.sql.SqlSubscriptionUsageMetric; -import com.microsoft.azure.management.sql.SqlVirtualNetworkRule; -import com.microsoft.azure.management.storage.StorageAccount; -import com.microsoft.azure.management.storage.StorageAccountEncryptionStatus; -import com.microsoft.azure.management.storage.StorageAccountKey; -import com.microsoft.azure.management.storage.StorageService; -import com.microsoft.azure.management.trafficmanager.TrafficManagerAzureEndpoint; -import com.microsoft.azure.management.trafficmanager.TrafficManagerExternalEndpoint; -import com.microsoft.azure.management.trafficmanager.TrafficManagerNestedProfileEndpoint; -import com.microsoft.azure.management.trafficmanager.TrafficManagerProfile; -import okhttp3.OkHttpClient; -import okhttp3.Request; -import org.apache.commons.lang3.StringUtils; +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.resourcemanager.samples; + +import com.azure.core.annotation.BodyParam; +import com.azure.core.annotation.ExpectedResponses; +import com.azure.core.annotation.Get; +import com.azure.core.annotation.Host; +import com.azure.core.annotation.HostParam; +import com.azure.core.annotation.PathParam; +import com.azure.core.annotation.Post; +import com.azure.core.annotation.ServiceInterface; +import com.azure.core.exception.HttpResponseException; +import com.azure.core.http.HttpPipelineBuilder; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.policy.HttpLogOptions; +import com.azure.core.http.policy.HttpLoggingPolicy; +import com.azure.core.http.policy.RetryPolicy; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.http.rest.RestProxy; +import com.azure.core.http.rest.SimpleResponse; +import com.azure.core.management.Region; +import com.azure.core.management.exception.ManagementException; +import com.azure.core.util.FluxUtil; +import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.serializer.JacksonAdapter; +import com.azure.core.util.serializer.SerializerEncoding; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.appservice.models.AppServicePlan; +import com.azure.resourcemanager.appservice.models.AppSetting; +import com.azure.resourcemanager.appservice.models.ConnectionString; +import com.azure.resourcemanager.appservice.models.Contact; +import com.azure.resourcemanager.appservice.models.HostnameBinding; +import com.azure.resourcemanager.appservice.models.HostnameSslState; +import com.azure.resourcemanager.appservice.models.PublishingProfile; +import com.azure.resourcemanager.appservice.models.SslState; +import com.azure.resourcemanager.appservice.models.WebAppBase; +import com.azure.resourcemanager.appservice.models.WebSiteBase; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryApplication; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryGroup; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryObject; +import com.azure.resourcemanager.authorization.models.ActiveDirectoryUser; +import com.azure.resourcemanager.authorization.models.Permission; +import com.azure.resourcemanager.authorization.models.RoleAssignment; +import com.azure.resourcemanager.authorization.models.RoleDefinition; +import com.azure.resourcemanager.authorization.models.ServicePrincipal; +import com.azure.resourcemanager.compute.models.AvailabilitySet; +import com.azure.resourcemanager.compute.models.DataDisk; +import com.azure.resourcemanager.compute.models.ImageDataDisk; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import com.azure.resourcemanager.compute.models.VirtualMachineCustomImage; +import com.azure.resourcemanager.compute.models.VirtualMachineExtension; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; +import com.azure.resourcemanager.cosmos.models.DatabaseAccountListKeysResult; +import com.azure.resourcemanager.cosmos.models.DatabaseAccountListReadOnlyKeysResult; +import com.azure.resourcemanager.cosmos.models.Location; +import com.azure.resourcemanager.dns.models.ARecordSet; +import com.azure.resourcemanager.dns.models.AaaaRecordSet; +import com.azure.resourcemanager.dns.models.CnameRecordSet; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.dns.models.MxRecord; +import com.azure.resourcemanager.dns.models.MxRecordSet; +import com.azure.resourcemanager.dns.models.NsRecordSet; +import com.azure.resourcemanager.dns.models.PtrRecordSet; +import com.azure.resourcemanager.dns.models.SoaRecord; +import com.azure.resourcemanager.dns.models.SoaRecordSet; +import com.azure.resourcemanager.dns.models.SrvRecord; +import com.azure.resourcemanager.dns.models.SrvRecordSet; +import com.azure.resourcemanager.dns.models.TxtRecord; +import com.azure.resourcemanager.dns.models.TxtRecordSet; +import com.azure.resourcemanager.keyvault.models.AccessPolicy; +import com.azure.resourcemanager.keyvault.models.CertificatePermissions; +import com.azure.resourcemanager.keyvault.models.KeyPermissions; +import com.azure.resourcemanager.keyvault.models.SecretPermissions; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.monitor.models.ActionGroup; +import com.azure.resourcemanager.monitor.models.ActivityLogAlert; +import com.azure.resourcemanager.monitor.models.AutomationRunbookReceiver; +import com.azure.resourcemanager.monitor.models.AzureAppPushReceiver; +import com.azure.resourcemanager.monitor.models.AzureFunctionReceiver; +import com.azure.resourcemanager.monitor.models.DiagnosticSetting; +import com.azure.resourcemanager.monitor.models.EmailReceiver; +import com.azure.resourcemanager.monitor.models.ItsmReceiver; +import com.azure.resourcemanager.monitor.models.LogSettings; +import com.azure.resourcemanager.monitor.models.LogicAppReceiver; +import com.azure.resourcemanager.monitor.models.MetricAlert; +import com.azure.resourcemanager.monitor.models.MetricAlertCondition; +import com.azure.resourcemanager.monitor.models.MetricDimension; +import com.azure.resourcemanager.monitor.models.MetricSettings; +import com.azure.resourcemanager.monitor.models.SmsReceiver; +import com.azure.resourcemanager.monitor.models.VoiceReceiver; +import com.azure.resourcemanager.monitor.models.WebhookReceiver; +import com.azure.resourcemanager.msi.models.Identity; +import com.azure.resourcemanager.network.fluent.models.SecurityRuleInner; +import com.azure.resourcemanager.network.models.ApplicationGateway; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackend; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendAddress; +import com.azure.resourcemanager.network.models.ApplicationGatewayBackendHttpConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayFrontend; +import com.azure.resourcemanager.network.models.ApplicationGatewayIpConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayListener; +import com.azure.resourcemanager.network.models.ApplicationGatewayProbe; +import com.azure.resourcemanager.network.models.ApplicationGatewayRedirectConfiguration; +import com.azure.resourcemanager.network.models.ApplicationGatewayRequestRoutingRule; +import com.azure.resourcemanager.network.models.ApplicationGatewaySslCertificate; +import com.azure.resourcemanager.network.models.EffectiveNetworkSecurityRule; +import com.azure.resourcemanager.network.models.FlowLogSettings; +import com.azure.resourcemanager.network.models.LoadBalancer; +import com.azure.resourcemanager.network.models.LoadBalancerBackend; +import com.azure.resourcemanager.network.models.LoadBalancerFrontend; +import com.azure.resourcemanager.network.models.LoadBalancerHttpProbe; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatPool; +import com.azure.resourcemanager.network.models.LoadBalancerInboundNatRule; +import com.azure.resourcemanager.network.models.LoadBalancerPrivateFrontend; +import com.azure.resourcemanager.network.models.LoadBalancerProbe; +import com.azure.resourcemanager.network.models.LoadBalancerPublicFrontend; +import com.azure.resourcemanager.network.models.LoadBalancerTcpProbe; +import com.azure.resourcemanager.network.models.LoadBalancingRule; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.NetworkInterface; +import com.azure.resourcemanager.network.models.NetworkPeering; +import com.azure.resourcemanager.network.models.NetworkSecurityGroup; +import com.azure.resourcemanager.network.models.NetworkSecurityRule; +import com.azure.resourcemanager.network.models.NetworkWatcher; +import com.azure.resourcemanager.network.models.NextHop; +import com.azure.resourcemanager.network.models.PacketCapture; +import com.azure.resourcemanager.network.models.PacketCaptureFilter; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import com.azure.resourcemanager.network.models.RouteTable; +import com.azure.resourcemanager.network.models.SecurityGroupNetworkInterface; +import com.azure.resourcemanager.network.models.SecurityGroupView; +import com.azure.resourcemanager.network.models.ServiceEndpointType; +import com.azure.resourcemanager.network.models.Subnet; +import com.azure.resourcemanager.network.models.Topology; +import com.azure.resourcemanager.network.models.TopologyAssociation; +import com.azure.resourcemanager.network.models.TopologyResource; +import com.azure.resourcemanager.network.models.VerificationIPFlow; +import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; +import com.azure.resourcemanager.resources.models.ResourceGroup; +import com.azure.resourcemanager.storage.models.StorageAccount; +import com.azure.resourcemanager.storage.models.StorageAccountEncryptionStatus; +import com.azure.resourcemanager.storage.models.StorageAccountKey; +import com.azure.resourcemanager.storage.models.StorageService; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.util.retry.Retry; import java.io.BufferedReader; import java.io.File; @@ -194,19 +158,95 @@ import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.time.Duration; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; -import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.stream.Collectors; /** * Common utils for Azure management samples. */ public final class Utils { + + private Utils() { + } + + /** @return a generated password */ + public static String password() { + String password = new ResourceManagerUtils.InternalRuntimeContext().randomResourceName("Pa5$", 12); + System.out.printf("Password: %s%n", password); + return password; + } + + /** + * Creates a randomized resource name. + * Please provider your own implementation, or avoid using the method, if code is to be used in production. + * + * @param azure the AzureResourceManager instance. + * @param prefix the prefix to the name. + * @param maxLen the max length of the name. + * @return the randomized resource name. + */ + public static String randomResourceName(AzureResourceManager azure, String prefix, int maxLen) { + return azure.resourceGroups().manager().internalContext().randomResourceName(prefix, maxLen); + } + + /** + * Generates the specified number of random resource names with the same prefix. + * Please provider your own implementation, or avoid using the method, if code is to be used in production. + * + * @param azure the AzureResourceManager instance. + * @param prefix the prefix to be used if possible + * @param maxLen the maximum length for the random generated name + * @param count the number of names to generate + * @return the randomized resource names. + */ + public static String[] randomResourceNames(AzureResourceManager azure, String prefix, int maxLen, int count) { + String[] names = new String[count]; + for (int i = 0; i < count; i++) { + names[i] = randomResourceName(azure, prefix, maxLen); + } + return names; + } + + /** + * Creates a random UUID. + * Please provider your own implementation, or avoid using the method, if code is to be used in production. + * + * @param azure the AzureResourceManager instance. + * @return the random UUID. + */ + public static String randomUuid(AzureResourceManager azure) { + return azure.resourceGroups().manager().internalContext().randomUuid(); + } + + /** + * Creates a randomized resource name. + * Please provider your own implementation, or avoid using the method, if code is to be used in production. + * + * @param authenticated the AzureResourceManager.Authenticated instance. + * @param prefix the prefix to the name. + * @param maxLen the max length of the name. + * @return the randomized resource name. + */ + public static String randomResourceName(AzureResourceManager.Authenticated authenticated, String prefix, int maxLen) { + return authenticated.roleAssignments().manager().internalContext().randomResourceName(prefix, maxLen); + } + /** * Print resource group info. * @@ -234,8 +274,7 @@ public static void print(Identity resource) { .append("\n\tTags: ").append(resource.tags()) .append("\n\tService Principal Id: ").append(resource.principalId()) .append("\n\tClient Id: ").append(resource.clientId()) - .append("\n\tTenant Id: ").append(resource.tenantId()) - .append("\n\tClient Secret Url: ").append(resource.clientSecretUrl()); + .append("\n\tTenant Id: ").append(resource.tenantId()); System.out.println(info.toString()); } @@ -396,7 +435,7 @@ public static void print(AvailabilitySet resource) { * Print network info. * * @param resource a network - * @throws CloudException Cloud errors + * @throws ManagementException Cloud errors */ public static void print(Network resource) { StringBuilder info = new StringBuilder(); @@ -476,7 +515,7 @@ public static void print(NetworkInterface resource) { .append("\n\tAccelerated networking enabled? ").append(resource.isAcceleratedNetworkingEnabled()) .append("\n\tMAC Address:").append(resource.macAddress()) .append("\n\tPrivate IP:").append(resource.primaryPrivateIP()) - .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIPAllocationMethod()) + .append("\n\tPrivate allocation method:").append(resource.primaryPrivateIpAllocationMethod()) .append("\n\tPrimary virtual network ID: ").append(resource.primaryIPConfiguration().networkId()) .append("\n\tPrimary subnet name:").append(resource.primaryIPConfiguration().subnetName()); @@ -517,7 +556,7 @@ public static void print(NetworkSecurityGroup resource) { * * @param resource a public IP address */ - public static void print(PublicIPAddress resource) { + public static void print(PublicIpAddress resource) { System.out.println(new StringBuilder().append("Public IP Address: ").append(resource.id()) .append("Name: ").append(resource.name()) .append("\n\tResource group: ").append(resource.resourceGroupName()) @@ -547,9 +586,18 @@ public static void print(Vault vault) { .append("\n\tVault URI: ").append(vault.vaultUri()) .append("\n\tAccess policies: "); for (AccessPolicy accessPolicy : vault.accessPolicies()) { - info.append("\n\t\tIdentity:").append(accessPolicy.objectId()) - .append("\n\t\tKey permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().keys())) - .append("\n\t\tSecret permissions: ").append(Joiner.on(", ").join(accessPolicy.permissions().secrets())); + info.append("\n\t\tIdentity:").append(accessPolicy.objectId()); + if (accessPolicy.permissions() != null) { + if (accessPolicy.permissions().keys() != null) { + info.append("\n\t\tKey permissions: ").append(accessPolicy.permissions().keys().stream().map(KeyPermissions::toString).collect(Collectors.joining(", "))); + } + if (accessPolicy.permissions().secrets() != null) { + info.append("\n\t\tSecret permissions: ").append(accessPolicy.permissions().secrets().stream().map(SecretPermissions::toString).collect(Collectors.joining(", "))); + } + if (accessPolicy.permissions().certificates() != null) { + info.append("\n\t\tCertificate permissions: ").append(accessPolicy.permissions().certificates().stream().map(CertificatePermissions::toString).collect(Collectors.joining(", "))); + } + } } System.out.println(info.toString()); } @@ -594,7 +642,7 @@ public static void print(StorageAccount storageAccount) { info.append("\n\t\t\t").append(ipAddressRange); } } - info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.inner().enableHttpsTrafficOnly()); + info.append("\n\t\tTraffic allowed from only HTTPS: ").append(storageAccount.innerModel().enableHttpsTrafficOnly()); info.append("\n\tEncryption status: "); for (Map.Entry eStatus : storageAccount.encryptionStatuses().entrySet()) { @@ -618,70 +666,71 @@ public static void print(List storageAccountKeys) { } - /** - * Print Redis Cache. - * - * @param redisCache a Redis cache. - */ - public static void print(RedisCache redisCache) { - StringBuilder redisInfo = new StringBuilder() - .append("Redis Cache Name: ").append(redisCache.name()) - .append("\n\tResource group: ").append(redisCache.resourceGroupName()) - .append("\n\tRegion: ").append(redisCache.region()) - .append("\n\tSKU Name: ").append(redisCache.sku().name()) - .append("\n\tSKU Family: ").append(redisCache.sku().family()) - .append("\n\tHost name: ").append(redisCache.hostName()) - .append("\n\tSSL port: ").append(redisCache.sslPort()) - .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); - if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { - redisInfo.append("\n\tRedis Configuration:"); - for (Map.Entry redisConfiguration : redisCache.redisConfiguration().entrySet()) { - redisInfo.append("\n\t '").append(redisConfiguration.getKey()) - .append("' : '").append(redisConfiguration.getValue()).append("'"); - } - } - if (redisCache.isPremium()) { - RedisCachePremium premium = redisCache.asPremium(); - List scheduleEntries = premium.listPatchSchedules(); - if (scheduleEntries != null && !scheduleEntries.isEmpty()) { - redisInfo.append("\n\tRedis Patch Schedule:"); - for (ScheduleEntry schedule : scheduleEntries) { - redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) - .append("', start at: '").append(schedule.startHourUtc()) - .append("', maintenance window: '").append(schedule.maintenanceWindow()) - .append("'"); - } - } - } - - System.out.println(redisInfo.toString()); - } - - /** - * Print Redis Cache access keys. - * - * @param redisAccessKeys a keys for Redis Cache - */ - public static void print(RedisAccessKeys redisAccessKeys) { - StringBuilder redisKeys = new StringBuilder() - .append("Redis Access Keys: ") - .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") - .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); - - System.out.println(redisKeys.toString()); - } - - /** - * Print management lock. - * @param lock a management lock - */ - public static void print(ManagementLock lock) { - StringBuilder info = new StringBuilder(); - info.append("\nLock ID: ").append(lock.id()) - .append("\nLocked resource ID: ").append(lock.lockedResourceId()) - .append("\nLevel: ").append(lock.level()); - System.out.println(info.toString()); - } +// /** +// * Print Redis Cache. +// * +// * @param redisCache a Redis cache. +// */ +// public static void print(RedisCache redisCache) { +// StringBuilder redisInfo = new StringBuilder() +// .append("Redis Cache Name: ").append(redisCache.name()) +// .append("\n\tResource group: ").append(redisCache.resourceGroupName()) +// .append("\n\tRegion: ").append(redisCache.region()) +// .append("\n\tSKU Name: ").append(redisCache.sku().name()) +// .append("\n\tSKU Family: ").append(redisCache.sku().family()) +// .append("\n\tHostname: ").append(redisCache.hostname()) +// .append("\n\tSSL port: ").append(redisCache.sslPort()) +// .append("\n\tNon-SSL port (6379) enabled: ").append(redisCache.nonSslPort()); +// if (redisCache.redisConfiguration() != null && !redisCache.redisConfiguration().isEmpty()) { +// redisInfo.append("\n\tRedis Configuration:"); +// for (Map.Entry redisConfiguration : redisCache.redisConfiguration().entrySet()) { +// redisInfo.append("\n\t '").append(redisConfiguration.getKey()) +// .append("' : '").append(redisConfiguration.getValue()).append("'"); +// } +// } +// if (redisCache.isPremium()) { +// RedisCachePremium premium = redisCache.asPremium(); +// List scheduleEntries = premium.listPatchSchedules(); +// if (scheduleEntries != null && !scheduleEntries.isEmpty()) { +// redisInfo.append("\n\tRedis Patch Schedule:"); +// for (ScheduleEntry schedule : scheduleEntries) { +// redisInfo.append("\n\t\tDay: '").append(schedule.dayOfWeek()) +// .append("', start at: '").append(schedule.startHourUtc()) +// .append("', maintenance window: '").append(schedule.maintenanceWindow()) +// .append("'"); +// } +// } +// } +// +// System.out.println(redisInfo.toString()); +// } + +// /** +// * Print Redis Cache access keys. +// * +// * @param redisAccessKeys a keys for Redis Cache +// */ +// public static void print(RedisAccessKeys redisAccessKeys) { +// StringBuilder redisKeys = new StringBuilder() +// .append("Redis Access Keys: ") +// .append("\n\tPrimary Key: '").append(redisAccessKeys.primaryKey()).append("', ") +// .append("\n\tSecondary Key: '").append(redisAccessKeys.secondaryKey()).append("', "); +// +// System.out.println(redisKeys.toString()); +// } + +// /** +// * Print management lock. +// * +// * @param lock a management lock +// */ +// public static void print(ManagementLock lock) { +// StringBuilder info = new StringBuilder(); +// info.append("\nLock ID: ").append(lock.id()) +// .append("\nLocked resource ID: ").append(lock.lockedResourceId()) +// .append("\nLevel: ").append(lock.level()); +// System.out.println(info.toString()); +// } /** * Print load balancer. @@ -699,8 +748,8 @@ public static void print(LoadBalancer resource) { // Show public IP addresses info.append("\n\tPublic IP address IDs: ") - .append(resource.publicIPAddressIds().size()); - for (String pipId : resource.publicIPAddressIds()) { + .append(resource.publicIpAddressIds().size()); + for (String pipId : resource.publicIpAddressIds()) { info.append("\n\t\tPIP id: ").append(pipId); } @@ -803,12 +852,12 @@ public static void print(LoadBalancer resource) { info.append("\n\t\tFrontend name: ").append(frontend.name()) .append("\n\t\t\tInternet facing: ").append(frontend.isPublic()); if (frontend.isPublic()) { - info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIPAddressId()); + info.append("\n\t\t\tPublic IP Address ID: ").append(((LoadBalancerPublicFrontend) frontend).publicIpAddressId()); } else { info.append("\n\t\t\tVirtual network ID: ").append(((LoadBalancerPrivateFrontend) frontend).networkId()) .append("\n\t\t\tSubnet name: ").append(((LoadBalancerPrivateFrontend) frontend).subnetName()) - .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAddress()) - .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIPAllocationMethod()); + .append("\n\t\t\tPrivate IP address: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAddress()) + .append("\n\t\t\tPrivate IP allocation method: ").append(((LoadBalancerPrivateFrontend) frontend).privateIpAllocationMethod()); } // Inbound NAT pool references @@ -843,7 +892,7 @@ public static void print(LoadBalancer resource) { .append("\n\t\t\tFrontend port: ").append(natRule.frontendPort()) .append("\n\t\t\tBackend port: ").append(natRule.backendPort()) .append("\n\t\t\tBackend NIC ID: ").append(natRule.backendNetworkInterfaceId()) - .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIPConfigurationName()) + .append("\n\t\t\tBackend NIC IP config name: ").append(natRule.backendNicIpConfigurationName()) .append("\n\t\t\tFloating IP? ").append(natRule.floatingIPEnabled()) .append("\n\t\t\tIdle timeout in minutes: ").append(natRule.idleTimeoutInMinutes()); } @@ -891,60 +940,60 @@ public static void print(LoadBalancer resource) { System.out.println(info.toString()); } - - /** - * Prints batch account keys. - * - * @param batchAccountKeys a list of batch account keys - */ - public static void print(BatchAccountKeys batchAccountKeys) { - System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" - + batchAccountKeys.secondary() + ")"); - } - - /** - * Prints batch account. - * - * @param batchAccount a Batch Account - */ - public static void print(BatchAccount batchAccount) { - StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); - - if (batchAccount.applications().size() > 0) { - for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { - Application application = applicationEntry.getValue(); - StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); - - for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { - ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); - StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); - singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); - - applicationPackages.append(singleApplicationPackage); - singleApplicationPackage.append("\n"); - } - - StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); - singleApplication.append("\n\t\tdisplayName: " + application.displayName()); - singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); - singleApplication.append(applicationPackages); - applicationsOutput.append(singleApplication); - applicationsOutput.append("\n"); - } - } - - System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) - .append("Name: ").append(batchAccount.name()) - .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) - .append("\n\tRegion: ").append(batchAccount.region()) - .append("\n\tTags: ").append(batchAccount.tags()) - .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) - .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) - .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) - .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) - .append(applicationsOutput) - .toString()); - } +// +// /** +// * Prints batch account keys. +// * +// * @param batchAccountKeys a list of batch account keys +// */ +// public static void print(BatchAccountKeys batchAccountKeys) { +// System.out.println("Primary Key (" + batchAccountKeys.primary() + ") Secondary key = (" +// + batchAccountKeys.secondary() + ")"); +// } + +// /** +// * Prints batch account. +// * +// * @param batchAccount a Batch Account +// */ +// public static void print(BatchAccount batchAccount) { +// StringBuilder applicationsOutput = new StringBuilder().append("\n\tapplications: "); +// +// if (batchAccount.applications().size() > 0) { +// for (Map.Entry applicationEntry : batchAccount.applications().entrySet()) { +// Application application = applicationEntry.getValue(); +// StringBuilder applicationPackages = new StringBuilder().append("\n\t\t\tapplicationPackages : "); +// +// for (Map.Entry applicationPackageEntry : application.applicationPackages().entrySet()) { +// ApplicationPackage applicationPackage = applicationPackageEntry.getValue(); +// StringBuilder singleApplicationPackage = new StringBuilder().append("\n\t\t\t\tapplicationPackage : " + applicationPackage.name()); +// singleApplicationPackage.append("\n\t\t\t\tapplicationPackageState : " + applicationPackage.state()); +// +// applicationPackages.append(singleApplicationPackage); +// singleApplicationPackage.append("\n"); +// } +// +// StringBuilder singleApplication = new StringBuilder().append("\n\t\tapplication: " + application.name()); +// singleApplication.append("\n\t\tdisplayName: " + application.displayName()); +// singleApplication.append("\n\t\tdefaultVersion: " + application.defaultVersion()); +// singleApplication.append(applicationPackages); +// applicationsOutput.append(singleApplication); +// applicationsOutput.append("\n"); +// } +// } +// +// System.out.println(new StringBuilder().append("BatchAccount: ").append(batchAccount.id()) +// .append("Name: ").append(batchAccount.name()) +// .append("\n\tResource group: ").append(batchAccount.resourceGroupName()) +// .append("\n\tRegion: ").append(batchAccount.region()) +// .append("\n\tTags: ").append(batchAccount.tags()) +// .append("\n\tAccountEndpoint: ").append(batchAccount.accountEndpoint()) +// .append("\n\tPoolQuota: ").append(batchAccount.poolQuota()) +// .append("\n\tActiveJobAndJobScheduleQuota: ").append(batchAccount.activeJobAndJobScheduleQuota()) +// .append("\n\tStorageAccount: ").append(batchAccount.autoStorage() == null ? "No storage account attached" : batchAccount.autoStorage().storageAccountId()) +// .append(applicationsOutput) +// .toString()); +// } /** * Print app service domain. @@ -1016,14 +1065,14 @@ public static void print(WebAppBase resource) { .append("\n\tState: ").append(resource.state()) .append("\n\tResource group: ").append(resource.resourceGroupName()) .append("\n\tRegion: ").append(resource.region()) - .append("\n\tDefault hostname: ").append(resource.defaultHostName()) + .append("\n\tDefault hostname: ").append(resource.defaultHostname()) .append("\n\tApp service plan: ").append(resource.appServicePlanId()) .append("\n\tHost name bindings: "); - for (HostNameBinding binding : resource.getHostNameBindings().values()) { + for (HostnameBinding binding : resource.getHostnameBindings().values()) { builder = builder.append("\n\t\t" + binding.toString()); } builder = builder.append("\n\tSSL bindings: "); - for (HostNameSslState binding : resource.hostNameSslStates().values()) { + for (HostnameSslState binding : resource.hostnameSslStates().values()) { builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { builder = builder.append(" - " + binding.thumbprint()); @@ -1041,80 +1090,103 @@ public static void print(WebAppBase resource) { } /** - * Print a traffic manager profile. + * Print a web site. * - * @param profile a traffic manager profile + * @param resource a web site */ - public static void print(TrafficManagerProfile profile) { - StringBuilder info = new StringBuilder(); - info.append("Traffic Manager Profile: ").append(profile.id()) - .append("\n\tName: ").append(profile.name()) - .append("\n\tResource group: ").append(profile.resourceGroupName()) - .append("\n\tRegion: ").append(profile.regionName()) - .append("\n\tTags: ").append(profile.tags()) - .append("\n\tDNSLabel: ").append(profile.dnsLabel()) - .append("\n\tFQDN: ").append(profile.fqdn()) - .append("\n\tTTL: ").append(profile.timeToLive()) - .append("\n\tEnabled: ").append(profile.isEnabled()) - .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) - .append("\n\tMonitor status: ").append(profile.monitorStatus()) - .append("\n\tMonitoring port: ").append(profile.monitoringPort()) - .append("\n\tMonitoring path: ").append(profile.monitoringPath()); - - Map azureEndpoints = profile.azureEndpoints(); - if (!azureEndpoints.isEmpty()) { - info.append("\n\tAzure endpoints:"); - int idx = 1; - for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { - info.append("\n\t\tAzure endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) - .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); - } - } - - Map externalEndpoints = profile.externalEndpoints(); - if (!externalEndpoints.isEmpty()) { - info.append("\n\tExternal endpoints:"); - int idx = 1; - for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { - info.append("\n\t\tExternal endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) - .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); - } - } - - Map nestedProfileEndpoints = profile.nestedProfileEndpoints(); - if (!nestedProfileEndpoints.isEmpty()) { - info.append("\n\tNested profile endpoints:"); - int idx = 1; - for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { - info.append("\n\t\tNested profile endpoint: #").append(idx++) - .append("\n\t\t\tId: ").append(endpoint.id()) - .append("\n\t\t\tType: ").append(endpoint.endpointType()) - .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) - .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) - .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) - .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) - .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) - .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) - .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); + public static void print(WebSiteBase resource) { + StringBuilder builder = new StringBuilder().append("Web app: ").append(resource.id()) + .append("\n\tName: ").append(resource.name()) + .append("\n\tState: ").append(resource.state()) + .append("\n\tResource group: ").append(resource.resourceGroupName()) + .append("\n\tRegion: ").append(resource.region()) + .append("\n\tDefault hostname: ").append(resource.defaultHostname()) + .append("\n\tApp service plan: ").append(resource.appServicePlanId()); + builder = builder.append("\n\tSSL bindings: "); + for (HostnameSslState binding : resource.hostnameSslStates().values()) { + builder = builder.append("\n\t\t" + binding.name() + ": " + binding.sslState()); + if (binding.sslState() != null && binding.sslState() != SslState.DISABLED) { + builder = builder.append(" - " + binding.thumbprint()); } } - System.out.println(info.toString()); + System.out.println(builder.toString()); } +// /** +// * Print a traffic manager profile. +// * +// * @param profile a traffic manager profile +// */ +// public static void print(TrafficManagerProfile profile) { +// StringBuilder info = new StringBuilder(); +// info.append("Traffic Manager Profile: ").append(profile.id()) +// .append("\n\tName: ").append(profile.name()) +// .append("\n\tResource group: ").append(profile.resourceGroupName()) +// .append("\n\tRegion: ").append(profile.regionName()) +// .append("\n\tTags: ").append(profile.tags()) +// .append("\n\tDNSLabel: ").append(profile.dnsLabel()) +// .append("\n\tFQDN: ").append(profile.fqdn()) +// .append("\n\tTTL: ").append(profile.timeToLive()) +// .append("\n\tEnabled: ").append(profile.isEnabled()) +// .append("\n\tRoutingMethod: ").append(profile.trafficRoutingMethod()) +// .append("\n\tMonitor status: ").append(profile.monitorStatus()) +// .append("\n\tMonitoring port: ").append(profile.monitoringPort()) +// .append("\n\tMonitoring path: ").append(profile.monitoringPath()); +// +// Map azureEndpoints = profile.azureEndpoints(); +// if (!azureEndpoints.isEmpty()) { +// info.append("\n\tAzure endpoints:"); +// int idx = 1; +// for (TrafficManagerAzureEndpoint endpoint : azureEndpoints.values()) { +// info.append("\n\t\tAzure endpoint: #").append(idx++) +// .append("\n\t\t\tId: ").append(endpoint.id()) +// .append("\n\t\t\tType: ").append(endpoint.endpointType()) +// .append("\n\t\t\tTarget resourceId: ").append(endpoint.targetAzureResourceId()) +// .append("\n\t\t\tTarget resourceType: ").append(endpoint.targetResourceType()) +// .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) +// .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) +// .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) +// .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); +// } +// } +// +// Map externalEndpoints = profile.externalEndpoints(); +// if (!externalEndpoints.isEmpty()) { +// info.append("\n\tExternal endpoints:"); +// int idx = 1; +// for (TrafficManagerExternalEndpoint endpoint : externalEndpoints.values()) { +// info.append("\n\t\tExternal endpoint: #").append(idx++) +// .append("\n\t\t\tId: ").append(endpoint.id()) +// .append("\n\t\t\tType: ").append(endpoint.endpointType()) +// .append("\n\t\t\tFQDN: ").append(endpoint.fqdn()) +// .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) +// .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) +// .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) +// .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) +// .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); +// } +// } +// +// Map nestedProfileEndpoints = profile.nestedProfileEndpoints(); +// if (!nestedProfileEndpoints.isEmpty()) { +// info.append("\n\tNested profile endpoints:"); +// int idx = 1; +// for (TrafficManagerNestedProfileEndpoint endpoint : nestedProfileEndpoints.values()) { +// info.append("\n\t\tNested profile endpoint: #").append(idx++) +// .append("\n\t\t\tId: ").append(endpoint.id()) +// .append("\n\t\t\tType: ").append(endpoint.endpointType()) +// .append("\n\t\t\tNested profileId: ").append(endpoint.nestedProfileId()) +// .append("\n\t\t\tMinimum child threshold: ").append(endpoint.minimumChildEndpointCount()) +// .append("\n\t\t\tSource Traffic Location: ").append(endpoint.sourceTrafficLocation()) +// .append("\n\t\t\tMonitor status: ").append(endpoint.monitorStatus()) +// .append("\n\t\t\tEnabled: ").append(endpoint.isEnabled()) +// .append("\n\t\t\tRouting priority: ").append(endpoint.routingPriority()) +// .append("\n\t\t\tRouting weight: ").append(endpoint.routingWeight()); +// } +// } +// System.out.println(info.toString()); +// } + /** * Print a dns zone. * @@ -1142,7 +1214,7 @@ public static void print(DnsZone dnsZone) { .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); - PagedList aRecordSets = dnsZone.aRecordSets().list(); + PagedIterable aRecordSets = dnsZone.aRecordSets().list(); info.append("\n\tA Record sets:"); for (ARecordSet aRecordSet : aRecordSets) { info.append("\n\t\tId: ").append(aRecordSet.id()) @@ -1154,7 +1226,7 @@ public static void print(DnsZone dnsZone) { } } - PagedList aaaaRecordSets = dnsZone.aaaaRecordSets().list(); + PagedIterable aaaaRecordSets = dnsZone.aaaaRecordSets().list(); info.append("\n\tAAAA Record sets:"); for (AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { info.append("\n\t\tId: ").append(aaaaRecordSet.id()) @@ -1166,18 +1238,18 @@ public static void print(DnsZone dnsZone) { } } - PagedList cnameRecordSets = dnsZone.cNameRecordSets().list(); + PagedIterable cnameRecordSets = dnsZone.cNameRecordSets().list(); info.append("\n\tCNAME Record sets:"); - for (CNameRecordSet cnameRecordSet : cnameRecordSets) { + for (CnameRecordSet cnameRecordSet : cnameRecordSets) { info.append("\n\t\tId: ").append(cnameRecordSet.id()) .append("\n\t\tName: ").append(cnameRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); } - PagedList mxRecordSets = dnsZone.mxRecordSets().list(); + PagedIterable mxRecordSets = dnsZone.mxRecordSets().list(); info.append("\n\tMX Record sets:"); - for (MXRecordSet mxRecordSet : mxRecordSets) { + for (MxRecordSet mxRecordSet : mxRecordSets) { info.append("\n\t\tId: ").append(mxRecordSet.id()) .append("\n\t\tName: ").append(mxRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) @@ -1190,9 +1262,9 @@ public static void print(DnsZone dnsZone) { } } - PagedList nsRecordSets = dnsZone.nsRecordSets().list(); + PagedIterable nsRecordSets = dnsZone.nsRecordSets().list(); info.append("\n\tNS Record sets:"); - for (NSRecordSet nsRecordSet : nsRecordSets) { + for (NsRecordSet nsRecordSet : nsRecordSets) { info.append("\n\t\tId: ").append(nsRecordSet.id()) .append("\n\t\tName: ").append(nsRecordSet.name()) .append("\n\t\tTTL (seconds): ").append(nsRecordSet.timeToLive()) @@ -1202,7 +1274,7 @@ public static void print(DnsZone dnsZone) { } } - PagedList ptrRecordSets = dnsZone.ptrRecordSets().list(); + PagedIterable ptrRecordSets = dnsZone.ptrRecordSets().list(); info.append("\n\tPTR Record sets:"); for (PtrRecordSet ptrRecordSet : ptrRecordSets) { info.append("\n\t\tId: ").append(ptrRecordSet.id()) @@ -1214,7 +1286,7 @@ public static void print(DnsZone dnsZone) { } } - PagedList srvRecordSets = dnsZone.srvRecordSets().list(); + PagedIterable srvRecordSets = dnsZone.srvRecordSets().list(); info.append("\n\tSRV Record sets:"); for (SrvRecordSet srvRecordSet : srvRecordSets) { info.append("\n\t\tId: ").append(srvRecordSet.id()) @@ -1233,7 +1305,7 @@ public static void print(DnsZone dnsZone) { } } - PagedList txtRecordSets = dnsZone.txtRecordSets().list(); + PagedIterable txtRecordSets = dnsZone.txtRecordSets().list(); info.append("\n\tTXT Record sets:"); for (TxtRecordSet txtRecordSet : txtRecordSets) { info.append("\n\t\tId: ").append(txtRecordSet.id()) @@ -1249,52 +1321,160 @@ public static void print(DnsZone dnsZone) { System.out.println(info.toString()); } - /** - * Print an Azure Container Registry. - * @param azureRegistry an Azure Container Registry - */ - public static void print(Registry azureRegistry) { - StringBuilder info = new StringBuilder(); - - RegistryCredentials acrCredentials = azureRegistry.getCredentials(); - info.append("Azure Container Registry: ").append(azureRegistry.id()) - .append("\n\tName: ").append(azureRegistry.name()) - .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) - .append("\n\tUser: ").append(acrCredentials.username()) - .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) - .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); - System.out.println(info.toString()); - } - - /** - * Print an Azure Container Service. - * @param containerService an Azure Container Service - */ - public static void print(ContainerService containerService) { - StringBuilder info = new StringBuilder(); - - info.append("Azure Container Service: ").append(containerService.id()) - .append("\n\tName: ").append(containerService.name()) - .append("\n\tWith orchestration: ").append(containerService.orchestratorType().toString()) - .append("\n\tMaster FQDN: ").append(containerService.masterFqdn()) - .append("\n\tMaster node count: ").append(containerService.masterNodeCount()) - .append("\n\tMaster domain label prefix: ").append(containerService.masterDnsPrefix()) - .append("\n\t\tWith Agent pool name: ").append(new ArrayList<>(containerService.agentPools().keySet()).get(0)) - .append("\n\t\tAgent pool count: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).count()) - .append("\n\t\tAgent pool VM size: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).vmSize().toString()) - .append("\n\t\tAgent pool FQDN: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).fqdn()) - .append("\n\t\tAgent pool domain label prefix: ").append(new ArrayList<>(containerService.agentPools().values()).get(0).dnsPrefix()) - .append("\n\tLinux user name: ").append(containerService.linuxRootUsername()) - .append("\n\tSSH key: ").append(containerService.sshKey()); - if (containerService.orchestratorType() == ContainerServiceOrchestratorTypes.KUBERNETES) { - info.append("\n\tName: ").append(containerService.servicePrincipalClientId()); - } - - System.out.println(info.toString()); - } +// /** +// * Print a private dns zone. +// * +// * @param privateDnsZone a private dns zone +// */ +// public static void print(PrivateDnsZone privateDnsZone) { +// StringBuilder info = new StringBuilder(); +// info.append("Private DNS Zone: ").append(privateDnsZone.id()) +// .append("\n\tName (Top level domain): ").append(privateDnsZone.name()) +// .append("\n\tResource group: ").append(privateDnsZone.resourceGroupName()) +// .append("\n\tRegion: ").append(privateDnsZone.regionName()) +// .append("\n\tTags: ").append(privateDnsZone.tags()) +// .append("\n\tName servers:"); +// com.azure.resourcemanager.privatedns.models.SoaRecordSet soaRecordSet = privateDnsZone.getSoaRecordSet(); +// com.azure.resourcemanager.privatedns.models.SoaRecord soaRecord = soaRecordSet.record(); +// info.append("\n\tSOA Record:") +// .append("\n\t\tHost:").append(soaRecord.host()) +// .append("\n\t\tEmail:").append(soaRecord.email()) +// .append("\n\t\tExpire time (seconds):").append(soaRecord.expireTime()) +// .append("\n\t\tRefresh time (seconds):").append(soaRecord.refreshTime()) +// .append("\n\t\tRetry time (seconds):").append(soaRecord.retryTime()) +// .append("\n\t\tNegative response cache ttl (seconds):").append(soaRecord.minimumTtl()) +// .append("\n\t\tTTL (seconds):").append(soaRecordSet.timeToLive()); +// +// PagedIterable aRecordSets = privateDnsZone +// .aRecordSets().list(); +// info.append("\n\tA Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.ARecordSet aRecordSet : aRecordSets) { +// info.append("\n\t\tId: ").append(aRecordSet.id()) +// .append("\n\t\tName: ").append(aRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(aRecordSet.timeToLive()) +// .append("\n\t\tIP v4 addresses: "); +// for (String ipAddress : aRecordSet.ipv4Addresses()) { +// info.append("\n\t\t\t").append(ipAddress); +// } +// } +// +// PagedIterable aaaaRecordSets = privateDnsZone +// .aaaaRecordSets().list(); +// info.append("\n\tAAAA Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.AaaaRecordSet aaaaRecordSet : aaaaRecordSets) { +// info.append("\n\t\tId: ").append(aaaaRecordSet.id()) +// .append("\n\t\tName: ").append(aaaaRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(aaaaRecordSet.timeToLive()) +// .append("\n\t\tIP v6 addresses: "); +// for (String ipAddress : aaaaRecordSet.ipv6Addresses()) { +// info.append("\n\t\t\t").append(ipAddress); +// } +// } +// +// PagedIterable cnameRecordSets = privateDnsZone.cnameRecordSets().list(); +// info.append("\n\tCNAME Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.CnameRecordSet cnameRecordSet : cnameRecordSets) { +// info.append("\n\t\tId: ").append(cnameRecordSet.id()) +// .append("\n\t\tName: ").append(cnameRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(cnameRecordSet.timeToLive()) +// .append("\n\t\tCanonical name: ").append(cnameRecordSet.canonicalName()); +// } +// +// PagedIterable mxRecordSets = privateDnsZone.mxRecordSets().list(); +// info.append("\n\tMX Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.MxRecordSet mxRecordSet : mxRecordSets) { +// info.append("\n\t\tId: ").append(mxRecordSet.id()) +// .append("\n\t\tName: ").append(mxRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(mxRecordSet.timeToLive()) +// .append("\n\t\tRecords: "); +// for (com.azure.resourcemanager.privatedns.models.MxRecord mxRecord : mxRecordSet.records()) { +// info.append("\n\t\t\tExchange server, Preference: ") +// .append(mxRecord.exchange()) +// .append(" ") +// .append(mxRecord.preference()); +// } +// } +// +// PagedIterable ptrRecordSets = privateDnsZone +// .ptrRecordSets().list(); +// info.append("\n\tPTR Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.PtrRecordSet ptrRecordSet : ptrRecordSets) { +// info.append("\n\t\tId: ").append(ptrRecordSet.id()) +// .append("\n\t\tName: ").append(ptrRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(ptrRecordSet.timeToLive()) +// .append("\n\t\tTarget domain names: "); +// for (String domainNames : ptrRecordSet.targetDomainNames()) { +// info.append("\n\t\t\t").append(domainNames); +// } +// } +// +// PagedIterable srvRecordSets = privateDnsZone +// .srvRecordSets().list(); +// info.append("\n\tSRV Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.SrvRecordSet srvRecordSet : srvRecordSets) { +// info.append("\n\t\tId: ").append(srvRecordSet.id()) +// .append("\n\t\tName: ").append(srvRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(srvRecordSet.timeToLive()) +// .append("\n\t\tRecords: "); +// for (com.azure.resourcemanager.privatedns.models.SrvRecord srvRecord : srvRecordSet.records()) { +// info.append("\n\t\t\tTarget, Port, Priority, Weight: ") +// .append(srvRecord.target()) +// .append(", ") +// .append(srvRecord.port()) +// .append(", ") +// .append(srvRecord.priority()) +// .append(", ") +// .append(srvRecord.weight()); +// } +// } +// +// PagedIterable txtRecordSets = privateDnsZone +// .txtRecordSets().list(); +// info.append("\n\tTXT Record sets:"); +// for (com.azure.resourcemanager.privatedns.models.TxtRecordSet txtRecordSet : txtRecordSets) { +// info.append("\n\t\tId: ").append(txtRecordSet.id()) +// .append("\n\t\tName: ").append(txtRecordSet.name()) +// .append("\n\t\tTTL (seconds): ").append(txtRecordSet.timeToLive()) +// .append("\n\t\tRecords: "); +// for (com.azure.resourcemanager.privatedns.models.TxtRecord txtRecord : txtRecordSet.records()) { +// if (txtRecord.value().size() > 0) { +// info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); +// } +// } +// } +// +// PagedIterable virtualNetworkLinks = privateDnsZone.virtualNetworkLinks().list(); +// info.append("\n\tVirtual Network Links:"); +// for (VirtualNetworkLink virtualNetworkLink : virtualNetworkLinks) { +// info.append("\n\tId: ").append(virtualNetworkLink.id()) +// .append("\n\tName: ").append(virtualNetworkLink.name()) +// .append("\n\tReference of Virtual Network: ").append(virtualNetworkLink.referencedVirtualNetworkId()) +// .append("\n\tRegistration enabled: ").append(virtualNetworkLink.isAutoRegistrationEnabled()); +// } +// System.out.println(info.toString()); +// } +// +// /** +// * Print an Azure Container Registry. +// * +// * @param azureRegistry an Azure Container Registry +// */ +// public static void print(Registry azureRegistry) { +// StringBuilder info = new StringBuilder(); +// +// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); +// info.append("Azure Container Registry: ").append(azureRegistry.id()) +// .append("\n\tName: ").append(azureRegistry.name()) +// .append("\n\tServer Url: ").append(azureRegistry.loginServerUrl()) +// .append("\n\tUser: ").append(acrCredentials.username()) +// .append("\n\tFirst Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) +// .append("\n\tSecond Password: ").append(acrCredentials.accessKeys().get(AccessKeyType.SECONDARY)); +// System.out.println(info.toString()); +// } /** * Print an Azure Container Service (AKS). + * * @param kubernetesCluster a managed container service */ public static void print(KubernetesCluster kubernetesCluster) { @@ -1314,74 +1494,92 @@ public static void print(KubernetesCluster kubernetesCluster) { System.out.println(info.toString()); } - /** - * Print an Azure Search Service. - * @param searchService an Azure Search Service - */ - public static void print(SearchService searchService) { - StringBuilder info = new StringBuilder(); - AdminKeys adminKeys = searchService.getAdminKeys(); - List queryKeys = searchService.listQueryKeys(); - - info.append("Azure Search: ").append(searchService.id()) - .append("\n\tResource group: ").append(searchService.resourceGroupName()) - .append("\n\tRegion: ").append(searchService.region()) - .append("\n\tTags: ").append(searchService.tags()) - .append("\n\tSku: ").append(searchService.sku().name()) - .append("\n\tStatus: ").append(searchService.status()) - .append("\n\tProvisioning State: ").append(searchService.provisioningState()) - .append("\n\tHosting Mode: ").append(searchService.hostingMode()) - .append("\n\tReplicas: ").append(searchService.replicaCount()) - .append("\n\tPartitions: ").append(searchService.partitionCount()) - .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) - .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) - .append("\n\tQuery keys:"); - - for (QueryKey queryKey : queryKeys) { - info.append("\n\t\tKey name: ").append(queryKey.name()); - info.append("\n\t\t Value: ").append(queryKey.key()); - } - System.out.println(info.toString()); - } +// /** +// * Print an Azure Search Service. +// * +// * @param searchService an Azure Search Service +// */ +// public static void print(SearchService searchService) { +// StringBuilder info = new StringBuilder(); +// AdminKeys adminKeys = searchService.getAdminKeys(); +// List queryKeys = searchService.listQueryKeys(); +// +// info.append("Azure Search: ").append(searchService.id()) +// .append("\n\tResource group: ").append(searchService.resourceGroupName()) +// .append("\n\tRegion: ").append(searchService.region()) +// .append("\n\tTags: ").append(searchService.tags()) +// .append("\n\tSku: ").append(searchService.sku().name()) +// .append("\n\tStatus: ").append(searchService.status()) +// .append("\n\tProvisioning State: ").append(searchService.provisioningState()) +// .append("\n\tHosting Mode: ").append(searchService.hostingMode()) +// .append("\n\tReplicas: ").append(searchService.replicaCount()) +// .append("\n\tPartitions: ").append(searchService.partitionCount()) +// .append("\n\tPrimary Admin Key: ").append(adminKeys.primaryKey()) +// .append("\n\tSecondary Admin Key: ").append(adminKeys.secondaryKey()) +// .append("\n\tQuery keys:"); +// +// for (QueryKey queryKey : queryKeys) { +// info.append("\n\t\tKey name: ").append(queryKey.name()); +// info.append("\n\t\t Value: ").append(queryKey.key()); +// } +// System.out.println(info.toString()); +// } /** * Retrieve the secondary service principal client ID. + * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal client ID * @throws Exception exception */ - public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws Exception { - Properties authSettings = new Properties(); - FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); - authSettings.load(credentialsFileStream); - credentialsFileStream.close(); + public static String getSecondaryServicePrincipalClientID(String envSecondaryServicePrincipal) throws IOException { + String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); + HashMap auth = new HashMap<>(); - return authSettings.getProperty("client"); + if (content.startsWith("{")) { + auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); + return auth.get("clientId"); + } else { + Properties authSettings = new Properties(); + try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { + authSettings.load(credentialsFileStream); + } + return authSettings.getProperty("client"); + } } /** * Retrieve the secondary service principal secret. + * * @param envSecondaryServicePrincipal an Azure Container Registry * @return a service principal secret * @throws Exception exception */ - public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws Exception { - Properties authSettings = new Properties(); - FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal)); - authSettings.load(credentialsFileStream); - credentialsFileStream.close(); - - return authSettings.getProperty("key"); - } + public static String getSecondaryServicePrincipalSecret(String envSecondaryServicePrincipal) throws IOException { + String content = new String(Files.readAllBytes(new File(envSecondaryServicePrincipal).toPath()), StandardCharsets.UTF_8).trim(); + HashMap auth = new HashMap<>(); - /** - * Creates and returns a randomized name based on the prefix file for use by the sample. - * @param namePrefix The prefix string to be used in generating the name. - * @return a random name - * */ - public static String createRandomName(String namePrefix) { - return SdkContext.randomResourceName(namePrefix, 30); + if (content.startsWith("{")) { + auth = new JacksonAdapter().deserialize(content, auth.getClass(), SerializerEncoding.JSON); + return auth.get("clientSecret"); + } else { + Properties authSettings = new Properties(); + try (FileInputStream credentialsFileStream = new FileInputStream(new File(envSecondaryServicePrincipal))) { + authSettings.load(credentialsFileStream); + } + return authSettings.getProperty("key"); + } } +// +// /** +// * Creates and returns a randomized name based on the prefix file for use by the sample. +// * +// * @param namePrefix The prefix string to be used in generating the name. +// * @return a random name +// */ +// public static String createRandomName(String namePrefix) { +// return ResourceManagerUtils.InternalRuntimeContext.randomResourceName(namePrefix, 30); +// } /** * This method creates a certificate for given password. @@ -1392,10 +1590,10 @@ public static String createRandomName(String namePrefix) { * @param password alias password * @param cnName domain name * @throws Exception exceptions from the creation + * @throws IOException IO Exception */ public static void createCertificate(String certPath, String pfxPath, - String alias, String password, String cnName) throws Exception { - SdkContext.prepareFileLocation(new File(pfxPath), new File(certPath)); + String alias, String password, String cnName) throws IOException { if (new File(pfxPath).exists()) { return; } @@ -1417,17 +1615,17 @@ public static void createCertificate(String certPath, String pfxPath, // Create Pfx file String[] commandArgs = {command, "-genkey", "-alias", alias, - "-keystore", pfxPath, "-storepass", password, "-validity", - validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, - "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; + "-keystore", pfxPath, "-storepass", password, "-validity", + validityInDays, "-keyalg", keyAlg, "-sigalg", sigAlg, "-keysize", keySize, + "-storetype", storeType, "-dname", "CN=" + cnName, "-ext", "EKU=1.3.6.1.5.5.7.3.1"}; Utils.cmdInvocation(commandArgs, true); // Create cer file i.e. extract public key from pfx File pfxFile = new File(pfxPath); if (pfxFile.exists()) { String[] certCommandArgs = {command, "-export", "-alias", alias, - "-storetype", storeType, "-keystore", pfxPath, - "-storepass", password, "-rfc", "-file", certPath}; + "-storetype", storeType, "-keystore", pfxPath, + "-storepass", password, "-rfc", "-file", certPath}; // output of keytool export command is going to error stream // although command is // executed successfully, hence ignoring error stream in this case @@ -1438,311 +1636,307 @@ public static void createCertificate(String certPath, String pfxPath, if (!cerFile.exists()) { throw new IOException( "Error occurred while creating certificate" - + StringUtils.join(" ", certCommandArgs)); + + String.join(" ", certCommandArgs)); } } else { throw new IOException("Error occurred while creating certificates" - + StringUtils.join(" ", commandArgs)); + + String.join(" ", commandArgs)); } } /** * This method is used for invoking native commands. * - * @param command - * :- command to invoke. - * @param ignoreErrorStream - * : Boolean which controls whether to throw exception or not - * based on error stream. + * @param command :- command to invoke. + * @param ignoreErrorStream : Boolean which controls whether to throw exception or not + * based on error stream. * @return result :- depending on the method invocation. * @throws Exception exceptions thrown from the execution */ public static String cmdInvocation(String[] command, - boolean ignoreErrorStream) throws Exception { + boolean ignoreErrorStream) throws IOException { String result = ""; String error = ""; - InputStream inputStream = null; - InputStream errorStream = null; - BufferedReader br = null; - BufferedReader ebr = null; - try { - Process process = new ProcessBuilder(command).start(); - inputStream = process.getInputStream(); - errorStream = process.getErrorStream(); - br = new BufferedReader(new InputStreamReader(inputStream)); + + Process process = new ProcessBuilder(command).start(); + try ( + InputStream inputStream = process.getInputStream(); + InputStream errorStream = process.getErrorStream(); + BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + BufferedReader ebr = new BufferedReader(new InputStreamReader(errorStream, StandardCharsets.UTF_8)); + ) { result = br.readLine(); process.waitFor(); - ebr = new BufferedReader(new InputStreamReader(errorStream)); error = ebr.readLine(); if (error != null && (!error.equals(""))) { // To do - Log error message if (!ignoreErrorStream) { - throw new Exception(error, null); + throw new IOException(error, null); } } } catch (Exception e) { - throw new Exception("Exception occurred while invoking command", e); - } finally { - if (inputStream != null) { - inputStream.close(); - } - if (errorStream != null) { - errorStream.close(); - } - if (br != null) { - br.close(); - } - if (ebr != null) { - ebr.close(); - } + throw new RuntimeException("Exception occurred while invoking command", e); } return result; } - /** - * Prints information for passed SQL Server. - * @param sqlServer sqlServer to be printed - */ - public static void print(SqlServer sqlServer) { - StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) - .append("Name: ").append(sqlServer.name()) - .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) - .append("\n\tRegion: ").append(sqlServer.region()) - .append("\n\tSqlServer version: ").append(sqlServer.version()) - .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed SQL Database. - * @param database database to be printed - */ - public static void print(SqlDatabase database) { - StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) - .append("Name: ").append(database.name()) - .append("\n\tResource group: ").append(database.resourceGroupName()) - .append("\n\tRegion: ").append(database.region()) - .append("\n\tSqlServer Name: ").append(database.sqlServerName()) - .append("\n\tEdition of SQL database: ").append(database.edition()) - .append("\n\tCollation of SQL database: ").append(database.collation()) - .append("\n\tCreation date of SQL database: ").append(database.creationDate()) - .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) - .append("\n\tCurrent service objective of SQL database: ").append(database.serviceLevelObjective()) - .append("\n\tId of current service objective of SQL database: ").append(database.currentServiceObjectiveId()) - .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) - .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed firewall rule. - * @param firewallRule firewall rule to be printed. - */ - public static void print(SqlFirewallRule firewallRule) { - StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) - .append("Name: ").append(firewallRule.name()) - .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) - .append("\n\tRegion: ").append(firewallRule.region()) - .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) - .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIPAddress()) - .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIPAddress()); - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed virtual network rule. - * @param virtualNetworkRule virtual network rule to be printed. - */ - public static void print(SqlVirtualNetworkRule virtualNetworkRule) { - StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) - .append("Name: ").append(virtualNetworkRule.name()) - .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) - .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) - .append("\n\tState: ").append(virtualNetworkRule.state()); - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed SQL subscription usage metric. - * @param subscriptionUsageMetric metric to be printed. - */ - public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { - StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) - .append("Name: ").append(subscriptionUsageMetric.name()) - .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) - .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) - .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) - .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) - .append("\n\tType: ").append(subscriptionUsageMetric.type()); - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed SQL database usage metric. - * @param dbUsageMetric metric to be printed. - */ - public static void print(SqlDatabaseUsageMetric dbUsageMetric) { - StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") - .append("Name: ").append(dbUsageMetric.name()) - .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) - .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) - .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) - .append("\n\tLimit: ").append(dbUsageMetric.limit()) - .append("\n\tUnit: ").append(dbUsageMetric.unit()) - .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed SQL database metric. - * @param dbMetric metric to be printed. - */ - public static void print(SqlDatabaseMetric dbMetric) { - StringBuilder builder = new StringBuilder().append("SQL Database Metric") - .append("Name: ").append(dbMetric.name()) - .append("\n\tStart Time: ").append(dbMetric.startTime()) - .append("\n\tEnd Time: ").append(dbMetric.endTime()) - .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) - .append("\n\tUnit: ").append(dbMetric.unit()); - for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { - builder - .append("\n\tMetric Value: ") - .append("\n\t\tCount: ").append(metricValue.count()) - .append("\n\t\tAverage: ").append(metricValue.average()) - .append("\n\t\tMaximum: ").append(metricValue.maximum()) - .append("\n\t\tMinimum: ").append(metricValue.minimum()) - .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) - .append("\n\t\tTotal: ").append(metricValue.total()); - } - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed Failover Group. - * @param failoverGroup the SQL Failover Group to be printed. - */ - public static void print(SqlFailoverGroup failoverGroup) { - StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) - .append("Name: ").append(failoverGroup.name()) - .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) - .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) - .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) - .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) - .append("\n\tReplication state: ").append(failoverGroup.replicationState()) - .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); - builder.append("\n\tPartner Servers: "); - for (PartnerInfo item : failoverGroup.partnerServers()) { - builder - .append("\n\t\tId: ").append(item.id()) - .append("\n\t\tLocation: ").append(item.location()) - .append("\n\t\tReplication role: ").append(item.replicationRole()); - } - builder.append("\n\tDatabases: "); - for (String databaseId : failoverGroup.databases()) { - builder.append("\n\t\tID: ").append(databaseId); - } - - System.out.println(builder.toString()); - } - - /** - * Prints information for the passed SQL server key. - * @param serverKey virtual network rule to be printed. - */ - public static void print(SqlServerKey serverKey) { - StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) - .append("Name: ").append(serverKey.name()) - .append("\n\tResource group: ").append(serverKey.resourceGroupName()) - .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) - .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") - .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) - .append("\n\tServer Key URI: ").append(serverKey.uri()) - .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) - .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); - - System.out.println(builder.toString()); - } - - /** - * Prints information of the elastic pool passed in. - * @param elasticPool elastic pool to be printed - */ - public static void print(SqlElasticPool elasticPool) { - StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) - .append("Name: ").append(elasticPool.name()) - .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) - .append("\n\tRegion: ").append(elasticPool.region()) - .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) - .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) - .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) - .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) - .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) - .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) - .append("\n\tState of the elastic pool: ").append(elasticPool.state()) - .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageMB()); - - System.out.println(builder.toString()); - } - - /** - * Prints information of the elastic pool activity. - * @param elasticPoolActivity elastic pool activity to be printed - */ - public static void print(ElasticPoolActivity elasticPoolActivity) { - StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) - .append("Name: ").append(elasticPoolActivity.name()) - .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) - .append("\n\tState: ").append(elasticPoolActivity.state()) - .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) - .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) - .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) - .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) - .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) - .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) - .append("\n\tOperation: ").append(elasticPoolActivity.operation()) - .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) - .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) - .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) - .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); - - System.out.println(builder.toString()); - - } - - /** - * Prints information of the database activity. - * @param databaseActivity database activity to be printed - */ - public static void print(ElasticPoolDatabaseActivity databaseActivity) { - StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) - .append("Name: ").append(databaseActivity.name()) - .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) - .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) - .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) - .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) - .append("\n\tState: ").append(databaseActivity.state()) - .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) - .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) - .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) - .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) - .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) - .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); - - System.out.println(builder.toString()); - } +// /** +// * Prints information for passed SQL Server. +// * +// * @param sqlServer sqlServer to be printed +// */ +// public static void print(SqlServer sqlServer) { +// StringBuilder builder = new StringBuilder().append("Sql Server: ").append(sqlServer.id()) +// .append("Name: ").append(sqlServer.name()) +// .append("\n\tResource group: ").append(sqlServer.resourceGroupName()) +// .append("\n\tRegion: ").append(sqlServer.region()) +// .append("\n\tSqlServer version: ").append(sqlServer.version()) +// .append("\n\tFully qualified name for Sql Server: ").append(sqlServer.fullyQualifiedDomainName()); +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed SQL Database. +// * +// * @param database database to be printed +// */ +// public static void print(SqlDatabase database) { +// StringBuilder builder = new StringBuilder().append("Sql Database: ").append(database.id()) +// .append("Name: ").append(database.name()) +// .append("\n\tResource group: ").append(database.resourceGroupName()) +// .append("\n\tRegion: ").append(database.region()) +// .append("\n\tSqlServer Name: ").append(database.sqlServerName()) +// .append("\n\tEdition of SQL database: ").append(database.edition()) +// .append("\n\tCollation of SQL database: ").append(database.collation()) +// .append("\n\tCreation date of SQL database: ").append(database.creationDate()) +// .append("\n\tIs data warehouse: ").append(database.isDataWarehouse()) +// .append("\n\tRequested service objective of SQL database: ").append(database.requestedServiceObjectiveName()) +// .append("\n\tName of current service objective of SQL database: ").append(database.currentServiceObjectiveName()) +// .append("\n\tMax size bytes of SQL database: ").append(database.maxSizeBytes()) +// .append("\n\tDefault secondary location of SQL database: ").append(database.defaultSecondaryLocation()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed firewall rule. +// * +// * @param firewallRule firewall rule to be printed. +// */ +// public static void print(SqlFirewallRule firewallRule) { +// StringBuilder builder = new StringBuilder().append("Sql firewall rule: ").append(firewallRule.id()) +// .append("Name: ").append(firewallRule.name()) +// .append("\n\tResource group: ").append(firewallRule.resourceGroupName()) +// .append("\n\tRegion: ").append(firewallRule.region()) +// .append("\n\tSqlServer Name: ").append(firewallRule.sqlServerName()) +// .append("\n\tStart IP Address of the firewall rule: ").append(firewallRule.startIpAddress()) +// .append("\n\tEnd IP Address of the firewall rule: ").append(firewallRule.endIpAddress()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed virtual network rule. +// * +// * @param virtualNetworkRule virtual network rule to be printed. +// */ +// public static void print(SqlVirtualNetworkRule virtualNetworkRule) { +// StringBuilder builder = new StringBuilder().append("SQL virtual network rule: ").append(virtualNetworkRule.id()) +// .append("Name: ").append(virtualNetworkRule.name()) +// .append("\n\tResource group: ").append(virtualNetworkRule.resourceGroupName()) +// .append("\n\tSqlServer Name: ").append(virtualNetworkRule.sqlServerName()) +// .append("\n\tSubnet ID: ").append(virtualNetworkRule.subnetId()) +// .append("\n\tState: ").append(virtualNetworkRule.state()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed SQL subscription usage metric. +// * +// * @param subscriptionUsageMetric metric to be printed. +// */ +// public static void print(SqlSubscriptionUsageMetric subscriptionUsageMetric) { +// StringBuilder builder = new StringBuilder().append("SQL Subscription Usage Metric: ").append(subscriptionUsageMetric.id()) +// .append("Name: ").append(subscriptionUsageMetric.name()) +// .append("\n\tDisplay Name: ").append(subscriptionUsageMetric.displayName()) +// .append("\n\tCurrent Value: ").append(subscriptionUsageMetric.currentValue()) +// .append("\n\tLimit: ").append(subscriptionUsageMetric.limit()) +// .append("\n\tUnit: ").append(subscriptionUsageMetric.unit()) +// .append("\n\tType: ").append(subscriptionUsageMetric.type()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed SQL database usage metric. +// * +// * @param dbUsageMetric metric to be printed. +// */ +// public static void print(SqlDatabaseUsageMetric dbUsageMetric) { +// StringBuilder builder = new StringBuilder().append("SQL Database Usage Metric") +// .append("Name: ").append(dbUsageMetric.name()) +// .append("\n\tResource Name: ").append(dbUsageMetric.resourceName()) +// .append("\n\tDisplay Name: ").append(dbUsageMetric.displayName()) +// .append("\n\tCurrent Value: ").append(dbUsageMetric.currentValue()) +// .append("\n\tLimit: ").append(dbUsageMetric.limit()) +// .append("\n\tUnit: ").append(dbUsageMetric.unit()) +// .append("\n\tNext Reset Time: ").append(dbUsageMetric.nextResetTime()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed SQL database metric. +// * +// * @param dbMetric metric to be printed. +// */ +// public static void print(SqlDatabaseMetric dbMetric) { +// StringBuilder builder = new StringBuilder().append("SQL Database Metric") +// .append("Name: ").append(dbMetric.name()) +// .append("\n\tStart Time: ").append(dbMetric.startTime()) +// .append("\n\tEnd Time: ").append(dbMetric.endTime()) +// .append("\n\tTime Grain: ").append(dbMetric.timeGrain()) +// .append("\n\tUnit: ").append(dbMetric.unit()); +// for (SqlDatabaseMetricValue metricValue : dbMetric.metricValues()) { +// builder +// .append("\n\tMetric Value: ") +// .append("\n\t\tCount: ").append(metricValue.count()) +// .append("\n\t\tAverage: ").append(metricValue.average()) +// .append("\n\t\tMaximum: ").append(metricValue.maximum()) +// .append("\n\t\tMinimum: ").append(metricValue.minimum()) +// .append("\n\t\tTimestamp: ").append(metricValue.timestamp()) +// .append("\n\t\tTotal: ").append(metricValue.total()); +// } +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed Failover Group. +// * +// * @param failoverGroup the SQL Failover Group to be printed. +// */ +// public static void print(SqlFailoverGroup failoverGroup) { +// StringBuilder builder = new StringBuilder().append("SQL Failover Group: ").append(failoverGroup.id()) +// .append("Name: ").append(failoverGroup.name()) +// .append("\n\tResource group: ").append(failoverGroup.resourceGroupName()) +// .append("\n\tSqlServer Name: ").append(failoverGroup.sqlServerName()) +// .append("\n\tRead-write endpoint policy: ").append(failoverGroup.readWriteEndpointPolicy()) +// .append("\n\tData loss grace period: ").append(failoverGroup.readWriteEndpointDataLossGracePeriodMinutes()) +// .append("\n\tRead-only endpoint policy: ").append(failoverGroup.readOnlyEndpointPolicy()) +// .append("\n\tReplication state: ").append(failoverGroup.replicationState()) +// .append("\n\tReplication role: ").append(failoverGroup.replicationRole()); +// builder.append("\n\tPartner Servers: "); +// for (PartnerInfo item : failoverGroup.partnerServers()) { +// builder +// .append("\n\t\tId: ").append(item.id()) +// .append("\n\t\tLocation: ").append(item.location()) +// .append("\n\t\tReplication role: ").append(item.replicationRole()); +// } +// builder.append("\n\tDatabases: "); +// for (String databaseId : failoverGroup.databases()) { +// builder.append("\n\t\tID: ").append(databaseId); +// } +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information for the passed SQL server key. +// * +// * @param serverKey virtual network rule to be printed. +// */ +// public static void print(SqlServerKey serverKey) { +// StringBuilder builder = new StringBuilder().append("SQL server key: ").append(serverKey.id()) +// .append("Name: ").append(serverKey.name()) +// .append("\n\tResource group: ").append(serverKey.resourceGroupName()) +// .append("\n\tSqlServer Name: ").append(serverKey.sqlServerName()) +// .append("\n\tRegion: ").append(serverKey.region() != null ? serverKey.region().name() : "") +// .append("\n\tServer Key Type: ").append(serverKey.serverKeyType()) +// .append("\n\tServer Key URI: ").append(serverKey.uri()) +// .append("\n\tServer Key Thumbprint: ").append(serverKey.thumbprint()) +// .append("\n\tServer Key Creation Date: ").append(serverKey.creationDate() != null ? serverKey.creationDate().toString() : ""); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information of the elastic pool passed in. +// * +// * @param elasticPool elastic pool to be printed +// */ +// public static void print(SqlElasticPool elasticPool) { +// StringBuilder builder = new StringBuilder().append("Sql elastic pool: ").append(elasticPool.id()) +// .append("Name: ").append(elasticPool.name()) +// .append("\n\tResource group: ").append(elasticPool.resourceGroupName()) +// .append("\n\tRegion: ").append(elasticPool.region()) +// .append("\n\tSqlServer Name: ").append(elasticPool.sqlServerName()) +// .append("\n\tEdition of elastic pool: ").append(elasticPool.edition()) +// .append("\n\tTotal number of DTUs in the elastic pool: ").append(elasticPool.dtu()) +// .append("\n\tMaximum DTUs a database can get in elastic pool: ").append(elasticPool.databaseDtuMax()) +// .append("\n\tMinimum DTUs a database is guaranteed in elastic pool: ").append(elasticPool.databaseDtuMin()) +// .append("\n\tCreation date for the elastic pool: ").append(elasticPool.creationDate()) +// .append("\n\tState of the elastic pool: ").append(elasticPool.state()) +// .append("\n\tStorage capacity in MBs for the elastic pool: ").append(elasticPool.storageCapacity()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Prints information of the elastic pool activity. +// * +// * @param elasticPoolActivity elastic pool activity to be printed +// */ +// public static void print(ElasticPoolActivity elasticPoolActivity) { +// StringBuilder builder = new StringBuilder().append("Sql elastic pool activity: ").append(elasticPoolActivity.id()) +// .append("Name: ").append(elasticPoolActivity.name()) +// .append("\n\tResource group: ").append(elasticPoolActivity.resourceGroupName()) +// .append("\n\tState: ").append(elasticPoolActivity.state()) +// .append("\n\tElastic pool name: ").append(elasticPoolActivity.elasticPoolName()) +// .append("\n\tStart time of activity: ").append(elasticPoolActivity.startTime()) +// .append("\n\tEnd time of activity: ").append(elasticPoolActivity.endTime()) +// .append("\n\tError code of activity: ").append(elasticPoolActivity.errorCode()) +// .append("\n\tError message of activity: ").append(elasticPoolActivity.errorMessage()) +// .append("\n\tError severity of activity: ").append(elasticPoolActivity.errorSeverity()) +// .append("\n\tOperation: ").append(elasticPoolActivity.operation()) +// .append("\n\tCompleted percentage of activity: ").append(elasticPoolActivity.percentComplete()) +// .append("\n\tRequested DTU max limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMax()) +// .append("\n\tRequested DTU min limit in activity: ").append(elasticPoolActivity.requestedDatabaseDtuMin()) +// .append("\n\tRequested DTU limit in activity: ").append(elasticPoolActivity.requestedDtu()); +// +// System.out.println(builder.toString()); +// +// } +// +// /** +// * Prints information of the database activity. +// * +// * @param databaseActivity database activity to be printed +// */ +// public static void print(ElasticPoolDatabaseActivity databaseActivity) { +// StringBuilder builder = new StringBuilder().append("Sql elastic pool database activity: ").append(databaseActivity.id()) +// .append("Name: ").append(databaseActivity.name()) +// .append("\n\tResource group: ").append(databaseActivity.resourceGroupName()) +// .append("\n\tSQL Server Name: ").append(databaseActivity.serverName()) +// .append("\n\tDatabase name name: ").append(databaseActivity.databaseName()) +// .append("\n\tCurrent elastic pool name of the database: ").append(databaseActivity.currentElasticPoolName()) +// .append("\n\tState: ").append(databaseActivity.state()) +// .append("\n\tStart time of activity: ").append(databaseActivity.startTime()) +// .append("\n\tEnd time of activity: ").append(databaseActivity.endTime()) +// .append("\n\tCompleted percentage: ").append(databaseActivity.percentComplete()) +// .append("\n\tError code of activity: ").append(databaseActivity.errorCode()) +// .append("\n\tError message of activity: ").append(databaseActivity.errorMessage()) +// .append("\n\tError severity of activity: ").append(databaseActivity.errorSeverity()); +// +// System.out.println(builder.toString()); +// } /** * Print an application gateway. + * * @param resource an application gateway */ public static void print(ApplicationGateway resource) { @@ -1756,14 +1950,14 @@ public static void print(ApplicationGateway resource) { .append("\n\tOperational state: ").append(resource.operationalState()) .append("\n\tInternet-facing? ").append(resource.isPublic()) .append("\n\tInternal? ").append(resource.isPrivate()) - .append("\n\tDefault private IP address: ").append(resource.privateIPAddress()) - .append("\n\tPrivate IP address allocation method: ").append(resource.privateIPAllocationMethod()) + .append("\n\tDefault private IP address: ").append(resource.privateIpAddress()) + .append("\n\tPrivate IP address allocation method: ").append(resource.privateIpAllocationMethod()) .append("\n\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); // Show IP configs - Map ipConfigs = resource.ipConfigurations(); + Map ipConfigs = resource.ipConfigurations(); info.append("\n\tIP configurations: ").append(ipConfigs.size()); - for (ApplicationGatewayIPConfiguration ipConfig : ipConfigs.values()) { + for (ApplicationGatewayIpConfiguration ipConfig : ipConfigs.values()) { info.append("\n\t\tName: ").append(ipConfig.name()) .append("\n\t\t\tNetwork id: ").append(ipConfig.networkId()) .append("\n\t\t\tSubnet name: ").append(ipConfig.subnetName()); @@ -1778,13 +1972,13 @@ public static void print(ApplicationGateway resource) { if (frontend.isPublic()) { // Show public frontend info - info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIPAddressId()); + info.append("\n\t\t\tPublic IP address ID: ").append(frontend.publicIpAddressId()); } if (frontend.isPrivate()) { // Show private frontend info - info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIPAddress()) - .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIPAllocationMethod()) + info.append("\n\t\t\tPrivate IP address: ").append(frontend.privateIpAddress()) + .append("\n\t\t\tPrivate IP allocation method: ").append(frontend.privateIpAllocationMethod()) .append("\n\t\t\tSubnet name: ").append(frontend.subnetName()) .append("\n\t\t\tVirtual network ID: ").append(frontend.networkId()); } @@ -1853,7 +2047,7 @@ public static void print(ApplicationGateway resource) { info.append("\n\tHTTP listeners: ").append(listeners.size()); for (ApplicationGatewayListener listener : listeners.values()) { info.append("\n\t\tName: ").append(listener.name()) - .append("\n\t\t\tHost name: ").append(listener.hostName()) + .append("\n\t\t\tHost name: ").append(listener.hostname()) .append("\n\t\t\tServer name indication required? ").append(listener.requiresServerNameIndication()) .append("\n\t\t\tAssociated frontend name: ").append(listener.frontend().name()) .append("\n\t\t\tFrontend port name: ").append(listener.frontendPortName()) @@ -1884,8 +2078,8 @@ public static void print(ApplicationGateway resource) { for (ApplicationGatewayRequestRoutingRule rule : rules.values()) { info.append("\n\t\tName: ").append(rule.name()) .append("\n\t\tType: ").append(rule.ruleType()) - .append("\n\t\tPublic IP address ID: ").append(rule.publicIPAddressId()) - .append("\n\t\tHost name: ").append(rule.hostName()) + .append("\n\t\tPublic IP address ID: ").append(rule.publicIpAddressId()) + .append("\n\t\tHost name: ").append(rule.hostname()) .append("\n\t\tServer name indication required? ").append(rule.requiresServerNameIndication()) .append("\n\t\tFrontend port: ").append(rule.frontendPort()) .append("\n\t\tFrontend protocol: ").append(rule.frontendProtocol().toString()) @@ -1992,82 +2186,33 @@ public static void print(VirtualMachineCustomImage image) { } /** - * Uploads a file to an Azure web app. - * @param profile the publishing profile for the web app. + * Uploads a file to an Azure app service for Web App. + * + * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ - public static void uploadFileToWebApp(PublishingProfile profile, String fileName, InputStream file) { - FTPClient ftpClient = new FTPClient(); - String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); - String server = ftpUrlSegments[0]; + public static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file) { String path = "./site/wwwroot/webapps"; - if (fileName.contains("/")) { - int lastslash = fileName.lastIndexOf('/'); - path = path + "/" + fileName.substring(0, lastslash); - fileName = fileName.substring(lastslash + 1); - } - try { - ftpClient.connect(server); - ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); - ftpClient.setFileType(FTP.BINARY_FILE_TYPE); - for (String segment : path.split("/")) { - if (!ftpClient.changeWorkingDirectory(segment)) { - ftpClient.makeDirectory(segment); - ftpClient.changeWorkingDirectory(segment); - } - } - ftpClient.storeFile(fileName, file); - ftpClient.disconnect(); - } catch (IOException e) { - e.printStackTrace(); - } + uploadFileViaFtp(profile, fileName, file, path); } /** - * Uploads a file to an Azure function app. - * @param profile the publishing profile for the web app. + * Uploads a file to an Azure app service for Function App. + * + * @param profile the publishing profile for the app service. * @param fileName the name of the file on server * @param file the local file */ - public static void uploadFileToFunctionApp(PublishingProfile profile, String fileName, InputStream file) { - FTPClient ftpClient = new FTPClient(); - String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); - String server = ftpUrlSegments[0]; - String path = "site/wwwroot"; - if (fileName.contains("/")) { - int lastslash = fileName.lastIndexOf('/'); - path = path + "/" + fileName.substring(0, lastslash); - fileName = fileName.substring(lastslash + 1); - } - try { - ftpClient.connect(server); - ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); - ftpClient.setFileType(FTP.ASCII_FILE_TYPE); - for (String segment : path.split("/")) { - if (!ftpClient.changeWorkingDirectory(segment)) { - ftpClient.makeDirectory(segment); - ftpClient.changeWorkingDirectory(segment); - } - } - ftpClient.storeFile(fileName, file); - ftpClient.disconnect(); - } catch (IOException e) { - e.printStackTrace(); - } + public static void uploadFileForFunctionViaFtp(PublishingProfile profile, String fileName, InputStream file) { + String path = "./site/wwwroot"; + uploadFileViaFtp(profile, fileName, file, path); } - /** - * Uploads a file to an Azure web app. - * @param profile the publishing profile for the web app. - * @param fileName the name of the file on server - * @param file the local file - */ - public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String fileName, InputStream file) { + private static void uploadFileViaFtp(PublishingProfile profile, String fileName, InputStream file, String path) { FTPClient ftpClient = new FTPClient(); String[] ftpUrlSegments = profile.ftpUrl().split("/", 2); String server = ftpUrlSegments[0]; - String path = "./site/wwwroot"; if (fileName.contains("/")) { int lastslash = fileName.lastIndexOf('/'); path = path + "/" + fileName.substring(0, lastslash); @@ -2075,6 +2220,7 @@ public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String f } try { ftpClient.connect(server); + ftpClient.enterLocalPassiveMode(); ftpClient.login(profile.ftpUsername(), profile.ftpPassword()); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); for (String segment : path.split("/")) { @@ -2090,214 +2236,219 @@ public static void uploadFileToWebAppWwwRoot(PublishingProfile profile, String f } } - private Utils() { - - } - - /** - * Print service bus namespace info. - * @param serviceBusNamespace a service bus namespace - */ - public static void print(ServiceBusNamespace serviceBusNamespace) { - StringBuilder builder = new StringBuilder() - .append("Service bus Namespace: ").append(serviceBusNamespace.id()) - .append("\n\tName: ").append(serviceBusNamespace.name()) - .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) - .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) - .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) - .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) - .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) - .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) - .append("\n\tSku: ") - .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) - .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) - .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); - - System.out.println(builder.toString()); - } - - /** - * Print service bus queue info. - * @param queue a service bus queue - */ - public static void print(Queue queue) { - StringBuilder builder = new StringBuilder() - .append("Service bus Queue: ").append(queue.id()) - .append("\n\tName: ").append(queue.name()) - .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) - .append("\n\tCreatedAt: ").append(queue.createdAt()) - .append("\n\tUpdatedAt: ").append(queue.updatedAt()) - .append("\n\tAccessedAt: ").append(queue.accessedAt()) - .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) - .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) - .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) - .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) - .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) - .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) - .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) - .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) - .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) - .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) - .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) - .append("\n\tMessageCount: ").append(queue.messageCount()) - .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) - .append("\n\tStatus: ").append(queue.status()) - .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) - .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) - .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); - - System.out.println(builder.toString()); - - } - - /** - * Print service bus queue authorization keys info. - * @param queueAuthorizationRule a service bus queue authorization keys - */ - public static void print(QueueAuthorizationRule queueAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) - .append("\n\tName: ").append(queueAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) - .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); - - List rights = queueAuthorizationRule.rights(); - builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); - for (AccessRights right: rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); - } - - System.out.println(builder.toString()); - } - - /** - * Print service bus namespace authorization keys info. - * @param keys a service bus namespace authorization keys - */ - public static void print(AuthorizationKeys keys) { - StringBuilder builder = new StringBuilder() - .append("Authorization keys: ") - .append("\n\tPrimaryKey: ").append(keys.primaryKey()) - .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) - .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) - .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); - - System.out.println(builder.toString()); - } - - /** - * Print service bus namespace authorization rule info. - * @param namespaceAuthorizationRule a service bus namespace authorization rule - */ - public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) - .append("\n\tName: ").append(namespaceAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); - - List rights = namespaceAuthorizationRule.rights(); - builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); - for (AccessRights right: rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); - } - - System.out.println(builder.toString()); - } - - /** - * Print service bus topic info. - * @param topic a service bus topic - */ - public static void print(Topic topic) { - StringBuilder builder = new StringBuilder() - .append("Service bus topic: ").append(topic.id()) - .append("\n\tName: ").append(topic.name()) - .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) - .append("\n\tCreatedAt: ").append(topic.createdAt()) - .append("\n\tUpdatedAt: ").append(topic.updatedAt()) - .append("\n\tAccessedAt: ").append(topic.accessedAt()) - .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) - .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) - .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) - .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) - .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) - .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) - .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) - .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) - .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) - .append("\n\tStatus: ").append(topic.status()) - .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) - .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) - .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); - - System.out.println(builder.toString()); - } - - /** - * Print service bus subscription info. - * @param serviceBusSubscription a service bus subscription - */ - public static void print(ServiceBusSubscription serviceBusSubscription) { - StringBuilder builder = new StringBuilder() - .append("Service bus subscription: ").append(serviceBusSubscription.id()) - .append("\n\tName: ").append(serviceBusSubscription.name()) - .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) - .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) - .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) - .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) - .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) - .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) - .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) - .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) - .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) - .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) - .append("\n\tStatus: ").append(serviceBusSubscription.status()) - .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) - .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) - .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) - .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) - .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) - .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) - .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) - .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); - - System.out.println(builder.toString()); - } - - /** - * Print topic Authorization Rule info. - * @param topicAuthorizationRule a topic Authorization Rule - */ - public static void print(TopicAuthorizationRule topicAuthorizationRule) { - StringBuilder builder = new StringBuilder() - .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) - .append("\n\tName: ").append(topicAuthorizationRule.name()) - .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) - .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) - .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); - - List rights = topicAuthorizationRule.rights(); - builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); - for (AccessRights right: rights) { - builder.append("\n\t\tAccessRight: ") - .append("\n\t\t\tName :").append(right.name()); - } - - System.out.println(builder.toString()); - } +// /** +// * Print service bus namespace info. +// * +// * @param serviceBusNamespace a service bus namespace +// */ +// public static void print(ServiceBusNamespace serviceBusNamespace) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus Namespace: ").append(serviceBusNamespace.id()) +// .append("\n\tName: ").append(serviceBusNamespace.name()) +// .append("\n\tRegion: ").append(serviceBusNamespace.regionName()) +// .append("\n\tResourceGroupName: ").append(serviceBusNamespace.resourceGroupName()) +// .append("\n\tCreatedAt: ").append(serviceBusNamespace.createdAt()) +// .append("\n\tUpdatedAt: ").append(serviceBusNamespace.updatedAt()) +// .append("\n\tDnsLabel: ").append(serviceBusNamespace.dnsLabel()) +// .append("\n\tFQDN: ").append(serviceBusNamespace.fqdn()) +// .append("\n\tSku: ") +// .append("\n\t\tCapacity: ").append(serviceBusNamespace.sku().capacity()) +// .append("\n\t\tSkuName: ").append(serviceBusNamespace.sku().name()) +// .append("\n\t\tTier: ").append(serviceBusNamespace.sku().tier()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print service bus queue info. +// * +// * @param queue a service bus queue +// */ +// public static void print(Queue queue) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus Queue: ").append(queue.id()) +// .append("\n\tName: ").append(queue.name()) +// .append("\n\tResourceGroupName: ").append(queue.resourceGroupName()) +// .append("\n\tCreatedAt: ").append(queue.createdAt()) +// .append("\n\tUpdatedAt: ").append(queue.updatedAt()) +// .append("\n\tAccessedAt: ").append(queue.accessedAt()) +// .append("\n\tActiveMessageCount: ").append(queue.activeMessageCount()) +// .append("\n\tCurrentSizeInBytes: ").append(queue.currentSizeInBytes()) +// .append("\n\tDeadLetterMessageCount: ").append(queue.deadLetterMessageCount()) +// .append("\n\tDefaultMessageTtlDuration: ").append(queue.defaultMessageTtlDuration()) +// .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(queue.duplicateMessageDetectionHistoryDuration()) +// .append("\n\tIsBatchedOperationsEnabled: ").append(queue.isBatchedOperationsEnabled()) +// .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(queue.isDeadLetteringEnabledForExpiredMessages()) +// .append("\n\tIsDuplicateDetectionEnabled: ").append(queue.isDuplicateDetectionEnabled()) +// .append("\n\tIsExpressEnabled: ").append(queue.isExpressEnabled()) +// .append("\n\tIsPartitioningEnabled: ").append(queue.isPartitioningEnabled()) +// .append("\n\tIsSessionEnabled: ").append(queue.isSessionEnabled()) +// .append("\n\tDeleteOnIdleDurationInMinutes: ").append(queue.deleteOnIdleDurationInMinutes()) +// .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(queue.maxDeliveryCountBeforeDeadLetteringMessage()) +// .append("\n\tMaxSizeInMB: ").append(queue.maxSizeInMB()) +// .append("\n\tMessageCount: ").append(queue.messageCount()) +// .append("\n\tScheduledMessageCount: ").append(queue.scheduledMessageCount()) +// .append("\n\tStatus: ").append(queue.status()) +// .append("\n\tTransferMessageCount: ").append(queue.transferMessageCount()) +// .append("\n\tLockDurationInSeconds: ").append(queue.lockDurationInSeconds()) +// .append("\n\tTransferDeadLetterMessageCount: ").append(queue.transferDeadLetterMessageCount()); +// +// System.out.println(builder.toString()); +// +// } +// +// /** +// * Print service bus queue authorization keys info. +// * +// * @param queueAuthorizationRule a service bus queue authorization keys +// */ +// public static void print(QueueAuthorizationRule queueAuthorizationRule) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus queue authorization rule: ").append(queueAuthorizationRule.id()) +// .append("\n\tName: ").append(queueAuthorizationRule.name()) +// .append("\n\tResourceGroupName: ").append(queueAuthorizationRule.resourceGroupName()) +// .append("\n\tNamespace Name: ").append(queueAuthorizationRule.namespaceName()) +// .append("\n\tQueue Name: ").append(queueAuthorizationRule.queueName()); +// +// List rights = queueAuthorizationRule.rights(); +// builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); +// for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { +// builder.append("\n\t\tAccessRight: ") +// .append("\n\t\t\tName :").append(right.name()); +// } +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print service bus namespace authorization keys info. +// * +// * @param keys a service bus namespace authorization keys +// */ +// public static void print(AuthorizationKeys keys) { +// StringBuilder builder = new StringBuilder() +// .append("Authorization keys: ") +// .append("\n\tPrimaryKey: ").append(keys.primaryKey()) +// .append("\n\tPrimaryConnectionString: ").append(keys.primaryConnectionString()) +// .append("\n\tSecondaryKey: ").append(keys.secondaryKey()) +// .append("\n\tSecondaryConnectionString: ").append(keys.secondaryConnectionString()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print service bus namespace authorization rule info. +// * +// * @param namespaceAuthorizationRule a service bus namespace authorization rule +// */ +// public static void print(NamespaceAuthorizationRule namespaceAuthorizationRule) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus queue authorization rule: ").append(namespaceAuthorizationRule.id()) +// .append("\n\tName: ").append(namespaceAuthorizationRule.name()) +// .append("\n\tResourceGroupName: ").append(namespaceAuthorizationRule.resourceGroupName()) +// .append("\n\tNamespace Name: ").append(namespaceAuthorizationRule.namespaceName()); +// +// List rights = namespaceAuthorizationRule.rights(); +// builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); +// for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { +// builder.append("\n\t\tAccessRight: ") +// .append("\n\t\t\tName :").append(right.name()); +// } +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print service bus topic info. +// * +// * @param topic a service bus topic +// */ +// public static void print(Topic topic) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus topic: ").append(topic.id()) +// .append("\n\tName: ").append(topic.name()) +// .append("\n\tResourceGroupName: ").append(topic.resourceGroupName()) +// .append("\n\tCreatedAt: ").append(topic.createdAt()) +// .append("\n\tUpdatedAt: ").append(topic.updatedAt()) +// .append("\n\tAccessedAt: ").append(topic.accessedAt()) +// .append("\n\tActiveMessageCount: ").append(topic.activeMessageCount()) +// .append("\n\tCurrentSizeInBytes: ").append(topic.currentSizeInBytes()) +// .append("\n\tDeadLetterMessageCount: ").append(topic.deadLetterMessageCount()) +// .append("\n\tDefaultMessageTtlDuration: ").append(topic.defaultMessageTtlDuration()) +// .append("\n\tDuplicateMessageDetectionHistoryDuration: ").append(topic.duplicateMessageDetectionHistoryDuration()) +// .append("\n\tIsBatchedOperationsEnabled: ").append(topic.isBatchedOperationsEnabled()) +// .append("\n\tIsDuplicateDetectionEnabled: ").append(topic.isDuplicateDetectionEnabled()) +// .append("\n\tIsExpressEnabled: ").append(topic.isExpressEnabled()) +// .append("\n\tIsPartitioningEnabled: ").append(topic.isPartitioningEnabled()) +// .append("\n\tDeleteOnIdleDurationInMinutes: ").append(topic.deleteOnIdleDurationInMinutes()) +// .append("\n\tMaxSizeInMB: ").append(topic.maxSizeInMB()) +// .append("\n\tScheduledMessageCount: ").append(topic.scheduledMessageCount()) +// .append("\n\tStatus: ").append(topic.status()) +// .append("\n\tTransferMessageCount: ").append(topic.transferMessageCount()) +// .append("\n\tSubscriptionCount: ").append(topic.subscriptionCount()) +// .append("\n\tTransferDeadLetterMessageCount: ").append(topic.transferDeadLetterMessageCount()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print service bus subscription info. +// * +// * @param serviceBusSubscription a service bus subscription +// */ +// public static void print(ServiceBusSubscription serviceBusSubscription) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus subscription: ").append(serviceBusSubscription.id()) +// .append("\n\tName: ").append(serviceBusSubscription.name()) +// .append("\n\tResourceGroupName: ").append(serviceBusSubscription.resourceGroupName()) +// .append("\n\tCreatedAt: ").append(serviceBusSubscription.createdAt()) +// .append("\n\tUpdatedAt: ").append(serviceBusSubscription.updatedAt()) +// .append("\n\tAccessedAt: ").append(serviceBusSubscription.accessedAt()) +// .append("\n\tActiveMessageCount: ").append(serviceBusSubscription.activeMessageCount()) +// .append("\n\tDeadLetterMessageCount: ").append(serviceBusSubscription.deadLetterMessageCount()) +// .append("\n\tDefaultMessageTtlDuration: ").append(serviceBusSubscription.defaultMessageTtlDuration()) +// .append("\n\tIsBatchedOperationsEnabled: ").append(serviceBusSubscription.isBatchedOperationsEnabled()) +// .append("\n\tDeleteOnIdleDurationInMinutes: ").append(serviceBusSubscription.deleteOnIdleDurationInMinutes()) +// .append("\n\tScheduledMessageCount: ").append(serviceBusSubscription.scheduledMessageCount()) +// .append("\n\tStatus: ").append(serviceBusSubscription.status()) +// .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) +// .append("\n\tIsDeadLetteringEnabledForExpiredMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForExpiredMessages()) +// .append("\n\tIsSessionEnabled: ").append(serviceBusSubscription.isSessionEnabled()) +// .append("\n\tLockDurationInSeconds: ").append(serviceBusSubscription.lockDurationInSeconds()) +// .append("\n\tMaxDeliveryCountBeforeDeadLetteringMessage: ").append(serviceBusSubscription.maxDeliveryCountBeforeDeadLetteringMessage()) +// .append("\n\tIsDeadLetteringEnabledForFilterEvaluationFailedMessages: ").append(serviceBusSubscription.isDeadLetteringEnabledForFilterEvaluationFailedMessages()) +// .append("\n\tTransferMessageCount: ").append(serviceBusSubscription.transferMessageCount()) +// .append("\n\tTransferDeadLetterMessageCount: ").append(serviceBusSubscription.transferDeadLetterMessageCount()); +// +// System.out.println(builder.toString()); +// } +// +// /** +// * Print topic Authorization Rule info. +// * +// * @param topicAuthorizationRule a topic Authorization Rule +// */ +// public static void print(TopicAuthorizationRule topicAuthorizationRule) { +// StringBuilder builder = new StringBuilder() +// .append("Service bus topic authorization rule: ").append(topicAuthorizationRule.id()) +// .append("\n\tName: ").append(topicAuthorizationRule.name()) +// .append("\n\tResourceGroupName: ").append(topicAuthorizationRule.resourceGroupName()) +// .append("\n\tNamespace Name: ").append(topicAuthorizationRule.namespaceName()) +// .append("\n\tTopic Name: ").append(topicAuthorizationRule.topicName()); +// +// List rights = topicAuthorizationRule.rights(); +// builder.append("\n\tNumber of access rights in queue: ").append(rights.size()); +// for (com.azure.resourcemanager.servicebus.models.AccessRights right : rights) { +// builder.append("\n\t\tAccessRight: ") +// .append("\n\t\t\tName :").append(right.name()); +// } +// +// System.out.println(builder.toString()); +// } /** * Print CosmosDB info. + * * @param cosmosDBAccount a CosmosDB */ public static void print(CosmosDBAccount cosmosDBAccount) { @@ -2312,18 +2463,18 @@ public static void print(CosmosDBAccount cosmosDBAccount) { DatabaseAccountListKeysResult keys = cosmosDBAccount.listKeys(); DatabaseAccountListReadOnlyKeysResult readOnlyKeys = cosmosDBAccount.listReadOnlyKeys(); builder - .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) - .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) - .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) - .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); + .append("\n\tPrimary Master Key: ").append(keys.primaryMasterKey()) + .append("\n\tSecondary Master Key: ").append(keys.secondaryMasterKey()) + .append("\n\tPrimary Read-Only Key: ").append(readOnlyKeys.primaryReadonlyMasterKey()) + .append("\n\tSecondary Read-Only Key: ").append(readOnlyKeys.secondaryReadonlyMasterKey()); - for (com.microsoft.azure.management.cosmosdb.Location writeReplica : cosmosDBAccount.writableReplications()) { + for (Location writeReplica : cosmosDBAccount.writableReplications()) { builder.append("\n\t\tWrite replication: ") .append("\n\t\t\tName :").append(writeReplica.locationName()); } builder.append("\n\tNumber of read replications: ").append(cosmosDBAccount.readableReplications().size()); - for (com.microsoft.azure.management.cosmosdb.Location readReplica : cosmosDBAccount.readableReplications()) { + for (Location readReplica : cosmosDBAccount.readableReplications()) { builder.append("\n\t\tRead replication: ") .append("\n\t\t\tName :").append(readReplica.locationName()); } @@ -2332,6 +2483,7 @@ public static void print(CosmosDBAccount cosmosDBAccount) { /** * Print Active Directory User info. + * * @param user active directory user */ public static void print(ActiveDirectoryUser user) { @@ -2348,6 +2500,7 @@ public static void print(ActiveDirectoryUser user) { /** * Print Active Directory User info. + * * @param role role definition */ public static void print(RoleDefinition role) { @@ -2384,6 +2537,7 @@ public static void print(RoleDefinition role) { /** * Print Role Assignment info. + * * @param roleAssignment role assignment */ public static void print(RoleAssignment roleAssignment) { @@ -2398,6 +2552,7 @@ public static void print(RoleAssignment roleAssignment) { /** * Print Active Directory Group info. + * * @param group active directory group */ public static void print(ActiveDirectoryGroup group) { @@ -2418,6 +2573,7 @@ public static void print(ActiveDirectoryGroup group) { /** * Print Active Directory Application info. + * * @param application active directory application */ public static void print(ActiveDirectoryApplication application) { @@ -2485,8 +2641,8 @@ public static void print(PacketCapture resource) { .append("\n\t Packet capture filters: ").append(resource.filters().size()); for (PacketCaptureFilter filter : resource.filters()) { sb.append("\n\t\tProtocol: ").append(filter.protocol()); - sb.append("\n\t\tLocal IP address: ").append(filter.localIPAddress()); - sb.append("\n\t\tRemote IP address: ").append(filter.remoteIPAddress()); + sb.append("\n\t\tLocal IP address: ").append(filter.localIpAddress()); + sb.append("\n\t\tRemote IP address: ").append(filter.remoteIpAddress()); sb.append("\n\t\tLocal port: ").append(filter.localPort()); sb.append("\n\t\tRemote port: ").append(filter.remotePort()); } @@ -2611,281 +2767,194 @@ public static void print(NextHop resource) { .toString()); } - /** - * Print container group info. - * - * @param resource a container group - */ - public static void print(ContainerGroup resource) { - StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) - .append("Name: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.resourceGroupName()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tOS type: ").append(resource.osType()); +// /** +// * Print container group info. +// * +// * @param resource a container group +// */ +// public static void print(ContainerGroup resource) { +// StringBuilder info = new StringBuilder().append("Container Group: ").append(resource.id()) +// .append("Name: ").append(resource.name()) +// .append("\n\tResource group: ").append(resource.resourceGroupName()) +// .append("\n\tRegion: ").append(resource.region()) +// .append("\n\tTags: ").append(resource.tags()) +// .append("\n\tOS type: ").append(resource.osType()); +// +// if (resource.ipAddress() != null) { +// info.append("\n\tPublic IP address: ").append(resource.ipAddress()); +// } +// if (resource.externalTcpPorts() != null) { +// info.append("\n\tExternal TCP ports:"); +// for (int port : resource.externalTcpPorts()) { +// info.append(" ").append(port); +// } +// } +// if (resource.externalUdpPorts() != null) { +// info.append("\n\tExternal UDP ports:"); +// for (int port : resource.externalUdpPorts()) { +// info.append(" ").append(port); +// } +// } +// if (resource.imageRegistryServers() != null) { +// info.append("\n\tPrivate Docker image registries:"); +// for (String server : resource.imageRegistryServers()) { +// info.append(" ").append(server); +// } +// } +// if (resource.volumes() != null) { +// info.append("\n\tVolume mapping: "); +// for (Map.Entry entry : resource.volumes().entrySet()) { +// info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") +// .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); +// } +// } +// if (resource.containers() != null) { +// info.append("\n\tContainer instances: "); +// for (Map.Entry entry : resource.containers().entrySet()) { +// Container container = entry.getValue(); +// info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); +// info.append("\n\t\t\tResources: "); +// info.append(container.resources().requests().cpu()).append("CPUs "); +// info.append(container.resources().requests().memoryInGB()).append("GB"); +// info.append("\n\t\t\tPorts:"); +// for (ContainerPort port : container.ports()) { +// info.append(" ").append(port.port()); +// } +// if (container.volumeMounts() != null) { +// info.append("\n\t\t\tVolume mounts:"); +// for (VolumeMount volumeMount : container.volumeMounts()) { +// info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); +// } +// } +// if (container.command() != null) { +// info.append("\n\t\t\tStart commands:"); +// for (String command : container.command()) { +// info.append("\n\t\t\t\t").append(command); +// } +// } +// if (container.environmentVariables() != null) { +// info.append("\n\t\t\tENV vars:"); +// for (EnvironmentVariable envVar : container.environmentVariables()) { +// info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); +// } +// } +// } +// } +// +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub namespace. +// * +// * @param resource a virtual machine +// */ +// public static void print(EventHubNamespace resource) { +// StringBuilder info = new StringBuilder(); +// info.append("Eventhub Namespace: ").append(resource.id()) +// .append("\n\tName: ").append(resource.name()) +// .append("\n\tRegion: ").append(resource.region()) +// .append("\n\tTags: ").append(resource.tags()) +// .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) +// .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) +// .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) +// .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) +// .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) +// .append("\n\tCreated time: ").append(resource.createdAt()) +// .append("\n\tUpdated time: ").append(resource.updatedAt()); +// +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub. +// * +// * @param resource event hub +// */ +// public static void print(EventHub resource) { +// StringBuilder info = new StringBuilder(); +// info.append("Eventhub: ").append(resource.id()) +// .append("\n\tName: ").append(resource.name()) +// .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) +// .append("\n\tNamespace: ").append(resource.namespaceName()) +// .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) +// .append("\n\tPartition ids: ").append(resource.partitionIds()); +// if (resource.isDataCaptureEnabled()) { +// info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); +// info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); +// if (resource.captureDestination() != null) { +// info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); +// info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); +// } +// } +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub namespace recovery pairing. +// * +// * @param resource event hub namespace disaster recovery pairing +// */ +// public static void print(EventHubDisasterRecoveryPairing resource) { +// StringBuilder info = new StringBuilder(); +// info.append("DisasterRecoveryPairing: ").append(resource.id()) +// .append("\n\tName: ").append(resource.name()) +// .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) +// .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) +// .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) +// .append("\n\tNamespace role: ").append(resource.namespaceRole()); +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub namespace recovery pairing auth rules. +// * +// * @param resource event hub namespace disaster recovery pairing auth rule +// */ +// public static void print(DisasterRecoveryPairingAuthorizationRule resource) { +// StringBuilder info = new StringBuilder(); +// info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); +// List rightsStr = new ArrayList<>(); +// for (AccessRights rights : resource.rights()) { +// rightsStr.add(rights.toString()); +// } +// info.append("\n\tRights: ").append(rightsStr); +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub namespace recovery pairing auth rule key. +// * +// * @param resource event hub namespace disaster recovery pairing auth rule key +// */ +// public static void print(DisasterRecoveryPairingAuthorizationKey resource) { +// StringBuilder info = new StringBuilder(); +// info.append("DisasterRecoveryPairing auth key: ") +// .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) +// .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) +// .append("\n\t Primary key: ").append(resource.primaryKey()) +// .append("\n\t Secondary key: ").append(resource.secondaryKey()) +// .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) +// .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); +// System.out.println(info.toString()); +// } +// +// /** +// * Print event hub consumer group. +// * +// * @param resource event hub consumer group +// */ +// public static void print(EventHubConsumerGroup resource) { +// StringBuilder info = new StringBuilder(); +// info.append("Event hub consumer group: ").append(resource.id()) +// .append("\n\tName: ").append(resource.name()) +// .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) +// .append("\n\tNamespace: ").append(resource.namespaceName()) +// .append("\n\tEvent hub name: ").append(resource.eventHubName()) +// .append("\n\tUser metadata: ").append(resource.userMetadata()); +// System.out.println(info.toString()); +// } - if (resource.ipAddress() != null) { - info.append("\n\tPublic IP address: ").append(resource.ipAddress()); - } - if (resource.externalTcpPorts() != null) { - info.append("\n\tExternal TCP ports:"); - for (int port : resource.externalTcpPorts()) { - info.append(" ").append(port); - } - } - if (resource.externalUdpPorts() != null) { - info.append("\n\tExternal UDP ports:"); - for (int port : resource.externalUdpPorts()) { - info.append(" ").append(port); - } - } - if (resource.imageRegistryServers() != null) { - info.append("\n\tPrivate Docker image registries:"); - for (String server : resource.imageRegistryServers()) { - info.append(" ").append(server); - } - } - if (resource.volumes() != null) { - info.append("\n\tVolume mapping: "); - for (Map.Entry entry: resource.volumes().entrySet()) { - info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ") - .append(entry.getValue().azureFile() != null ? entry.getValue().azureFile().shareName() : "empty direcory volume"); - } - } - if (resource.containers() != null) { - info.append("\n\tContainer instances: "); - for (Map.Entry entry: resource.containers().entrySet()) { - Container container = entry.getValue(); - info.append("\n\t\tName: ").append(entry.getKey()).append(" -> ").append(container.image()); - info.append("\n\t\t\tResources: "); - info.append(container.resources().requests().cpu()).append("CPUs "); - info.append(container.resources().requests().memoryInGB()).append("GB"); - info.append("\n\t\t\tPorts:"); - for (ContainerPort port : container.ports()) { - info.append(" ").append(port.port()); - } - if (container.volumeMounts() != null) { - info.append("\n\t\t\tVolume mounts:"); - for (VolumeMount volumeMount : container.volumeMounts()) { - info.append(" ").append(volumeMount.name()).append("->").append(volumeMount.mountPath()); - } - } - if (container.command() != null) { - info.append("\n\t\t\tStart commands:"); - for (String command : container.command()) { - info.append("\n\t\t\t\t").append(command); - } - } - if (container.environmentVariables() != null) { - info.append("\n\t\t\tENV vars:"); - for (EnvironmentVariable envVar : container.environmentVariables()) { - info.append("\n\t\t\t\t").append(envVar.name()).append("=").append(envVar.value()); - } - } - } - } - - System.out.println(info.toString()); - } - - /** - * Print event hub namespace. - * - * @param resource a virtual machine - */ - public static void print(EventHubNamespace resource) { - StringBuilder info = new StringBuilder(); - info.append("Eventhub Namespace: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tRegion: ").append(resource.region()) - .append("\n\tTags: ").append(resource.tags()) - .append("\n\tAzureInsightMetricId: ").append(resource.azureInsightMetricId()) - .append("\n\tIsAutoScale enabled: ").append(resource.isAutoScaleEnabled()) - .append("\n\tServiceBus endpoint: ").append(resource.serviceBusEndpoint()) - .append("\n\tThroughPut upper limit: ").append(resource.throughputUnitsUpperLimit()) - .append("\n\tCurrent ThroughPut: ").append(resource.currentThroughputUnits()) - .append("\n\tCreated time: ").append(resource.createdAt()) - .append("\n\tUpdated time: ").append(resource.updatedAt()); - - System.out.println(info.toString()); - } - - /** - * Print event hub. - * - * @param resource event hub - */ - public static void print(EventHub resource) { - StringBuilder info = new StringBuilder(); - info.append("Eventhub: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) - .append("\n\tNamespace: ").append(resource.namespaceName()) - .append("\n\tIs data capture enabled: ").append(resource.isDataCaptureEnabled()) - .append("\n\tPartition ids: ").append(resource.partitionIds()); - if (resource.isDataCaptureEnabled()) { - info.append("\n\t\t\tData capture window size in MB: ").append(resource.dataCaptureWindowSizeInMB()); - info.append("\n\t\t\tData capture window size in seconds: ").append(resource.dataCaptureWindowSizeInSeconds()); - if (resource.captureDestination() != null) { - info.append("\n\t\t\tData capture storage account: ").append(resource.captureDestination().storageAccountResourceId()); - info.append("\n\t\t\tData capture storage container: ").append(resource.captureDestination().blobContainer()); - } - } - System.out.println(info.toString()); - } - - /** - * Print event hub namespace recovery pairing. - * - * @param resource event hub namespace disaster recovery pairing - */ - public static void print(EventHubDisasterRecoveryPairing resource) { - StringBuilder info = new StringBuilder(); - info.append("DisasterRecoveryPairing: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tPrimary namespace resource group name: ").append(resource.primaryNamespaceResourceGroupName()) - .append("\n\tPrimary namespace name: ").append(resource.primaryNamespaceName()) - .append("\n\tSecondary namespace: ").append(resource.secondaryNamespaceId()) - .append("\n\tNamespace role: ").append(resource.namespaceRole()); - System.out.println(info.toString()); - } - - /** - * Print event hub namespace recovery pairing auth rules. - * - * @param resource event hub namespace disaster recovery pairing auth rule - */ - public static void print(DisasterRecoveryPairingAuthorizationRule resource) { - StringBuilder info = new StringBuilder(); - info.append("DisasterRecoveryPairing auth rule: ").append(resource.name()); - List rightsStr = new ArrayList<>(); - for (com.microsoft.azure.management.eventhub.AccessRights rights : resource.rights()) { - rightsStr.add(rights.toString()); - } - info.append("\n\tRights: ").append(rightsStr); - System.out.println(info.toString()); - } - - /** - * Print event hub namespace recovery pairing auth rule key. - * - * @param resource event hub namespace disaster recovery pairing auth rule key - */ - public static void print(DisasterRecoveryPairingAuthorizationKey resource) { - StringBuilder info = new StringBuilder(); - info.append("DisasterRecoveryPairing auth key: ") - .append("\n\t Alias primary connection string: ").append(resource.aliasPrimaryConnectionString()) - .append("\n\t Alias secondary connection string: ").append(resource.aliasSecondaryConnectionString()) - .append("\n\t Primary key: ").append(resource.primaryKey()) - .append("\n\t Secondary key: ").append(resource.secondaryKey()) - .append("\n\t Primary connection string: ").append(resource.primaryConnectionString()) - .append("\n\t Secondary connection string: ").append(resource.secondaryConnectionString()); - System.out.println(info.toString()); - } - - /** - * Print event hub consumer group. - * - * @param resource event hub consumer group - */ - public static void print(EventHubConsumerGroup resource) { - StringBuilder info = new StringBuilder(); - info.append("Event hub consumer group: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tNamespace resource group: ").append(resource.namespaceResourceGroupName()) - .append("\n\tNamespace: ").append(resource.namespaceName()) - .append("\n\tEvent hub name: ").append(resource.eventHubName()) - .append("\n\tUser metadata: ").append(resource.userMetadata()); - System.out.println(info.toString()); - } - - /** - * Print Batch AI Cluster. - * - * @param resource batch ai cluster - */ - public static void print(BatchAICluster resource) { - StringBuilder info = new StringBuilder("Batch AI cluster: ") - .append("\n\tId: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tResource group: ").append(resource.workspace().resourceGroupName()) - .append("\n\tRegion: ").append(resource.workspace().regionName()) - .append("\n\tVM Size: ").append(resource.vmSize()) - .append("\n\tVM Priority: ").append(resource.vmPriority()) - .append("\n\tSubnet: ").append(resource.subnet()) - .append("\n\tAllocation state: ").append(resource.allocationState()) - .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) - .append("\n\tCreation time: ").append(resource.creationTime()) - .append("\n\tCurrent node count: ").append(resource.currentNodeCount()) - .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()) - .append("\n\tAllocation state transition time: ").append(resource.allocationStateTransitionTime()); - if (resource.scaleSettings().autoScale() != null) { - info.append("\n\tAuto scale settings: ") - .append("\n\t\tInitial node count: ").append(resource.scaleSettings().autoScale().initialNodeCount()) - .append("\n\t\tMinimum node count: ").append(resource.scaleSettings().autoScale().minimumNodeCount()) - .append("\n\t\tMaximum node count: ").append(resource.scaleSettings().autoScale().maximumNodeCount()); - } - if (resource.scaleSettings().manual() != null) { - info.append("\n\tManual scale settings: ") - .append("\n\t\tTarget node count: ").append(resource.scaleSettings().manual().targetNodeCount()) - .append("\n\t\tDeallocation option: ") - .append(resource.scaleSettings().manual().nodeDeallocationOption()); - } - if (resource.nodeStateCounts() != null) { - info.append("\n\tNode state counts: ") - .append("\n\t\tRunning nodes count: ").append(resource.nodeStateCounts().runningNodeCount()) - .append("\n\t\tIdle nodes count: ").append(resource.nodeStateCounts().idleNodeCount()) - .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()) - .append("\n\t\tLeaving nodes count: ").append(resource.nodeStateCounts().leavingNodeCount()) - .append("\n\t\tPreparing nodes count: ").append(resource.nodeStateCounts().preparingNodeCount()); - } - if (resource.virtualMachineConfiguration() != null && resource.virtualMachineConfiguration().imageReference() != null) { - info.append("\n\tVirtual machine configuration: ") - .append("\n\t\tPublisher: ").append(resource.virtualMachineConfiguration().imageReference().publisher()) - .append("\n\t\tOffer: ").append(resource.virtualMachineConfiguration().imageReference().offer()) - .append("\n\t\tSku: ").append(resource.virtualMachineConfiguration().imageReference().sku()) - .append("\n\t\tVersion: ").append(resource.virtualMachineConfiguration().imageReference().version()); - } - if (resource.nodeSetup() != null && resource.nodeSetup().setupTask() != null) { - info.append("\n\tSetup task: ") - .append("\n\t\tCommand line: ").append(resource.nodeSetup().setupTask().commandLine()) - .append("\n\t\tStdout/err Path Prefix: ").append(resource.nodeSetup().setupTask().stdOutErrPathPrefix()); - } - System.out.println(info.toString()); - } - - /** - * Print Batch AI Job. - * - * @param resource batch ai job - */ - public static void print(BatchAIJob resource) { - StringBuilder info = new StringBuilder("Batch AI job: ") - .append("\n\tId: ").append(resource.id()) - .append("\n\tName: ").append(resource.name()) - .append("\n\tCluster Id: ").append(resource.cluster()) - .append("\n\tCreation time: ").append(resource.creationTime()) - .append("\n\tNode count: ").append(resource.nodeCount()) - .append("\n\tPriority: ").append(resource.schedulingPriority()) - .append("\n\tExecution state: ").append(resource.executionState()) - .append("\n\tExecution state transition time: ").append(resource.executionStateTransitionTime()) - .append("\n\tTool type: ").append(resource.toolType()) - .append("\n\tExperiment name: ").append(resource.experiment().name()); - if (resource.mountVolumes() != null) { - info.append("\n\tMount volumes:"); - if (resource.mountVolumes().azureFileShares() != null) { - info.append("\n\t\tAzure fileshares:"); - for (AzureFileShareReference share : resource.mountVolumes().azureFileShares()) { - info.append("\n\t\t\tAccount name:").append(share.accountName()) - .append("\n\t\t\tFile Url:").append(share.azureFileUrl()) - .append("\n\t\t\tDirectory mode:").append(share.directoryMode()) - .append("\n\t\t\tFile mode:").append(share.fileMode()) - .append("\n\t\t\tRelative mount path:").append(share.relativeMountPath()); - } - } - } - System.out.println(info.toString()); - } /** * Print Diagnostic Setting. @@ -3125,32 +3194,209 @@ public static void print(MetricAlert metricAlert) { } System.out.println(info.toString()); } - private static OkHttpClient httpClient; - /** - * Ensure the HTTP client is valid. +// /** +// * Print spring service settings. +// * +// * @param springService spring service instance +// */ +// public static void print(SpringService springService) { +// StringBuilder info = new StringBuilder("Spring Service: ") +// .append("\n\tId: ").append(springService.id()) +// .append("\n\tName: ").append(springService.name()) +// .append("\n\tResource Group: ").append(springService.resourceGroupName()) +// .append("\n\tRegion: ").append(springService.region()) +// .append("\n\tTags: ").append(springService.tags()); +// +// ConfigServerProperties serverProperties = springService.getServerProperties(); +// if (serverProperties != null && serverProperties.provisioningState() != null +// && serverProperties.provisioningState().equals(ConfigServerState.SUCCEEDED) && serverProperties.configServer() != null) { +// info.append("\n\tProperties: "); +// if (serverProperties.configServer().gitProperty() != null) { +// info.append("\n\t\tGit: ").append(serverProperties.configServer().gitProperty().uri()); +// } +// } +// +// if (springService.sku() != null) { +// info.append("\n\tSku: ") +// .append("\n\t\tName: ").append(springService.sku().name()) +// .append("\n\t\tTier: ").append(springService.sku().tier()) +// .append("\n\t\tCapacity: ").append(springService.sku().capacity()); +// } +// +// MonitoringSettingProperties monitoringSettingProperties = springService.getMonitoringSetting(); +// if (monitoringSettingProperties != null && monitoringSettingProperties.provisioningState() != null +// && monitoringSettingProperties.provisioningState().equals(MonitoringSettingState.SUCCEEDED)) { +// info.append("\n\tTrace: ") +// .append("\n\t\tEnabled: ").append(monitoringSettingProperties.traceEnabled()) +// .append("\n\t\tApp Insight Instrumentation Key: ").append(monitoringSettingProperties.appInsightsInstrumentationKey()); +// } +// +// System.out.println(info.toString()); +// } +// +// /** +// * Print spring app settings. +// * +// * @param springApp spring app instance +// */ +// public static void print(SpringApp springApp) { +// StringBuilder info = new StringBuilder("Spring Service: ") +// .append("\n\tId: ").append(springApp.id()) +// .append("\n\tName: ").append(springApp.name()) +// .append("\n\tCreated Time: ").append(springApp.createdTime()) +// .append("\n\tPublic Endpoint: ").append(springApp.isPublic()) +// .append("\n\tUrl: ").append(springApp.url()) +// .append("\n\tHttps Only: ").append(springApp.isHttpsOnly()) +// .append("\n\tFully Qualified Domain Name: ").append(springApp.fqdn()) +// .append("\n\tActive Deployment Name: ").append(springApp.activeDeploymentName()); +// +// if (springApp.temporaryDisk() != null) { +// info.append("\n\tTemporary Disk:") +// .append("\n\t\tSize In GB: ").append(springApp.temporaryDisk().sizeInGB()) +// .append("\n\t\tMount Path: ").append(springApp.temporaryDisk().mountPath()); +// } +// +// if (springApp.persistentDisk() != null) { +// info.append("\n\tPersistent Disk:") +// .append("\n\t\tSize In GB: ").append(springApp.persistentDisk().sizeInGB()) +// .append("\n\t\tMount Path: ").append(springApp.persistentDisk().mountPath()); +// } +// +// if (springApp.identity() != null) { +// info.append("\n\tIdentity:") +// .append("\n\t\tType: ").append(springApp.identity().type()) +// .append("\n\t\tPrincipal Id: ").append(springApp.identity().principalId()) +// .append("\n\t\tTenant Id: ").append(springApp.identity().tenantId()); +// } +// +// System.out.println(info.toString()); +// } + + /** + * Sends a GET request to target URL. + *

+ * Retry logic tuned for AppService. + * The method does not handle 301 redirect. * + * @param urlString the target URL. + * @return Content of the HTTP response. */ - private static OkHttpClient ensureValidHttpClient() { - if (httpClient == null) { - httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build(); - } + public static String sendGetRequest(String urlString) { + ClientLogger logger = new ClientLogger(Utils.class); - return httpClient; + try { + Mono>> response = + HTTP_CLIENT.getString(getHost(urlString), getPathAndQuery(urlString)) + .retryWhen(Retry + .fixedDelay(5, Duration.ofSeconds(30)) + .filter(t -> { + boolean retry = false; + if (t instanceof TimeoutException) { + retry = true; + } else if (t instanceof HttpResponseException + && ((HttpResponseException) t).getResponse().getStatusCode() == 503) { + retry = true; + } + + if (retry) { + logger.info("retry GET request to {}", urlString); + } + return retry; + })); + Response ret = stringResponse(response).block(); + return ret == null ? null : ret.getValue(); + } catch (MalformedURLException e) { + logger.logThrowableAsError(e); + return null; + } } /** - * Connect to a specified URL using "curl" like HTTP GET client. + * Sends a POST request to target URL. + *

+ * Retry logic tuned for AppService. * - * @param url URL to be tested - * @return the HTTP GET response content - */ - public static String curl(String url) { - Request request = new Request.Builder().url(url).get().build(); + * @param urlString the target URL. + * @param body the request body. + * @return Content of the HTTP response. + * */ + public static String sendPostRequest(String urlString, String body) { + ClientLogger logger = new ClientLogger(Utils.class); + try { - return ensureValidHttpClient().newCall(request).execute().body().string(); - } catch (IOException e) { + Mono> response = + stringResponse(HTTP_CLIENT.postString(getHost(urlString), getPathAndQuery(urlString), body)) + .retryWhen(Retry + .fixedDelay(5, Duration.ofSeconds(30)) + .filter(t -> { + boolean retry = false; + if (t instanceof TimeoutException) { + retry = true; + } + + if (retry) { + logger.info("retry POST request to {}", urlString); + } + return retry; + })); + Response ret = response.block(); + return ret == null ? null : ret.getValue(); + } catch (Exception e) { + logger.logThrowableAsError(e); return null; } } + + private static Mono> stringResponse(Mono>> responseMono) { + return responseMono.flatMap(response -> FluxUtil.collectBytesInByteBufferStream(response.getValue()) + .map(bytes -> new String(bytes, StandardCharsets.UTF_8)) + .map(str -> new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), str))); + } + + private static String getHost(String urlString) throws MalformedURLException { + URL url = new URL(urlString); + String protocol = url.getProtocol(); + String host = url.getAuthority(); + return protocol + "://" + host; + } + + private static String getPathAndQuery(String urlString) throws MalformedURLException { + URL url = new URL(urlString); + String path = url.getPath(); + String query = url.getQuery(); + if (query != null && !query.isEmpty()) { + path = path + "?" + query; + } + return path; + } + + private static final WebAppTestClient HTTP_CLIENT = RestProxy.create( + WebAppTestClient.class, + new HttpPipelineBuilder() + .policies( + new HttpLoggingPolicy(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BASIC)), + new RetryPolicy("Retry-After", ChronoUnit.SECONDS)) + .build()); + + @Host("{$host}") + @ServiceInterface(name = "WebAppTestClient") + private interface WebAppTestClient { + @Get("{path}") + @ExpectedResponses({200, 400, 404}) + Mono>> getString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path); + + @Post("{path}") + @ExpectedResponses({200, 400, 404}) + Mono>> postString(@HostParam("$host") String host, @PathParam(value = "path", encoded = true) String path, @BodyParam("text/plain") String body); + } + + public static int getSize(Iterable iterable) { + int res = 0; + Iterator iterator = iterable.iterator(); + while (iterator.hasNext()) { + iterator.next(); + } + return res; + } }