From a1bcaf4bef02ff094f6b92563f83073e81733826 Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Tue, 17 Nov 2020 14:26:06 +0800 Subject: [PATCH 1/7] Revert "Mgmt: GA azure, remove non-GA packages (#16499)" This reverts commit 2756f500460f587abbaa4209e43bbc1e82b0107b. --- sdk/resourcemanager/README.md | 2 +- .../azure-resourcemanager-samples/README.md | 2 +- .../samples/ManageSpringCloud.java | 670 +++--- .../ManageLinuxWebAppCosmosDbByMsi.java | 490 ++-- .../ManageLinuxWebAppSqlConnection.java | 318 +-- ...anageLinuxWebAppWithContainerRegistry.java | 402 ++-- .../ManageLinuxWebAppWithTrafficManager.java | 588 ++--- .../samples/ManageWebAppSqlConnection.java | 312 +-- .../ManageWebAppWithTrafficManager.java | 584 ++--- .../cdn/samples/ManageCdn.java | 362 +-- .../samples/ManageCdnWithCustomDomain.java | 356 +-- ...tainerInstanceWithAzureFileShareMount.java | 296 +-- ...WithManualAzureFileShareMountCreation.java | 328 +-- ...erInstanceWithMultipleContainerImages.java | 266 +-- ...ManyUsingContainerServiceOrchestrator.java | 1050 ++++---- .../samples/ManageContainerRegistry.java | 404 ++-- .../ManageContainerRegistryWithWebhooks.java | 442 ++-- .../eventhubs/samples/ManageEventHub.java | 404 ++-- .../samples/ManageEventHubEvents.java | 310 +-- .../ManageEventHubGeoDisasterRecovery.java | 384 +-- ...mageFromContainerRegistryToKubernetes.java | 956 ++++---- .../privatedns/samples/ManagePrivateDns.java | 410 ++-- .../rediscache/samples/ManageRedisCache.java | 382 +-- .../azure/resourcemanager/samples/Utils.java | 2104 +++++++++-------- ...iceBusPublishSubscribeAdvanceFeatures.java | 450 ++-- .../ServiceBusPublishSubscribeBasic.java | 418 ++-- .../ServiceBusQueueAdvanceFeatures.java | 402 ++-- .../samples/ServiceBusQueueBasic.java | 410 ++-- ...ServiceBusWithClaimBasedAuthorization.java | 330 +-- .../sql/samples/GettingSqlServerMetrics.java | 702 +++--- .../sql/samples/ManageSqlDatabase.java | 310 +-- .../ManageSqlDatabaseInElasticPool.java | 484 ++-- ...qlDatabasesAcrossDifferentDataCenters.java | 474 ++-- .../sql/samples/ManageSqlFailoverGroups.java | 390 +-- .../sql/samples/ManageSqlFirewallRules.java | 304 +-- .../ManageSqlImportExportDatabase.java | 328 +-- .../samples/ManageSqlServerDnsAliases.java | 478 ++-- ...nageSqlServerKeysWithAzureKeyVaultKey.java | 362 +-- .../ManageSqlServerSecurityAlertPolicy.java | 280 +-- .../samples/ManageSqlVirtualNetworkRules.java | 332 +-- ...ageSqlWithRecoveredOrRestoredDatabase.java | 358 +-- .../samples/ManageSimpleTrafficManager.java | 360 +-- .../samples/ManageTrafficManager.java | 542 ++--- .../samples/AppPlatformLiveOnlyTests.java | 28 +- .../AppServiceSampleLiveOnlyTests.java | 76 +- .../samples/AppServiceSampleTests.java | 25 +- .../samples/CdnSampleLiveOnlyTests.java | 23 +- .../samples/CdnSampleTests.java | 12 +- .../samples/ContainerInstanceTests.java | 72 +- .../samples/ContainerRegistryTests.java | 46 +- .../samples/EventHubsSampleTests.java | 34 +- .../samples/KubernetesClusterTests.java | 13 +- .../samples/PrivateDnsSampleTests.java | 12 +- .../samples/RedisCacheSampleTests.java | 12 +- .../ServiceBusSampleLiveOnlyTests.java | 97 +- .../samples/SqlSampleTests.java | 203 +- .../samples/TrafficManagerSampleTests.java | 36 +- .../azure-resourcemanager/README.md | 2 +- .../azure-resourcemanager/pom.xml | 50 + .../resourcemanager/AzureResourceManager.java | 240 +- .../src/main/java/module-info.java | 20 +- .../AzureResourceManagerTests.java | 350 +-- ...ContainerInstanceWithPrivateIpAddress.java | 472 ++-- ...hPublicIpAddressWithSystemAssignedMSI.java | 428 ++-- .../TestContainerRegistry.java | 348 +-- .../azure/resourcemanager/TestPrivateDns.java | 814 +++---- .../com/azure/resourcemanager/TestRedis.java | 98 +- .../com/azure/resourcemanager/TestSql.java | 180 +- .../resourcemanager/TestTrafficManager.java | 814 +++---- 69 files changed, 12138 insertions(+), 11903 deletions(-) diff --git a/sdk/resourcemanager/README.md b/sdk/resourcemanager/README.md index 373b8460efde..6612202a1f55 100644 --- a/sdk/resourcemanager/README.md +++ b/sdk/resourcemanager/README.md @@ -28,7 +28,7 @@ If you are an existing user of the older version of Azure management library for com.azure.resourcemanager azure-resourcemanager - 2.0.0 + 2.0.0-beta.5 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/README.md b/sdk/resourcemanager/azure-resourcemanager-samples/README.md index a4947dc6a68b..d927a16ffd87 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-samples/README.md @@ -17,7 +17,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager - 2.0.0 + 2.0.0-beta.5 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index 5d477cfde58e..9f4608d3fb54 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -1,337 +1,337 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -//package com.azure.resourcemanager.appplatform.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.util.Configuration; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appplatform.models.SpringApp; -//import com.azure.resourcemanager.appplatform.models.SpringService; -//import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; -//import com.azure.resourcemanager.appservice.models.AppServiceDomain; -//import com.azure.resourcemanager.dns.models.DnsZone; -//import com.azure.resourcemanager.keyvault.models.CertificatePermissions; -//import com.azure.resourcemanager.keyvault.models.Secret; -//import com.azure.resourcemanager.keyvault.models.SecretPermissions; -//import com.azure.resourcemanager.keyvault.models.Vault; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.security.keyvault.certificates.CertificateClient; -//import com.azure.security.keyvault.certificates.CertificateClientBuilder; -//import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; -//import org.apache.commons.compress.archivers.tar.TarArchiveEntry; -//import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; -//import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; -//import org.apache.commons.compress.utils.IOUtils; -// -//import javax.xml.bind.DatatypeConverter; -//import java.io.ByteArrayInputStream; -//import java.io.File; -//import java.io.FileOutputStream; -//import java.io.IOException; -//import java.io.InputStream; -//import java.io.OutputStream; -//import java.net.HttpURLConnection; -//import java.net.URL; -//import java.security.KeyStore; -//import java.security.KeyStoreException; -//import java.security.MessageDigest; -//import java.security.NoSuchAlgorithmException; -//import java.security.cert.CertificateException; -//import java.util.Base64; -//import java.util.Collections; -// -///** -// * Azure App Platform sample for managing Spring Cloud. -// * - Create a Spring Cloud Service -// * - Create 3 app: gateway, auth-service, account-service from sample -// * - Open public endpoint for gateway -// * - Create a custom domain -// * - Add a CNAME to the gateway fully qualified domain name -// * - Order a certificate -// * - Save the certificate to a key vault -// * - Assign certificate to spring cloud -// * - Assign custom domain to gateway endpoint -// */ -//public class ManageSpringCloud { -// private static final String PIGGYMETRICS_TAR_GZ_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; -// private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @param clientId the aad client id in azure instance -// * @return true if sample runs successfully -// * @throws IllegalStateException unexcepted state -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); -// final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); -// final Region region = Region.US_EAST; -// final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; -// final String certOrderName = Utils.randomResourceName(azureResourceManager, "cert", 15); -// final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); -// final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); -// -// try { -// azureResourceManager.resourceGroups().define(rgName) -// .withRegion(region) -// .create(); -// -// //============================================================ -// // Create a spring cloud service with 3 apps: gateway, auth-service, account-service -// -// System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); -// -// SpringService service = azureResourceManager.springServices().define(serviceName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .create(); -// -// System.out.printf("Created spring cloud service %s%n", service.name()); -// Utils.print(service); -// -// // get source code of a sample project -// File gzFile = new File("piggymetrics.tar.gz"); -// if (!gzFile.exists()) { -// HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); -// connection.connect(); -// try (InputStream inputStream = connection.getInputStream(); -// OutputStream outputStream = new FileOutputStream(gzFile)) { -// IOUtils.copy(inputStream, outputStream); -// } -// connection.disconnect(); -// } -// -// //============================================================ -// // Create spring cloud app: gateway -// -// System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); -// SpringApp gateway = service.apps().define("gateway") -// .defineActiveDeployment("default") -// .withSourceCodeTarGzFile(gzFile) -// .withTargetModule("gateway") -// .attach() -// .withDefaultPublicEndpoint() -// .withHttpsOnly() -// .create(); -// -// System.out.println("Created spring cloud service gateway"); -// Utils.print(gateway); -// -// //============================================================ -// // Create spring cloud app: auth-service -// -// System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); -// SpringApp authService = service.apps().define("auth-service") -// .defineActiveDeployment("default") -// .withSourceCodeTarGzFile(gzFile) -// .withTargetModule("auth-service") -// .attach() -// .create(); -// -// System.out.println("Created spring cloud service auth-service"); -// Utils.print(authService); -// -// //============================================================ -// // Create spring cloud app: account-service -// -// System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); -// SpringApp accountService = service.apps().define("account-service") -// .defineActiveDeployment("default") -// .withSourceCodeTarGzFile(gzFile) -// .withTargetModule("account-service") -// .attach() -// .create(); -// -// System.out.println("Created spring cloud service account-service"); -// Utils.print(accountService); -// -// //============================================================ -// // Create App Service Domain and Certificate -// -// System.out.println("Purchasing a domain " + domainName + "..."); -// -// AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) -// .withExistingResourceGroup(rgName) -// .defineRegistrantContact() -// .withFirstName("Jon") -// .withLastName("Doe") -// .withEmail("jondoe@contoso.com") -// .withAddressLine1("123 4th Ave") -// .withCity("Redmond") -// .withStateOrProvince("WA") -// .withCountry(CountryIsoCode.UNITED_STATES) -// .withPostalCode("98052") -// .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) -// .withPhoneNumber("4258828080") -// .attach() -// .withDomainPrivacyEnabled(true) -// .withAutoRenewEnabled(false) -// .create(); -// System.out.println("Purchased domain " + domain.name()); -// Utils.print(domain); -// -// DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); -// gateway.refresh(); -// -// System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); -// dnsZone.update() -// .withCNameRecordSet("ssl", gateway.fqdn()) -// .apply(); -// -// // Please use a trusted certificate for actual use -// System.out.printf("Generate a self-signed certificate for ssl.%s %n", domainName); -// allowAllSSL(); -// String cerPassword = password(); -// String cerPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".cer"; -// String pfxPath = ManageSpringCloud.class.getClass().getResource("/").getPath() + domainName + ".pfx"; -// createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); -// -// byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); -// -// System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); -// Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); -// vault.update() -// .defineAccessPolicy() -// .forServicePrincipal(clientId) -// .allowSecretAllPermissions() -// .allowCertificateAllPermissions() -// .attach() -// .defineAccessPolicy() -// .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) -// .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) -// .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) -// .attach() -// .apply(); -// System.out.printf("Created key vault %s%n", vault.name()); -// Utils.print(vault); -// -// KeyStore store = KeyStore.getInstance("PKCS12"); -// store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); -// String alias = Collections.list(store.aliases()).get(0); -// thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); -// -// System.out.printf("Get certificate: %s%n", secret.getValue()); -// System.out.printf("Certificate Thumbprint: %s%n", thumbprint); -// -// // upload certificate -// CertificateClient certificateClient = new CertificateClientBuilder() -// .vaultUrl(vault.vaultUri()) -// .pipeline(service.manager().httpPipeline()) -// .buildClient(); -// -// System.out.printf("Uploading certificate to %s in key vault ...%n", certName); -// certificateClient.importCertificate( -// new ImportCertificateOptions(certName, certificate) -// .setPassword(cerPassword) -// .setEnabled(true) -// ); -// -// //============================================================ -// // Update Certificate and Custom Domain for Spring Cloud -// System.out.println("Updating Spring Cloud Service with certificate ..."); -// service.update() -// .withCertificate(certName, vault.vaultUri(), certName) -// .apply(); -// -// System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); -// gateway.update() -// .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) -// .apply(); -// -// System.out.printf("Successfully expose domain ssl.%s%n", domainName); -// -// return true; -// } finally { -// try { -// System.out.println("Delete Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// } catch (NullPointerException npe) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// public static void extraTarGzSource(File folder, URL url) throws IOException { -// HttpURLConnection connection = (HttpURLConnection) url.openConnection(); -// connection.connect(); -// try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { -// TarArchiveEntry entry; -// while ((entry = inputStream.getNextTarEntry()) != null) { -// if (entry.isDirectory()) { -// continue; -// } -// File file = new File(folder, entry.getName()); -// File parent = file.getParentFile(); -// if (parent.exists() || parent.mkdirs()) { -// try (OutputStream outputStream = new FileOutputStream(file)) { -// IOUtils.copy(inputStream, outputStream); -// } -// } else { -// throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); -// } -// } -// } finally { -// connection.disconnect(); -// } -// } -// -// private static void allowAllSSL() throws NoSuchAlgorithmException, KeyManagementException { -// TrustManager[] trustAllCerts = new TrustManager[]{ -// new X509TrustManager() { -// public java.security.cert.X509Certificate[] getAcceptedIssuers() { -// return null; -// } -// public void checkClientTrusted( -// java.security.cert.X509Certificate[] certs, String authType) { -// } -// public void checkServerTrusted( -// java.security.cert.X509Certificate[] certs, String authType) { -// } -// } -// }; -// SSLContext sslContext = SSLContext.getInstance("SSL"); -// sslContext.init(null, trustAllCerts, new SecureRandom()); -// HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); -// } -//} + +package com.azure.resourcemanager.appplatform.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appplatform.models.SpringApp; +import com.azure.resourcemanager.appplatform.models.SpringService; +import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.keyvault.models.CertificatePermissions; +import com.azure.resourcemanager.keyvault.models.Secret; +import com.azure.resourcemanager.keyvault.models.SecretPermissions; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.security.keyvault.certificates.CertificateClient; +import com.azure.security.keyvault.certificates.CertificateClientBuilder; +import com.azure.security.keyvault.certificates.models.ImportCertificateOptions; +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; +import org.apache.commons.compress.utils.IOUtils; + +import javax.xml.bind.DatatypeConverter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.Base64; +import java.util.Collections; + +/** + * Azure App Platform sample for managing Spring Cloud. + * - Create a Spring Cloud Service + * - Create 3 app: gateway, auth-service, account-service from sample + * - Open public endpoint for gateway + * - Create a custom domain + * - Add a CNAME to the gateway fully qualified domain name + * - Order a certificate + * - Save the certificate to a key vault + * - Assign certificate to spring cloud + * - Assign custom domain to gateway endpoint + */ +public class ManageSpringCloud { + private static final String PIGGYMETRICS_TAR_GZ_URL = "https://github.com/weidongxu-microsoft/azure-sdk-for-java-management-tests/raw/master/spring-cloud/piggymetrics.tar.gz"; + private static final String SPRING_CLOUD_SERVICE_PRINCIPAL = "03b39d0f-4213-4864-a245-b1476ec03169"; + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @param clientId the aad client id in azure instance + * @return true if sample runs successfully + * @throws IllegalStateException unexcepted state + */ + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); + final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); + final Region region = Region.US_EAST; + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String certOrderName = Utils.randomResourceName(azureResourceManager, "cert", 15); + final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); + final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); + + try { + azureResourceManager.resourceGroups().define(rgName) + .withRegion(region) + .create(); + + //============================================================ + // Create a spring cloud service with 3 apps: gateway, auth-service, account-service + + System.out.printf("Creating spring cloud service %s in resource group %s ...%n", serviceName, rgName); + + SpringService service = azureResourceManager.springServices().define(serviceName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); + + System.out.printf("Created spring cloud service %s%n", service.name()); + Utils.print(service); + + // get source code of a sample project + File gzFile = new File("piggymetrics.tar.gz"); + if (!gzFile.exists()) { + HttpURLConnection connection = (HttpURLConnection) new URL(PIGGYMETRICS_TAR_GZ_URL).openConnection(); + connection.connect(); + try (InputStream inputStream = connection.getInputStream(); + OutputStream outputStream = new FileOutputStream(gzFile)) { + IOUtils.copy(inputStream, outputStream); + } + connection.disconnect(); + } + + //============================================================ + // Create spring cloud app: gateway + + System.out.printf("Creating spring cloud app gateway in resource group %s ...%n", rgName); + SpringApp gateway = service.apps().define("gateway") + .defineActiveDeployment("default") + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("gateway") + .attach() + .withDefaultPublicEndpoint() + .withHttpsOnly() + .create(); + + System.out.println("Created spring cloud service gateway"); + Utils.print(gateway); + + //============================================================ + // Create spring cloud app: auth-service + + System.out.printf("Creating spring cloud app auth-service in resource group %s ...%n", rgName); + SpringApp authService = service.apps().define("auth-service") + .defineActiveDeployment("default") + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("auth-service") + .attach() + .create(); + + System.out.println("Created spring cloud service auth-service"); + Utils.print(authService); + + //============================================================ + // Create spring cloud app: account-service + + System.out.printf("Creating spring cloud app account-service in resource group %s ...%n", rgName); + SpringApp accountService = service.apps().define("account-service") + .defineActiveDeployment("default") + .withSourceCodeTarGzFile(gzFile) + .withTargetModule("account-service") + .attach() + .create(); + + System.out.println("Created spring cloud service account-service"); + Utils.print(accountService); + + //============================================================ + // Create App Service Domain and Certificate + + System.out.println("Purchasing a domain " + domainName + "..."); + + AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); + System.out.println("Purchased domain " + domain.name()); + Utils.print(domain); + + DnsZone dnsZone = azureResourceManager.dnsZones().getById(domain.dnsZoneId()); + gateway.refresh(); + + System.out.printf("Updating dns with CNAME ssl.%s to %s%n", domainName, gateway.fqdn()); + dnsZone.update() + .withCNameRecordSet("ssl", gateway.fqdn()) + .apply(); + + // Please use a trusted certificate for actual use + System.out.printf("Generate a self-signed certificate for ssl.%s %n", domainName); + allowAllSSL(); + String cerPassword = password(); + String cerPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".cer"; + String pfxPath = ManageSpringCloud.class.getClass().getResource("/").getPath() + domainName + ".pfx"; + createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); + + byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); + + System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); + Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); + vault.update() + .defineAccessPolicy() + .forServicePrincipal(clientId) + .allowSecretAllPermissions() + .allowCertificateAllPermissions() + .attach() + .defineAccessPolicy() + .forServicePrincipal(SPRING_CLOUD_SERVICE_PRINCIPAL) + .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) + .attach() + .apply(); + System.out.printf("Created key vault %s%n", vault.name()); + Utils.print(vault); + + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); + String alias = Collections.list(store.aliases()).get(0); + thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); + + System.out.printf("Get certificate: %s%n", secret.getValue()); + System.out.printf("Certificate Thumbprint: %s%n", thumbprint); + + // upload certificate + CertificateClient certificateClient = new CertificateClientBuilder() + .vaultUrl(vault.vaultUri()) + .pipeline(service.manager().httpPipeline()) + .buildClient(); + + System.out.printf("Uploading certificate to %s in key vault ...%n", certName); + certificateClient.importCertificate( + new ImportCertificateOptions(certName, certificate) + .setPassword(cerPassword) + .setEnabled(true) + ); + + //============================================================ + // Update Certificate and Custom Domain for Spring Cloud + System.out.println("Updating Spring Cloud Service with certificate ..."); + service.update() + .withCertificate(certName, vault.vaultUri(), certName) + .apply(); + + System.out.printf("Updating Spring Cloud App with domain ssl.%s ...%n", domainName); + gateway.update() + .withCustomDomain(String.format("ssl.%s", domainName), thumbprint) + .apply(); + + System.out.printf("Successfully expose domain ssl.%s%n", domainName); + + return true; + } finally { + try { + System.out.println("Delete Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + } catch (NullPointerException npe) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager, Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLIENT_ID)); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + public static void extraTarGzSource(File folder, URL url) throws IOException { + HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.connect(); + try (TarArchiveInputStream inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(connection.getInputStream()))) { + TarArchiveEntry entry; + while ((entry = inputStream.getNextTarEntry()) != null) { + if (entry.isDirectory()) { + continue; + } + File file = new File(folder, entry.getName()); + File parent = file.getParentFile(); + if (parent.exists() || parent.mkdirs()) { + try (OutputStream outputStream = new FileOutputStream(file)) { + IOUtils.copy(inputStream, outputStream); + } + } else { + throw new IllegalStateException("Cannot create directory: " + parent.getAbsolutePath()); + } + } + } finally { + connection.disconnect(); + } + } + + private static void allowAllSSL() throws NoSuchAlgorithmException, KeyManagementException { + TrustManager[] trustAllCerts = new TrustManager[]{ + new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + public void checkClientTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + public void checkServerTrusted( + java.security.cert.X509Certificate[] certs, String authType) { + } + } + }; + SSLContext sslContext = SSLContext.getInstance("SSL"); + sslContext.init(null, trustAllCerts, new SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java index f9946c5c2977..a0015b6863e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppCosmosDbByMsi.java @@ -1,247 +1,247 @@ // 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.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.authorization.models.ServicePrincipal; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; -//import com.azure.resourcemanager.keyvault.models.SecretPermissions; -//import com.azure.resourcemanager.keyvault.models.Vault; -//import com.azure.resourcemanager.samples.DockerUtils; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.PullImageResultCallback; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.core.command.PushImageResultCallback; -// -//import java.io.IOException; -//import java.nio.file.Files; -//import java.nio.file.Paths; -// -///** -// * Azure App Service basic sample for managing web apps. -// * - Create a Cosmos DB with credentials stored in a Key Vault -// * - Create a web app which interacts with the Cosmos DB by first -// * reading the secrets from the Key Vault. -// * -// * The source code of the web app is located at -// * https://github.com/Microsoft/todo-app-java-on-azure/tree/keyvault-secrets -// */ -//public final class ManageLinuxWebAppCosmosDbByMsi { -// -// /** -// * Main function which runs the actual sample. -// * @param azure instance of the azure client -// * @param clientId the client ID -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azure, String clientId) throws IOException, InterruptedException { -// // New resources -// final Region region = Region.US_WEST; -// final String acrName = Utils.randomResourceName(azure, "acr", 20); -// final String appName = Utils.randomResourceName(azure, "webapp1-", 20); -// final String password = Utils.password(); -// final String rgName = Utils.randomResourceName(azure, "rg1NEMV_", 24); -// final String vaultName = Utils.randomResourceName(azure, "vault", 20); -// final String cosmosName = Utils.randomResourceName(azure, "cosmosdb", 20); -// -// String servicePrincipalClientId = clientId; // replace with a real service principal client id -// -// try { -// //============================================================ -// // Create a CosmosDB -// -// System.out.println("Creating a CosmosDB..."); -// CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts().define(cosmosName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withDataModelSql() -// .withStrongConsistency() -// .create(); -// -// System.out.println("Created CosmosDB"); -// Utils.print(cosmosDBAccount); -// -// //============================================================ -// // Create a service principal -// -// ServicePrincipal servicePrincipal = azure.accessManagement().servicePrincipals() -// .define(appName) -// .withNewApplication("http://" + appName + ".azurewebsites.net") -// .definePasswordCredential("password") -// .withPasswordValue(password) -// .attach() -// .create(); -// -// //============================================================= -// // If service principal client id and secret are not set via the local variables, attempt to read the service -// // principal client id and secret from a secondary ".azureauth" file set through an environment variable. -// // -// // If the environment variable was not set then reuse the main service principal set for running this sample. -// -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { -// servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { -// String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); -// -// if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { -// envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); -// } -// -// servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); -// } -// } -// -// //============================================================ -// // Create a key vault -// -// Vault vault = azure.vaults() -// .define(vaultName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .defineAccessPolicy() -// .forServicePrincipal(servicePrincipalClientId) -// .allowSecretAllPermissions() -// .attach() -// .defineAccessPolicy() -// .forServicePrincipal(servicePrincipal) -// .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) -// .attach() -// .create(); -// -//// SdkContext.sleep(10000); -// -// //============================================================ -// // Store Cosmos DB credentials in Key Vault -// -// vault.secrets().define("azure-documentdb-uri") -// .withValue(cosmosDBAccount.documentEndpoint()) -// .create(); -// -// vault.secrets().define("azure-documentdb-key") -// .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) -// .create(); -// -// vault.secrets().define("azure-documentdb-database") -// .withValue("tododb") -// .create(); -// -//// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.uri", cosmosDBAccount.documentEndpoint()).build()); -//// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.key", cosmosDBAccount.listKeys().primaryMasterKey()).build()); -//// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.database", "tododb").build()); -// -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// long t1 = System.currentTimeMillis(); -// -// Registry azureRegistry = azure.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .create(); -// -// long t2 = System.currentTimeMillis(); -// System.out.println("Created Azure Container Registry: (took " + ((t2 - t1) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// String imageName = "tomcat:7.0-slim"; -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/todoapp"; -// dockerClient.pullImageCmd(imageName) -// .withAuthConfig(new AuthConfig()) // anonymous -// .exec(new PullImageResultCallback()) -// .awaitCompletion(); -// -// String imageId = dockerClient.inspectImageCmd(imageName).exec().getId(); -// dockerClient.tagImageCmd(imageId, privateRepoUrl, "latest").exec(); -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .exec(new PushImageResultCallback()).awaitCompletion(); -// -// //============================================================ -// // Create a web app with a new app service plan -// -// System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); -// -// WebApp app1 = azure.webApps() -// .define(appName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withNewLinuxPlan(PricingTier.STANDARD_S1) -// .withPrivateRegistryImage(privateRepoUrl, azureRegistry.loginServerUrl()) -// .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) -// .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) -// .withAppSetting("AZURE_KEYVAULT_CLIENT_ID", servicePrincipal.applicationId()) -// .withAppSetting("AZURE_KEYVAULT_CLIENT_KEY", password) -// .create(); -// -// System.out.println("Created web app " + app1.name()); -// Utils.print(app1); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azure.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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// runSample(azureResourceManager, ""); -// -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +package com.azure.resourcemanager.appservice.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.authorization.models.ServicePrincipal; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; +import com.azure.resourcemanager.keyvault.models.SecretPermissions; +import com.azure.resourcemanager.keyvault.models.Vault; +import com.azure.resourcemanager.samples.DockerUtils; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.core.command.PushImageResultCallback; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; + +/** + * Azure App Service basic sample for managing web apps. + * - Create a Cosmos DB with credentials stored in a Key Vault + * - Create a web app which interacts with the Cosmos DB by first + * reading the secrets from the Key Vault. + * + * The source code of the web app is located at + * https://github.com/Microsoft/todo-app-java-on-azure/tree/keyvault-secrets + */ +public final class ManageLinuxWebAppCosmosDbByMsi { + + /** + * Main function which runs the actual sample. + * @param azure instance of the azure client + * @param clientId the client ID + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azure, String clientId) throws IOException, InterruptedException { + // New resources + final Region region = Region.US_WEST; + final String acrName = Utils.randomResourceName(azure, "acr", 20); + final String appName = Utils.randomResourceName(azure, "webapp1-", 20); + final String password = Utils.password(); + final String rgName = Utils.randomResourceName(azure, "rg1NEMV_", 24); + final String vaultName = Utils.randomResourceName(azure, "vault", 20); + final String cosmosName = Utils.randomResourceName(azure, "cosmosdb", 20); + + String servicePrincipalClientId = clientId; // replace with a real service principal client id + + try { + //============================================================ + // Create a CosmosDB + + System.out.println("Creating a CosmosDB..."); + CosmosDBAccount cosmosDBAccount = azure.cosmosDBAccounts().define(cosmosName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDataModelSql() + .withStrongConsistency() + .create(); + + System.out.println("Created CosmosDB"); + Utils.print(cosmosDBAccount); + + //============================================================ + // Create a service principal + + ServicePrincipal servicePrincipal = azure.accessManagement().servicePrincipals() + .define(appName) + .withNewApplication("http://" + appName + ".azurewebsites.net") + .definePasswordCredential("password") + .withPasswordValue(password) + .attach() + .create(); + + //============================================================= + // If service principal client id and secret are not set via the local variables, attempt to read the service + // principal client id and secret from a secondary ".azureauth" file set through an environment variable. + // + // If the environment variable was not set then reuse the main service principal set for running this sample. + + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { + servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { + String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); + + if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); + } + + servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); + } + } + + //============================================================ + // Create a key vault + + Vault vault = azure.vaults() + .define(vaultName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forServicePrincipal(servicePrincipalClientId) + .allowSecretAllPermissions() + .attach() + .defineAccessPolicy() + .forServicePrincipal(servicePrincipal) + .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) + .attach() + .create(); + +// SdkContext.sleep(10000); + + //============================================================ + // Store Cosmos DB credentials in Key Vault + + vault.secrets().define("azure-documentdb-uri") + .withValue(cosmosDBAccount.documentEndpoint()) + .create(); + + vault.secrets().define("azure-documentdb-key") + .withValue(cosmosDBAccount.listKeys().primaryMasterKey()) + .create(); + + vault.secrets().define("azure-documentdb-database") + .withValue("tododb") + .create(); + +// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.uri", cosmosDBAccount.documentEndpoint()).build()); +// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.key", cosmosDBAccount.listKeys().primaryMasterKey()).build()); +// client.setSecret(new SetSecretRequest.Builder(vault.vaultUri(), "azure.documentdb.database", "tododb").build()); + + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + long t1 = System.currentTimeMillis(); + + Registry azureRegistry = azure.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); + + long t2 = System.currentTimeMillis(); + System.out.println("Created Azure Container Registry: (took " + ((t2 - t1) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azure, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + String imageName = "tomcat:7.0-slim"; + String privateRepoUrl = azureRegistry.loginServerUrl() + "/todoapp"; + dockerClient.pullImageCmd(imageName) + .withAuthConfig(new AuthConfig()) // anonymous + .exec(new PullImageResultCallback()) + .awaitCompletion(); + + String imageId = dockerClient.inspectImageCmd(imageName).exec().getId(); + dockerClient.tagImageCmd(imageId, privateRepoUrl, "latest").exec(); + + dockerClient.pushImageCmd(privateRepoUrl) + .exec(new PushImageResultCallback()).awaitCompletion(); + + //============================================================ + // Create a web app with a new app service plan + + System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); + + WebApp app1 = azure.webApps() + .define(appName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withPrivateRegistryImage(privateRepoUrl, azureRegistry.loginServerUrl()) + .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withAppSetting("AZURE_KEYVAULT_URI", vault.vaultUri()) + .withAppSetting("AZURE_KEYVAULT_CLIENT_ID", servicePrincipal.applicationId()) + .withAppSetting("AZURE_KEYVAULT_CLIENT_KEY", password) + .create(); + + System.out.println("Created web app " + app1.name()); + Utils.print(app1); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azure.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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + runSample(azureResourceManager, ""); + + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java index ec516ba797e2..1594bc31cf8c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppSqlConnection.java @@ -1,161 +1,161 @@ // 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.PricingTier; -//import com.azure.resourcemanager.appservice.models.RuntimeStack; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.core.http.policy.HttpLogDetailLevel; -// -//import java.io.IOException; -// -///** -// * Azure App Service basic sample for managing web apps. -// * - Create a SQL database in a new SQL server -// * - Create a web app deployed with Project Nami (WordPress's SQL Server variant) -// * that contains the app settings to connect to the SQL database -// * - Update the SQL server's firewall rules to allow the web app to access -// * - Clean up -// */ -//public final class ManageLinuxWebAppSqlConnection { -// -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// // New resources -// final String suffix = ".azurewebsites.net"; -// final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); -// final String appUrl = appName + suffix; -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); -// final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); -// final String admin = "jsdkadmin"; -// final String password = Utils.password(); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); -// -// try { -// -// -// //============================================================ -// // Create a sql server -// -// System.out.println("Creating SQL server " + sqlServerName + "..."); -// -// SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(admin) -// .withAdministratorPassword(password) -// .create(); -// -// System.out.println("Created SQL server " + server.name()); -// -// //============================================================ -// // Create a sql database for the web app to use -// -// System.out.println("Creating SQL database " + sqlDbName + "..."); -// -// SqlDatabase db = server.databases().define(sqlDbName).create(); -// -// System.out.println("Created SQL database " + db.name()); -// -// //============================================================ -// // Create a web app with a new app service plan -// -// System.out.println("Creating web app " + appName + "..."); -// -// WebApp app = azureResourceManager.webApps().define(appName) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withNewLinuxPlan(PricingTier.STANDARD_S1) -// .withBuiltInImage(RuntimeStack.PHP_7_2) -// .defineSourceControl() -// .withPublicGitRepository("https://github.com/ProjectNami/projectnami") -// .withBranch("master") -// .attach() -// .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) -// .withAppSetting("ProjectNami.DBName", db.name()) -// .withAppSetting("ProjectNami.DBUser", admin) -// .withAppSetting("ProjectNami.DBPass", password) -// .create(); -// -// System.out.println("Created web app " + app.name()); -// Utils.print(app); -// -// //============================================================ -// // Allow web app to access the SQL server -// -// System.out.println("Allowing web app " + appName + " to access SQL server..."); -// -// SqlServer.Update update = server.update(); -// for (String ip : app.outboundIPAddresses()) { -// update = update.defineFirewallRule("filewallRule1").withIpAddress(ip).attach(); -// } -// server = update.apply(); -// -// System.out.println("Firewall rules added for web app " + appName); -// Utils.print(server); -// -// System.out.println("Your WordPress app is ready."); -// System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); -// System.in.read(); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +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.PricingTier; +import com.azure.resourcemanager.appservice.models.RuntimeStack; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.core.http.policy.HttpLogDetailLevel; + +import java.io.IOException; + +/** + * Azure App Service basic sample for managing web apps. + * - Create a SQL database in a new SQL server + * - Create a web app deployed with Project Nami (WordPress's SQL Server variant) + * that contains the app settings to connect to the SQL database + * - Update the SQL server's firewall rules to allow the web app to access + * - Clean up + */ +public final class ManageLinuxWebAppSqlConnection { + + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + // New resources + final String suffix = ".azurewebsites.net"; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String appUrl = appName + suffix; + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); + final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); + final String admin = "jsdkadmin"; + final String password = Utils.password(); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + + try { + + + //============================================================ + // Create a sql server + + System.out.println("Creating SQL server " + sqlServerName + "..."); + + SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(admin) + .withAdministratorPassword(password) + .create(); + + System.out.println("Created SQL server " + server.name()); + + //============================================================ + // Create a sql database for the web app to use + + System.out.println("Creating SQL database " + sqlDbName + "..."); + + SqlDatabase db = server.databases().define(sqlDbName).create(); + + System.out.println("Created SQL database " + db.name()); + + //============================================================ + // Create a web app with a new app service plan + + System.out.println("Creating web app " + appName + "..."); + + WebApp app = azureResourceManager.webApps().define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withBuiltInImage(RuntimeStack.PHP_7_2) + .defineSourceControl() + .withPublicGitRepository("https://github.com/ProjectNami/projectnami") + .withBranch("master") + .attach() + .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) + .withAppSetting("ProjectNami.DBName", db.name()) + .withAppSetting("ProjectNami.DBUser", admin) + .withAppSetting("ProjectNami.DBPass", password) + .create(); + + System.out.println("Created web app " + app.name()); + Utils.print(app); + + //============================================================ + // Allow web app to access the SQL server + + System.out.println("Allowing web app " + appName + " to access SQL server..."); + + SqlServer.Update update = server.update(); + for (String ip : app.outboundIPAddresses()) { + update = update.defineFirewallRule("filewallRule1").withIpAddress(ip).attach(); + } + server = update.apply(); + + System.out.println("Firewall rules added for web app " + appName); + Utils.print(server); + + System.out.println("Your WordPress app is ready."); + System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); + System.in.read(); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java index 3da37a09d2d1..503f313a6e43 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithContainerRegistry.java @@ -1,203 +1,203 @@ // 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.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//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.DockerUtils; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.CreateContainerResponse; -//import com.github.dockerjava.api.command.PullImageResultCallback; -//import com.github.dockerjava.api.exception.NotFoundException; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.api.model.Image; -//import com.github.dockerjava.core.command.PushImageResultCallback; -// -//import java.io.IOException; -//import java.time.Duration; -//import java.util.Date; -//import java.util.List; -// -///** -// * Azure App Service sample for deploying from an Azure Container Registry. -// * - Create an Azure Container Registry to be used for holding the Docker images -// * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine -// * to be used for this sample -// * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry -// * - Pull a test image from the public Docker repo (tomcat:8-jre8) to be used as a sample for pushing/pulling -// * to/from an Azure Container Registry -// * - Deploys to a new web app from the Tomcat image -// */ -//public class ManageLinuxWebAppWithContainerRegistry { -// -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); -// final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); -// final String appName = Utils.randomResourceName(azureResourceManager, "webapp", 20); -// final String appUrl = appName + ".azurewebsites.net"; -// final Region region = Region.US_EAST; -// final String dockerImageName = "tomcat"; -// final String dockerImageTag = "8-jre8"; -// final String dockerContainerName = "tomcat-private"; -// -// try { -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// Date t1 = new Date(); -// -// Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .create(); -// -// Date t2 = new Date(); -// System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// //============================================================= -// // Pull a temp image from public Docker repo and create a temporary container from that image -// // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR -// -// dockerClient.pullImageCmd(dockerImageName) -// .withTag(dockerImageTag) -// .withAuthConfig(new AuthConfig()) -// .exec(new PullImageResultCallback()) -// .awaitCompletion(); -// System.out.println("List local Docker images:"); -// List images = dockerClient.listImagesCmd().withShowAll(true).exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// -// CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) -// .withName(dockerContainerName) -// .exec(); -// -// //============================================================= -// // Commit the new container -// -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; -// dockerClient.commitCmd(dockerContainerInstance.getId()) -// .withRepository(privateRepoUrl) -// .withTag("latest").exec(); -// -// // We can now remove the temporary container instance -// dockerClient.removeContainerCmd(dockerContainerInstance.getId()) -// .withForce(true) -// .exec(); -// -// //============================================================= -// // Push the new Docker image to the Azure Container Registry -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PushImageResultCallback()).awaitSuccess(); -// -// // Remove the temp image from the local Docker host -// try { -// dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); -// } catch (NotFoundException e) { -// // just ignore if not exist -// } -// -// //============================================================ -// // Create a web app with a new app service plan -// -// System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); -// -// WebApp app = azureResourceManager.webApps().define(appName) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withNewLinuxPlan(PricingTier.STANDARD_S1) -// .withPrivateRegistryImage(privateRepoUrl + ":latest", "http://" + azureRegistry.loginServerUrl()) -// .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) -// .withAppSetting("PORT", "8080") -// .create(); -// -// System.out.println("Created web app " + app.name()); -// Utils.print(app); -// -// // warm up -// System.out.println("Warming up " + appUrl + "..."); -// Utils.sendGetRequest("http://" + appUrl); -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// System.out.println("CURLing " + appUrl + "..."); -// System.out.println(Utils.sendGetRequest("http://" + appUrl)); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +package com.azure.resourcemanager.appservice.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +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.DockerUtils; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.core.command.PushImageResultCallback; + +import java.io.IOException; +import java.time.Duration; +import java.util.Date; +import java.util.List; + +/** + * Azure App Service sample for deploying from an Azure Container Registry. + * - Create an Azure Container Registry to be used for holding the Docker images + * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine + * to be used for this sample + * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry + * - Pull a test image from the public Docker repo (tomcat:8-jre8) to be used as a sample for pushing/pulling + * to/from an Azure Container Registry + * - Deploys to a new web app from the Tomcat image + */ +public class ManageLinuxWebAppWithContainerRegistry { + + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); + final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); + final String appName = Utils.randomResourceName(azureResourceManager, "webapp", 20); + final String appUrl = appName + ".azurewebsites.net"; + final Region region = Region.US_EAST; + final String dockerImageName = "tomcat"; + final String dockerImageTag = "8-jre8"; + final String dockerContainerName = "tomcat-private"; + + try { + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + Date t1 = new Date(); + + Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); + + Date t2 = new Date(); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + //============================================================= + // Pull a temp image from public Docker repo and create a temporary container from that image + // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR + + dockerClient.pullImageCmd(dockerImageName) + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) + .exec(new PullImageResultCallback()) + .awaitCompletion(); + System.out.println("List local Docker images:"); + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + + CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .exec(); + + //============================================================= + // Commit the new container + + String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; + dockerClient.commitCmd(dockerContainerInstance.getId()) + .withRepository(privateRepoUrl) + .withTag("latest").exec(); + + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()) + .withForce(true) + .exec(); + + //============================================================= + // Push the new Docker image to the Azure Container Registry + + dockerClient.pushImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PushImageResultCallback()).awaitSuccess(); + + // Remove the temp image from the local Docker host + try { + dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + + //============================================================ + // Create a web app with a new app service plan + + System.out.println("Creating web app " + appName + " in resource group " + rgName + "..."); + + WebApp app = azureResourceManager.webApps().define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewLinuxPlan(PricingTier.STANDARD_S1) + .withPrivateRegistryImage(privateRepoUrl + ":latest", "http://" + azureRegistry.loginServerUrl()) + .withCredentials(acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withAppSetting("PORT", "8080") + .create(); + + System.out.println("Created web app " + app.name()); + Utils.print(app); + + // warm up + System.out.println("Warming up " + appUrl + "..."); + Utils.sendGetRequest("http://" + appUrl); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + System.out.println("CURLing " + appUrl + "..."); + System.out.println(Utils.sendGetRequest("http://" + appUrl)); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java index d6b5ecc9b817..5e55edc6db9a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java @@ -1,296 +1,296 @@ // 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.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.AppServiceDomain; -//import com.azure.resourcemanager.appservice.models.AppServicePlan; -//import com.azure.resourcemanager.appservice.models.OperatingSystem; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.RuntimeStack; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -//import com.azure.core.management.Region; -// -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; -//import com.azure.resourcemanager.trafficmanager.models.TrafficRoutingMethod; -// -//import java.io.File; -//import java.io.IOException; -// -///** -// * Azure App Service sample for managing web apps. -// * - Create a domain -// * - Create a self-signed certificate for the domain -// * - Create 3 app service plans in 3 different regions -// * - Create 5 web apps under the 3 plans, bound to the domain and the certificate -// * - Create a traffic manager in front of the web apps -// * - Scale up the app service plans to twice the capacity -// */ -//public final class ManageLinuxWebAppWithTrafficManager { -// private static String rgName; -// -// private static final String CERT_PASSWORD = "StrongPass!12"; -// -// private static AzureResourceManager azureResourceManager; -// private static AppServiceDomain domain; -// private static String pfxPath; -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); -// -// if (ManageLinuxWebAppWithTrafficManager.azureResourceManager == null) { -// ManageLinuxWebAppWithTrafficManager.azureResourceManager = azureResourceManager; -// } -// -// // New resources -// 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 app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); -// final String app5Name = Utils.randomResourceName(azureResourceManager, "webapp5-", 20); -// final String plan1Name = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); -// final String plan2Name = Utils.randomResourceName(azureResourceManager, "jplan2_", 15); -// final String plan3Name = Utils.randomResourceName(azureResourceManager, "jplan3_", 15); -// final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; -// final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); -// -// try { -// -// //============================================================ -// // Purchase a domain (will be canceled for a full refund) -// -// System.out.println("Purchasing a domain " + domainName + "..."); -// -// azureResourceManager.resourceGroups().define(rgName) -// .withRegion(Region.US_WEST) -// .create(); -// -// domain = azureResourceManager.appServiceDomains().define(domainName) -// .withExistingResourceGroup(rgName) -// .defineRegistrantContact() -// .withFirstName("Jon") -// .withLastName("Doe") -// .withEmail("jondoe@contoso.com") -// .withAddressLine1("123 4th Ave") -// .withCity("Redmond") -// .withStateOrProvince("WA") -// .withCountry(CountryIsoCode.UNITED_STATES) -// .withPostalCode("98052") -// .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) -// .withPhoneNumber("4258828080") -// .attach() -// .withDomainPrivacyEnabled(true) -// .withAutoRenewEnabled(false) -// .create(); -// System.out.println("Purchased domain " + domain.name()); -// Utils.print(domain); -// -// //============================================================ -// // Create a self-singed SSL certificate -// -// pfxPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; -// String cerPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; -// -// System.out.println("Creating a self-signed certificate " + pfxPath + "..."); -// -// Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); -// -// //============================================================ -// // Create 3 app service plans in 3 regions -// -// System.out.println("Creating app service plan " + plan1Name + " in US West..."); -// -// AppServicePlan plan1 = createAppServicePlan(plan1Name, Region.US_WEST); -// -// System.out.println("Created app service plan " + plan1.name()); -// Utils.print(plan1); -// -// System.out.println("Creating app service plan " + plan2Name + " in Europe West..."); -// -// AppServicePlan plan2 = createAppServicePlan(plan2Name, Region.EUROPE_WEST); -// -// System.out.println("Created app service plan " + plan2.name()); -// Utils.print(plan1); -// -// System.out.println("Creating app service plan " + plan3Name + " in Asia East..."); -// -// AppServicePlan plan3 = createAppServicePlan(plan3Name, Region.ASIA_SOUTHEAST); -// -// System.out.println("Created app service plan " + plan2.name()); -// Utils.print(plan1); -// -// //============================================================ -// // Create 5 web apps under these 3 app service plans -// -// System.out.println("Creating web app " + app1Name + "..."); -// -// WebApp app1 = createWebApp(app1Name, plan1); -// -// System.out.println("Created web app " + app1.name()); -// Utils.print(app1); -// -// System.out.println("Creating another web app " + app2Name + "..."); -// WebApp app2 = createWebApp(app2Name, plan2); -// -// System.out.println("Created web app " + app2.name()); -// Utils.print(app2); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app3 = createWebApp(app3Name, plan3); -// -// System.out.println("Created web app " + app3.name()); -// Utils.print(app3); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app4 = createWebApp(app4Name, plan1); -// -// System.out.println("Created web app " + app4.name()); -// Utils.print(app4); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app5 = createWebApp(app5Name, plan1); -// -// System.out.println("Created web app " + app5.name()); -// Utils.print(app5); -// -// //============================================================ -// // Create a traffic manager -// -// System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); -// -// TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) -// .withExistingResourceGroup(rgName) -// .withLeafDomainLabel(tmName) -// .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) -// .defineAzureTargetEndpoint("endpoint1") -// .toResourceId(app1.id()) -// .withRoutingPriority(1) -// .attach() -// .defineAzureTargetEndpoint("endpoint2") -// .toResourceId(app2.id()) -// .withRoutingPriority(2) -// .attach() -// .defineAzureTargetEndpoint("endpoint3") -// .toResourceId(app3.id()) -// .withRoutingPriority(3) -// .attach() -// .create(); -// -// System.out.println("Created traffic manager " + trafficManager.name()); -// Utils.print(trafficManager); -// -// //============================================================ -// // Scale up the app service plans -// -// System.out.println("Scaling up app service plan " + plan1Name + "..."); -// -// plan1.update() -// .withCapacity(plan1.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan1Name); -// Utils.print(plan1); -// -// System.out.println("Scaling up app service plan " + plan2Name + "..."); -// -// plan2.update() -// .withCapacity(plan2.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan2Name); -// Utils.print(plan2); -// -// System.out.println("Scaling up app service plan " + plan3Name + "..."); -// -// plan3.update() -// .withCapacity(plan3.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan3Name); -// Utils.print(plan3); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// private static AppServicePlan createAppServicePlan(String name, Region region) { -// return azureResourceManager.appServicePlans().define(name) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .withPricingTier(PricingTier.STANDARD_S2) -// .withOperatingSystem(OperatingSystem.LINUX) -// .create(); -// } -// -// private static final String WEB_APP_PACKAGE_URL = -// "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/helloworld.zip"; -// -// private static WebApp createWebApp(String name, AppServicePlan plan) { -// return azureResourceManager.webApps().define(name) -// .withExistingLinuxPlan(plan) -// .withExistingResourceGroup(rgName) -// .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) -// .withManagedHostnameBindings(domain, name) -// .defineSslBinding() -// .forHostname(name + "." + domain.name()) -// .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) -// .withSniBasedSsl() -// .attach() -// .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", WEB_APP_PACKAGE_URL) -// .create(); -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// // -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +package com.azure.resourcemanager.appservice.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.appservice.models.AppServicePlan; +import com.azure.resourcemanager.appservice.models.OperatingSystem; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.RuntimeStack; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; +import com.azure.core.management.Region; + +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; +import com.azure.resourcemanager.trafficmanager.models.TrafficRoutingMethod; + +import java.io.File; +import java.io.IOException; + +/** + * Azure App Service sample for managing web apps. + * - Create a domain + * - Create a self-signed certificate for the domain + * - Create 3 app service plans in 3 different regions + * - Create 5 web apps under the 3 plans, bound to the domain and the certificate + * - Create a traffic manager in front of the web apps + * - Scale up the app service plans to twice the capacity + */ +public final class ManageLinuxWebAppWithTrafficManager { + private static String rgName; + + private static final String CERT_PASSWORD = "StrongPass!12"; + + private static AzureResourceManager azureResourceManager; + private static AppServiceDomain domain; + private static String pfxPath; + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + + if (ManageLinuxWebAppWithTrafficManager.azureResourceManager == null) { + ManageLinuxWebAppWithTrafficManager.azureResourceManager = azureResourceManager; + } + + // New resources + 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 app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); + final String app5Name = Utils.randomResourceName(azureResourceManager, "webapp5-", 20); + final String plan1Name = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); + final String plan2Name = Utils.randomResourceName(azureResourceManager, "jplan2_", 15); + final String plan3Name = Utils.randomResourceName(azureResourceManager, "jplan3_", 15); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); + + try { + + //============================================================ + // Purchase a domain (will be canceled for a full refund) + + System.out.println("Purchasing a domain " + domainName + "..."); + + azureResourceManager.resourceGroups().define(rgName) + .withRegion(Region.US_WEST) + .create(); + + domain = azureResourceManager.appServiceDomains().define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); + System.out.println("Purchased domain " + domain.name()); + Utils.print(domain); + + //============================================================ + // Create a self-singed SSL certificate + + pfxPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath = ManageLinuxWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + + System.out.println("Creating a self-signed certificate " + pfxPath + "..."); + + Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); + + //============================================================ + // Create 3 app service plans in 3 regions + + System.out.println("Creating app service plan " + plan1Name + " in US West..."); + + AppServicePlan plan1 = createAppServicePlan(plan1Name, Region.US_WEST); + + System.out.println("Created app service plan " + plan1.name()); + Utils.print(plan1); + + System.out.println("Creating app service plan " + plan2Name + " in Europe West..."); + + AppServicePlan plan2 = createAppServicePlan(plan2Name, Region.EUROPE_WEST); + + System.out.println("Created app service plan " + plan2.name()); + Utils.print(plan1); + + System.out.println("Creating app service plan " + plan3Name + " in Asia East..."); + + AppServicePlan plan3 = createAppServicePlan(plan3Name, Region.ASIA_SOUTHEAST); + + System.out.println("Created app service plan " + plan2.name()); + Utils.print(plan1); + + //============================================================ + // Create 5 web apps under these 3 app service plans + + System.out.println("Creating web app " + app1Name + "..."); + + WebApp app1 = createWebApp(app1Name, plan1); + + System.out.println("Created web app " + app1.name()); + Utils.print(app1); + + System.out.println("Creating another web app " + app2Name + "..."); + WebApp app2 = createWebApp(app2Name, plan2); + + System.out.println("Created web app " + app2.name()); + Utils.print(app2); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app3 = createWebApp(app3Name, plan3); + + System.out.println("Created web app " + app3.name()); + Utils.print(app3); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app4 = createWebApp(app4Name, plan1); + + System.out.println("Created web app " + app4.name()); + Utils.print(app4); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app5 = createWebApp(app5Name, plan1); + + System.out.println("Created web app " + app5.name()); + Utils.print(app5); + + //============================================================ + // Create a traffic manager + + System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); + + TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(tmName) + .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) + .defineAzureTargetEndpoint("endpoint1") + .toResourceId(app1.id()) + .withRoutingPriority(1) + .attach() + .defineAzureTargetEndpoint("endpoint2") + .toResourceId(app2.id()) + .withRoutingPriority(2) + .attach() + .defineAzureTargetEndpoint("endpoint3") + .toResourceId(app3.id()) + .withRoutingPriority(3) + .attach() + .create(); + + System.out.println("Created traffic manager " + trafficManager.name()); + Utils.print(trafficManager); + + //============================================================ + // Scale up the app service plans + + System.out.println("Scaling up app service plan " + plan1Name + "..."); + + plan1.update() + .withCapacity(plan1.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan1Name); + Utils.print(plan1); + + System.out.println("Scaling up app service plan " + plan2Name + "..."); + + plan2.update() + .withCapacity(plan2.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan2Name); + Utils.print(plan2); + + System.out.println("Scaling up app service plan " + plan3Name + "..."); + + plan3.update() + .withCapacity(plan3.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan3Name); + Utils.print(plan3); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + private static AppServicePlan createAppServicePlan(String name, Region region) { + return azureResourceManager.appServicePlans().define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.STANDARD_S2) + .withOperatingSystem(OperatingSystem.LINUX) + .create(); + } + + private static final String WEB_APP_PACKAGE_URL = + "https://raw.githubusercontent.com/Azure/azure-sdk-for-java/master/sdk/resourcemanager/azure-resourcemanager-samples/src/main/resources/helloworld.zip"; + + private static WebApp createWebApp(String name, AppServicePlan plan) { + return azureResourceManager.webApps().define(name) + .withExistingLinuxPlan(plan) + .withExistingResourceGroup(rgName) + .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8) + .withManagedHostnameBindings(domain, name) + .defineSslBinding() + .forHostname(name + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) + .withSniBasedSsl() + .attach() + .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", WEB_APP_PACKAGE_URL) + .create(); + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + // + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java index 819c442e9f96..a1b0be7a913a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppSqlConnection.java @@ -1,158 +1,158 @@ // 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.PhpVersion; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.core.http.policy.HttpLogDetailLevel; -// -//import java.io.IOException; -// -///** -// * Azure App Service basic sample for managing web apps. -// * - Create a SQL database in a new SQL server -// * - Create a web app deployed with Project Nami (WordPress's SQL Server variant) -// * that contains the app settings to connect to the SQL database -// * - Update the SQL server's firewall rules to allow the web app to access -// * - Clean up -// */ -//public final class ManageWebAppSqlConnection { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// // New resources -// final String suffix = ".azurewebsites.net"; -// final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); -// final String appUrl = appName + suffix; -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); -// final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); -// final String admin = "jsdkadmin"; -// final String password = Utils.password(); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); -// -// try { -// -// -// //============================================================ -// // Create a sql server -// -// System.out.println("Creating SQL server " + sqlServerName + "..."); -// -// SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(admin) -// .withAdministratorPassword(password) -// .create(); -// -// System.out.println("Created SQL server " + server.name()); -// -// //============================================================ -// // Create a sql database for the web app to use -// -// System.out.println("Creating SQL database " + sqlDbName + "..."); -// -// SqlDatabase db = server.databases().define(sqlDbName).create(); -// -// System.out.println("Created SQL database " + db.name()); -// -// //============================================================ -// // Create a web app with a new app service plan -// -// System.out.println("Creating web app " + appName + "..."); -// -// WebApp app = azureResourceManager.webApps().define(appName) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withNewWindowsPlan(PricingTier.STANDARD_S1) -// .withPhpVersion(PhpVersion.PHP5_6) -// .defineSourceControl() -// .withPublicGitRepository("https://github.com/ProjectNami/projectnami") -// .withBranch("master") -// .attach() -// .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) -// .withAppSetting("ProjectNami.DBName", db.name()) -// .withAppSetting("ProjectNami.DBUser", admin) -// .withAppSetting("ProjectNami.DBPass", password) -// .create(); -// -// System.out.println("Created web app " + app.name()); -// Utils.print(app); -// -// //============================================================ -// // Allow web app to access the SQL server -// -// System.out.println("Allowing web app " + appName + " to access SQL server..."); -// -// SqlServer.Update update = server.update(); -// for (String ip : app.outboundIPAddresses()) { -// update = update.defineFirewallRule("filewallRule1").withIpAddress(ip).attach(); -// } -// server = update.apply(); -// -// System.out.println("Firewall rules added for web app " + appName); -// Utils.print(server); -// -// System.out.println("Your WordPress app is ready."); -// System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); -// System.in.read(); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +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.PhpVersion; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.core.http.policy.HttpLogDetailLevel; + +import java.io.IOException; + +/** + * Azure App Service basic sample for managing web apps. + * - Create a SQL database in a new SQL server + * - Create a web app deployed with Project Nami (WordPress's SQL Server variant) + * that contains the app settings to connect to the SQL database + * - Update the SQL server's firewall rules to allow the web app to access + * - Clean up + */ +public final class ManageWebAppSqlConnection { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + // New resources + final String suffix = ".azurewebsites.net"; + final String appName = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String appUrl = appName + suffix; + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "jsdkserver", 20); + final String sqlDbName = Utils.randomResourceName(azureResourceManager, "jsdkdb", 20); + final String admin = "jsdkadmin"; + final String password = Utils.password(); + final String rgName = Utils.randomResourceName(azureResourceManager, "rg1NEMV_", 24); + + try { + + + //============================================================ + // Create a sql server + + System.out.println("Creating SQL server " + sqlServerName + "..."); + + SqlServer server = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(admin) + .withAdministratorPassword(password) + .create(); + + System.out.println("Created SQL server " + server.name()); + + //============================================================ + // Create a sql database for the web app to use + + System.out.println("Creating SQL database " + sqlDbName + "..."); + + SqlDatabase db = server.databases().define(sqlDbName).create(); + + System.out.println("Created SQL database " + db.name()); + + //============================================================ + // Create a web app with a new app service plan + + System.out.println("Creating web app " + appName + "..."); + + WebApp app = azureResourceManager.webApps().define(appName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withPhpVersion(PhpVersion.PHP5_6) + .defineSourceControl() + .withPublicGitRepository("https://github.com/ProjectNami/projectnami") + .withBranch("master") + .attach() + .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName()) + .withAppSetting("ProjectNami.DBName", db.name()) + .withAppSetting("ProjectNami.DBUser", admin) + .withAppSetting("ProjectNami.DBPass", password) + .create(); + + System.out.println("Created web app " + app.name()); + Utils.print(app); + + //============================================================ + // Allow web app to access the SQL server + + System.out.println("Allowing web app " + appName + " to access SQL server..."); + + SqlServer.Update update = server.update(); + for (String ip : app.outboundIPAddresses()) { + update = update.defineFirewallRule("filewallRule1").withIpAddress(ip).attach(); + } + server = update.apply(); + + System.out.println("Firewall rules added for web app " + appName); + Utils.print(server); + + System.out.println("Your WordPress app is ready."); + System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit."); + System.in.read(); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java index 98980c2e2829..4874462cbc86 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java @@ -1,294 +1,294 @@ // 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.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.AppServiceDomain; -//import com.azure.resourcemanager.appservice.models.AppServicePlan; -//import com.azure.resourcemanager.appservice.models.OperatingSystem; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -//import com.azure.core.management.Region; -// -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; -//import com.azure.resourcemanager.trafficmanager.models.TrafficRoutingMethod; -// -//import java.io.File; -//import java.io.IOException; -// -///** -// * Azure App Service sample for managing web apps. -// * - Create a domain -// * - Create a self-signed certificate for the domain -// * - Create 3 app service plans in 3 different regions -// * - Create 5 web apps under the 3 plans, bound to the domain and the certificate -// * - Create a traffic manager in front of the web apps -// * - Scale up the app service plans to twice the capacity -// */ -//public final class ManageWebAppWithTrafficManager { -// private static String rgName; -// -// private static final String CERT_PASSWORD = "StrongPass!12"; -// -// private static AzureResourceManager azureResourceManager; -// private static AppServiceDomain domain; -// private static String pfxPath; -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); -// -// if (ManageWebAppWithTrafficManager.azureResourceManager == null) { -// ManageWebAppWithTrafficManager.azureResourceManager = azureResourceManager; -// } -// -// // New resources -// 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 app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); -// final String app5Name = Utils.randomResourceName(azureResourceManager, "webapp5-", 20); -// final String plan1Name = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); -// final String plan2Name = Utils.randomResourceName(azureResourceManager, "jplan2_", 15); -// final String plan3Name = Utils.randomResourceName(azureResourceManager, "jplan3_", 15); -// final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; -// final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); -// -// try { -// -// //============================================================ -// // Purchase a domain (will be canceled for a full refund) -// -// System.out.println("Purchasing a domain " + domainName + "..."); -// -// azureResourceManager.resourceGroups().define(rgName) -// .withRegion(Region.US_WEST) -// .create(); -// -// domain = azureResourceManager.appServiceDomains().define(domainName) -// .withExistingResourceGroup(rgName) -// .defineRegistrantContact() -// .withFirstName("Jon") -// .withLastName("Doe") -// .withEmail("jondoe@contoso.com") -// .withAddressLine1("123 4th Ave") -// .withCity("Redmond") -// .withStateOrProvince("WA") -// .withCountry(CountryIsoCode.UNITED_STATES) -// .withPostalCode("98052") -// .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) -// .withPhoneNumber("4258828080") -// .attach() -// .withDomainPrivacyEnabled(true) -// .withAutoRenewEnabled(false) -// .create(); -// System.out.println("Purchased domain " + domain.name()); -// Utils.print(domain); -// -// //============================================================ -// // Create a self-singed SSL certificate -// -// pfxPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; -// String cerPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; -// -// System.out.println("Creating a self-signed certificate " + pfxPath + "..."); -// -// Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); -// -// //============================================================ -// // Create 3 app service plans in 3 regions -// -// System.out.println("Creating app service plan " + plan1Name + " in US West..."); -// -// AppServicePlan plan1 = createAppServicePlan(plan1Name, Region.US_WEST); -// -// System.out.println("Created app service plan " + plan1.name()); -// Utils.print(plan1); -// -// System.out.println("Creating app service plan " + plan2Name + " in Europe West..."); -// -// AppServicePlan plan2 = createAppServicePlan(plan2Name, Region.EUROPE_WEST); -// -// System.out.println("Created app service plan " + plan2.name()); -// Utils.print(plan1); -// -// System.out.println("Creating app service plan " + plan3Name + " in Asia East..."); -// -// AppServicePlan plan3 = createAppServicePlan(plan3Name, Region.ASIA_EAST); -// -// System.out.println("Created app service plan " + plan2.name()); -// Utils.print(plan1); -// -// //============================================================ -// // Create 5 web apps under these 3 app service plans -// -// System.out.println("Creating web app " + app1Name + "..."); -// -// WebApp app1 = createWebApp(app1Name, plan1); -// -// System.out.println("Created web app " + app1.name()); -// Utils.print(app1); -// -// System.out.println("Creating another web app " + app2Name + "..."); -// WebApp app2 = createWebApp(app2Name, plan2); -// -// System.out.println("Created web app " + app2.name()); -// Utils.print(app2); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app3 = createWebApp(app3Name, plan3); -// -// System.out.println("Created web app " + app3.name()); -// Utils.print(app3); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app4 = createWebApp(app4Name, plan1); -// -// System.out.println("Created web app " + app4.name()); -// Utils.print(app4); -// -// System.out.println("Creating another web app " + app3Name + "..."); -// WebApp app5 = createWebApp(app5Name, plan1); -// -// System.out.println("Created web app " + app5.name()); -// Utils.print(app5); -// -// //============================================================ -// // Create a traffic manager -// -// System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); -// -// TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) -// .withExistingResourceGroup(rgName) -// .withLeafDomainLabel(tmName) -// .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) -// .defineAzureTargetEndpoint("endpoint1") -// .toResourceId(app1.id()) -// .withRoutingPriority(1) -// .attach() -// .defineAzureTargetEndpoint("endpoint2") -// .toResourceId(app2.id()) -// .withRoutingPriority(2) -// .attach() -// .defineAzureTargetEndpoint("endpoint3") -// .toResourceId(app3.id()) -// .withRoutingPriority(3) -// .attach() -// .create(); -// -// System.out.println("Created traffic manager " + trafficManager.name()); -// Utils.print(trafficManager); -// -// //============================================================ -// // Scale up the app service plans -// -// System.out.println("Scaling up app service plan " + plan1Name + "..."); -// -// plan1.update() -// .withCapacity(plan1.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan1Name); -// Utils.print(plan1); -// -// System.out.println("Scaling up app service plan " + plan2Name + "..."); -// -// plan2.update() -// .withCapacity(plan2.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan2Name); -// Utils.print(plan2); -// -// System.out.println("Scaling up app service plan " + plan3Name + "..."); -// -// plan3.update() -// .withCapacity(plan3.capacity() * 2) -// .apply(); -// -// System.out.println("Scaled up app service plan " + plan3Name); -// Utils.print(plan3); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// private static AppServicePlan createAppServicePlan(String name, Region region) { -// return azureResourceManager.appServicePlans().define(name) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .withPricingTier(PricingTier.STANDARD_S1) -// .withOperatingSystem(OperatingSystem.WINDOWS) -// .create(); -// } -// -// private static WebApp createWebApp(String name, AppServicePlan plan) { -// return azureResourceManager.webApps().define(name) -// .withExistingWindowsPlan(plan) -// .withExistingResourceGroup(rgName) -// .withManagedHostnameBindings(domain, name) -// .defineSslBinding() -// .forHostname(name + "." + domain.name()) -// .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) -// .withSniBasedSsl() -// .attach() -// .defineSourceControl() -// .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") -// .withBranch("master") -// .attach() -// .create(); -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// // -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} + +package com.azure.resourcemanager.appservice.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.appservice.models.AppServicePlan; +import com.azure.resourcemanager.appservice.models.OperatingSystem; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; +import com.azure.core.management.Region; + +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; +import com.azure.resourcemanager.trafficmanager.models.TrafficRoutingMethod; + +import java.io.File; +import java.io.IOException; + +/** + * Azure App Service sample for managing web apps. + * - Create a domain + * - Create a self-signed certificate for the domain + * - Create 3 app service plans in 3 different regions + * - Create 5 web apps under the 3 plans, bound to the domain and the certificate + * - Create a traffic manager in front of the web apps + * - Scale up the app service plans to twice the capacity + */ +public final class ManageWebAppWithTrafficManager { + private static String rgName; + + private static final String CERT_PASSWORD = "StrongPass!12"; + + private static AzureResourceManager azureResourceManager; + private static AppServiceDomain domain; + private static String pfxPath; + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + + if (ManageWebAppWithTrafficManager.azureResourceManager == null) { + ManageWebAppWithTrafficManager.azureResourceManager = azureResourceManager; + } + + // New resources + 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 app4Name = Utils.randomResourceName(azureResourceManager, "webapp4-", 20); + final String app5Name = Utils.randomResourceName(azureResourceManager, "webapp5-", 20); + final String plan1Name = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); + final String plan2Name = Utils.randomResourceName(azureResourceManager, "jplan2_", 15); + final String plan3Name = Utils.randomResourceName(azureResourceManager, "jplan3_", 15); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); + + try { + + //============================================================ + // Purchase a domain (will be canceled for a full refund) + + System.out.println("Purchasing a domain " + domainName + "..."); + + azureResourceManager.resourceGroups().define(rgName) + .withRegion(Region.US_WEST) + .create(); + + domain = azureResourceManager.appServiceDomains().define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); + System.out.println("Purchased domain " + domain.name()); + Utils.print(domain); + + //============================================================ + // Create a self-singed SSL certificate + + pfxPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath = ManageWebAppWithTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + + System.out.println("Creating a self-signed certificate " + pfxPath + "..."); + + Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); + + //============================================================ + // Create 3 app service plans in 3 regions + + System.out.println("Creating app service plan " + plan1Name + " in US West..."); + + AppServicePlan plan1 = createAppServicePlan(plan1Name, Region.US_WEST); + + System.out.println("Created app service plan " + plan1.name()); + Utils.print(plan1); + + System.out.println("Creating app service plan " + plan2Name + " in Europe West..."); + + AppServicePlan plan2 = createAppServicePlan(plan2Name, Region.EUROPE_WEST); + + System.out.println("Created app service plan " + plan2.name()); + Utils.print(plan1); + + System.out.println("Creating app service plan " + plan3Name + " in Asia East..."); + + AppServicePlan plan3 = createAppServicePlan(plan3Name, Region.ASIA_EAST); + + System.out.println("Created app service plan " + plan2.name()); + Utils.print(plan1); + + //============================================================ + // Create 5 web apps under these 3 app service plans + + System.out.println("Creating web app " + app1Name + "..."); + + WebApp app1 = createWebApp(app1Name, plan1); + + System.out.println("Created web app " + app1.name()); + Utils.print(app1); + + System.out.println("Creating another web app " + app2Name + "..."); + WebApp app2 = createWebApp(app2Name, plan2); + + System.out.println("Created web app " + app2.name()); + Utils.print(app2); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app3 = createWebApp(app3Name, plan3); + + System.out.println("Created web app " + app3.name()); + Utils.print(app3); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app4 = createWebApp(app4Name, plan1); + + System.out.println("Created web app " + app4.name()); + Utils.print(app4); + + System.out.println("Creating another web app " + app3Name + "..."); + WebApp app5 = createWebApp(app5Name, plan1); + + System.out.println("Created web app " + app5.name()); + Utils.print(app5); + + //============================================================ + // Create a traffic manager + + System.out.println("Creating a traffic manager " + tmName + " for the web apps..."); + + TrafficManagerProfile trafficManager = azureResourceManager.trafficManagerProfiles().define(tmName) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(tmName) + .withTrafficRoutingMethod(TrafficRoutingMethod.PRIORITY) + .defineAzureTargetEndpoint("endpoint1") + .toResourceId(app1.id()) + .withRoutingPriority(1) + .attach() + .defineAzureTargetEndpoint("endpoint2") + .toResourceId(app2.id()) + .withRoutingPriority(2) + .attach() + .defineAzureTargetEndpoint("endpoint3") + .toResourceId(app3.id()) + .withRoutingPriority(3) + .attach() + .create(); + + System.out.println("Created traffic manager " + trafficManager.name()); + Utils.print(trafficManager); + + //============================================================ + // Scale up the app service plans + + System.out.println("Scaling up app service plan " + plan1Name + "..."); + + plan1.update() + .withCapacity(plan1.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan1Name); + Utils.print(plan1); + + System.out.println("Scaling up app service plan " + plan2Name + "..."); + + plan2.update() + .withCapacity(plan2.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan2Name); + Utils.print(plan2); + + System.out.println("Scaling up app service plan " + plan3Name + "..."); + + plan3.update() + .withCapacity(plan3.capacity() * 2) + .apply(); + + System.out.println("Scaled up app service plan " + plan3Name); + Utils.print(plan3); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + private static AppServicePlan createAppServicePlan(String name, Region region) { + return azureResourceManager.appServicePlans().define(name) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.STANDARD_S1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); + } + + private static WebApp createWebApp(String name, AppServicePlan plan) { + return azureResourceManager.webApps().define(name) + .withExistingWindowsPlan(plan) + .withExistingResourceGroup(rgName) + .withManagedHostnameBindings(domain, name) + .defineSslBinding() + .forHostname(name + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), CERT_PASSWORD) + .withSniBasedSsl() + .attach() + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + // + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java index c70b8daf31cb..3cd42d6abcf5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdn.java @@ -1,184 +1,184 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.cdn.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.JavaVersion; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.appservice.models.WebContainer; -//import com.azure.resourcemanager.cdn.models.CdnEndpoint; -//import com.azure.resourcemanager.cdn.models.CdnProfile; -//import com.azure.resourcemanager.cdn.models.QueryStringCachingBehavior; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.resourcemanager.samples.Utils; -// -//import java.util.HashSet; -//import java.util.Set; -// -///** -// * Azure CDN sample for managing CDN profile. -// * - Create 8 web apps in 8 regions: -// * * 2 in US -// * * 2 in EU -// * * 2 in Southeast -// * * 1 in Brazil -// * * 1 in Japan -// * - Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps. -// * - Load some content (referenced by Web Apps) to the CDN endpoints. -// */ -//public class ManageCdn { -// -// private static final String SUFFIX = ".azurewebsites.net"; -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 20); -// final String cdnProfileName = Utils.randomResourceName(azureResourceManager, "cdnStandardProfile", 20); -// String[] appNames = new String[8]; -// -// try { -// // ============================================================ -// // Create a resource group for holding all the created resources -// azureResourceManager.resourceGroups().define(resourceGroupName) -// .withRegion(Region.US_CENTRAL) -// .create(); -// -// // ============================================================ -// // Create 8 websites -// for (int i = 0; i < 8; i++) { -// appNames[i] = Utils.randomResourceName(azureResourceManager, "webapp" + (i + 1) + "-", 20); -// } -// -// // 2 in US -// createWebApp(appNames[0], Region.US_WEST, azureResourceManager, resourceGroupName); -// createWebApp(appNames[1], Region.US_EAST, azureResourceManager, resourceGroupName); -// -// // 2 in EU -// createWebApp(appNames[2], Region.EUROPE_WEST, azureResourceManager, resourceGroupName); -// createWebApp(appNames[3], Region.EUROPE_NORTH, azureResourceManager, resourceGroupName); -// -// // 2 in Southeast -// createWebApp(appNames[4], Region.ASIA_SOUTHEAST, azureResourceManager, resourceGroupName); -// createWebApp(appNames[5], Region.AUSTRALIA_SOUTHEAST, azureResourceManager, resourceGroupName); -// -// // 1 in Brazil -// createWebApp(appNames[6], Region.BRAZIL_SOUTH, azureResourceManager, resourceGroupName); -// -// // 1 in Japan -// createWebApp(appNames[7], Region.JAPAN_WEST, azureResourceManager, resourceGroupName); -// -// // ======================================================================================= -// // Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps. -// System.out.println("Creating a CDN Profile"); -// -// // Create CDN Profile definition object that will let us do a for loop -// // to define all 8 endpoints and then parallelize their creation -// CdnProfile.DefinitionStages.WithStandardCreate profileDefinition = azureResourceManager.cdnProfiles().define(cdnProfileName) -// .withRegion(Region.US_CENTRAL) -// .withExistingResourceGroup(resourceGroupName) -// .withStandardVerizonSku(); -// -// // Define all the endpoints. We need to keep track of the last creatable stage -// // to be able to call create on the entire Cdn profile deployment definition. -// Creatable cdnCreatable = null; -// for (String webSite : appNames) { -// cdnCreatable = profileDefinition.defineNewEndpoint() -// .withOrigin(webSite + SUFFIX) -// .withHostHeader(webSite + SUFFIX) -// .withCompressionEnabled(true) -// .withContentTypeToCompress("application/javascript") -// .withQueryStringCachingBehavior(QueryStringCachingBehavior.IGNORE_QUERY_STRING) -// .attach(); -// } -// -// // Create profile and then all the defined endpoints in parallel -// CdnProfile profile = cdnCreatable.create(); -// -// // ======================================================================================= -// // Load some content (referenced by Web Apps) to the CDN endpoints. -// Set contentToLoad = new HashSet<>(); -// contentToLoad.add("/server.js"); -// contentToLoad.add("/pictures/microsoft_logo.png"); -// -// for (CdnEndpoint endpoint : profile.endpoints().values()) { -// endpoint.loadContent(contentToLoad); -// } -// return true; -// } finally { -// if (azureResourceManager.resourceGroups().getByName(resourceGroupName) != null) { -// System.out.println("Deleting Resource Group: " + resourceGroupName); -// azureResourceManager.resourceGroups().deleteByName(resourceGroupName); -// System.out.println("Deleted Resource Group: " + resourceGroupName); -// } else { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private static WebApp createWebApp(String appName, Region region, AzureResourceManager azureResourceManager, String resourceGroupName) { -// final String appUrl = appName + SUFFIX; -// -// System.out.println("Creating web app " + appName + " with master branch..."); -// -// WebApp app = azureResourceManager.webApps() -// .define(appName) -// .withRegion(region) -// .withExistingResourceGroup(resourceGroupName) -// .withNewWindowsPlan(PricingTier.STANDARD_S1) -// .withJavaVersion(JavaVersion.JAVA_8_NEWEST) -// .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) -// .defineSourceControl() -// .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") -// .withBranch("master") -// .attach() -// .create(); -// -// System.out.println("Created web app " + app.name()); -// Utils.print(app); -// -// System.out.println("CURLing " + appUrl + "..."); -// System.out.println(Utils.sendGetRequest("http://" + appUrl)); -// return app; -// } -//} +package com.azure.resourcemanager.cdn.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.JavaVersion; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.appservice.models.WebContainer; +import com.azure.resourcemanager.cdn.models.CdnEndpoint; +import com.azure.resourcemanager.cdn.models.CdnProfile; +import com.azure.resourcemanager.cdn.models.QueryStringCachingBehavior; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.resourcemanager.samples.Utils; + +import java.util.HashSet; +import java.util.Set; + +/** + * Azure CDN sample for managing CDN profile. + * - Create 8 web apps in 8 regions: + * * 2 in US + * * 2 in EU + * * 2 in Southeast + * * 1 in Brazil + * * 1 in Japan + * - Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps. + * - Load some content (referenced by Web Apps) to the CDN endpoints. + */ +public class ManageCdn { + + private static final String SUFFIX = ".azurewebsites.net"; + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String resourceGroupName = Utils.randomResourceName(azureResourceManager, "rg", 20); + final String cdnProfileName = Utils.randomResourceName(azureResourceManager, "cdnStandardProfile", 20); + String[] appNames = new String[8]; + + try { + // ============================================================ + // Create a resource group for holding all the created resources + azureResourceManager.resourceGroups().define(resourceGroupName) + .withRegion(Region.US_CENTRAL) + .create(); + + // ============================================================ + // Create 8 websites + for (int i = 0; i < 8; i++) { + appNames[i] = Utils.randomResourceName(azureResourceManager, "webapp" + (i + 1) + "-", 20); + } + + // 2 in US + createWebApp(appNames[0], Region.US_WEST, azureResourceManager, resourceGroupName); + createWebApp(appNames[1], Region.US_EAST, azureResourceManager, resourceGroupName); + + // 2 in EU + createWebApp(appNames[2], Region.EUROPE_WEST, azureResourceManager, resourceGroupName); + createWebApp(appNames[3], Region.EUROPE_NORTH, azureResourceManager, resourceGroupName); + + // 2 in Southeast + createWebApp(appNames[4], Region.ASIA_SOUTHEAST, azureResourceManager, resourceGroupName); + createWebApp(appNames[5], Region.AUSTRALIA_SOUTHEAST, azureResourceManager, resourceGroupName); + + // 1 in Brazil + createWebApp(appNames[6], Region.BRAZIL_SOUTH, azureResourceManager, resourceGroupName); + + // 1 in Japan + createWebApp(appNames[7], Region.JAPAN_WEST, azureResourceManager, resourceGroupName); + + // ======================================================================================= + // Create CDN profile using Standard Verizon SKU with endpoints in each region of Web apps. + System.out.println("Creating a CDN Profile"); + + // Create CDN Profile definition object that will let us do a for loop + // to define all 8 endpoints and then parallelize their creation + CdnProfile.DefinitionStages.WithStandardCreate profileDefinition = azureResourceManager.cdnProfiles().define(cdnProfileName) + .withRegion(Region.US_CENTRAL) + .withExistingResourceGroup(resourceGroupName) + .withStandardVerizonSku(); + + // Define all the endpoints. We need to keep track of the last creatable stage + // to be able to call create on the entire Cdn profile deployment definition. + Creatable cdnCreatable = null; + for (String webSite : appNames) { + cdnCreatable = profileDefinition.defineNewEndpoint() + .withOrigin(webSite + SUFFIX) + .withHostHeader(webSite + SUFFIX) + .withCompressionEnabled(true) + .withContentTypeToCompress("application/javascript") + .withQueryStringCachingBehavior(QueryStringCachingBehavior.IGNORE_QUERY_STRING) + .attach(); + } + + // Create profile and then all the defined endpoints in parallel + CdnProfile profile = cdnCreatable.create(); + + // ======================================================================================= + // Load some content (referenced by Web Apps) to the CDN endpoints. + Set contentToLoad = new HashSet<>(); + contentToLoad.add("/server.js"); + contentToLoad.add("/pictures/microsoft_logo.png"); + + for (CdnEndpoint endpoint : profile.endpoints().values()) { + endpoint.loadContent(contentToLoad); + } + return true; + } finally { + if (azureResourceManager.resourceGroups().getByName(resourceGroupName) != null) { + System.out.println("Deleting Resource Group: " + resourceGroupName); + azureResourceManager.resourceGroups().deleteByName(resourceGroupName); + System.out.println("Deleted Resource Group: " + resourceGroupName); + } else { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private static WebApp createWebApp(String appName, Region region, AzureResourceManager azureResourceManager, String resourceGroupName) { + final String appUrl = appName + SUFFIX; + + System.out.println("Creating web app " + appName + " with master branch..."); + + WebApp app = azureResourceManager.webApps() + .define(appName) + .withRegion(region) + .withExistingResourceGroup(resourceGroupName) + .withNewWindowsPlan(PricingTier.STANDARD_S1) + .withJavaVersion(JavaVersion.JAVA_8_NEWEST) + .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") + .withBranch("master") + .attach() + .create(); + + System.out.println("Created web app " + app.name()); + Utils.print(app); + + System.out.println("CURLing " + appUrl + "..."); + System.out.println(Utils.sendGetRequest("http://" + appUrl)); + return app; + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java index 08e7392119bc..93894d9ae154 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/cdn/samples/ManageCdnWithCustomDomain.java @@ -1,181 +1,181 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.cdn.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.AppServiceDomain; -//import com.azure.resourcemanager.cdn.models.CdnEndpoint; -//import com.azure.resourcemanager.cdn.models.CdnProfile; -//import com.azure.resourcemanager.dns.models.DnsZone; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -// -//import java.util.Map; -// -///** -// * Azure DNS sample for managing CDN profile. -// * - Purchase a domain -// * - Create root DNS zone -// * - Create CNAME DNS record -// * - Create CDN profile -// * - Create CDN endpoint -// * - Associate the custom domain with CDN endpoint -// */ -//public class ManageCdnWithCustomDomain { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); -// final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkcdn", 15) + ".com"; -// final String cdnProfileName = Utils.randomResourceName(azureResourceManager, "jsdkcdnp", 24); -// final String cdnEndpointName = Utils.randomResourceName(azureResourceManager, "jsdkcdne", 24); -// final Region region = Region.US_WEST; -// final String cnameRecordName = "sample"; -// String customDomain = cnameRecordName + "." + domainName; -// -// try { -// azureResourceManager.resourceGroups().define(rgName) -// .withRegion(region) -// .create(); -// -// //============================================================ -// // Purchase a domain -// -// System.out.println("Purchasing a domain " + domainName + "..."); -// AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) -// .withExistingResourceGroup(rgName) -// .defineRegistrantContact() -// .withFirstName("Jon") -// .withLastName("Doe") -// .withEmail("jondoe@contoso.com") -// .withAddressLine1("123 4th Ave") -// .withCity("Redmond") -// .withStateOrProvince("WA") -// .withCountry(CountryIsoCode.UNITED_STATES) -// .withPostalCode("98052") -// .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) -// .withPhoneNumber("4258828080") -// .attach() -// .withDomainPrivacyEnabled(true) -// .withAutoRenewEnabled(false) -// .create(); -// System.out.println("Purchased domain " + domain.name()); -// -// //============================================================ -// // Create root DNS zone -// -// System.out.println("Creating root DNS zone " + domainName + "..."); -// DnsZone dnsZone = azureResourceManager.dnsZones().define(domainName) -// .withExistingResourceGroup(rgName) -// .create(); -// System.out.println("Created root DNS zone " + dnsZone.name()); -// -// //============================================================ -// // Create CNAME DNS record -// -// System.out.println("Creating CNAME DNS record " + cnameRecordName + "..."); -// dnsZone.update() -// .withCNameRecordSet(cnameRecordName, cdnEndpointName + ".azureedge.net") -// .apply(); -// System.out.println("Created CNAME DNS record"); -// -// //============================================================ -// // Create CDN profile -// -// System.out.println("Creating CDN profile " + cdnProfileName + "..."); -// CdnProfile cdnProfile = azureResourceManager.cdnProfiles().define(cdnProfileName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .withStandardAkamaiSku() -// .create(); -// System.out.println("Created CDN profile " + cdnProfile.name()); -// -// //============================================================ -// // Create CDN endpoint -// -// System.out.println("Creating CDN endpoint " + cdnEndpointName + "..."); -// cdnProfile.update() -// .defineNewEndpoint(cdnEndpointName) -// .withOrigin("origin1", "www.someDomain.net") -// .withHttpAllowed(true) -// .withHttpsAllowed(true) -// .attach() -// .apply(); -// -// Map cdnEndpoints = cdnProfile.endpoints(); -// CdnEndpoint cdnEndpoint = cdnEndpoints.get(cdnEndpointName); -// System.out.println("Created CDN endpoint " + cdnEndpoint.name()); -// -// //============================================================ -// // Associate the custom domain with CDN endpoint -// -// System.out.println("Associating the custom domain with CDN endpoint " + cdnEndpoint.name()); -// cdnProfile.update() -// .updateEndpoint(cdnEndpointName) -// .withCustomDomain(customDomain) -// .parent() -// .apply(); -// cdnEndpoints = cdnProfile.endpoints(); -// cdnEndpoint = cdnEndpoints.get(cdnEndpointName); -// System.out.println("Associated the custom domain with CDN endpoint " + cdnEndpoint.name()); -// -// System.out.println("Listing custom domains associated with CDN endpoint " + cdnEndpoint.name() + "..."); -// for (String attachedDomain : cdnEndpoint.customDomains()) { -// System.out.println(attachedDomain); -// } -// System.out.println("Listed custom domains."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.cdn.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.cdn.models.CdnEndpoint; +import com.azure.resourcemanager.cdn.models.CdnProfile; +import com.azure.resourcemanager.dns.models.DnsZone; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; + +import java.util.Map; + +/** + * Azure DNS sample for managing CDN profile. + * - Purchase a domain + * - Create root DNS zone + * - Create CNAME DNS record + * - Create CDN profile + * - Create CDN endpoint + * - Associate the custom domain with CDN endpoint + */ +public class ManageCdnWithCustomDomain { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkcdn", 15) + ".com"; + final String cdnProfileName = Utils.randomResourceName(azureResourceManager, "jsdkcdnp", 24); + final String cdnEndpointName = Utils.randomResourceName(azureResourceManager, "jsdkcdne", 24); + final Region region = Region.US_WEST; + final String cnameRecordName = "sample"; + String customDomain = cnameRecordName + "." + domainName; + + try { + azureResourceManager.resourceGroups().define(rgName) + .withRegion(region) + .create(); + + //============================================================ + // Purchase a domain + + System.out.println("Purchasing a domain " + domainName + "..."); + AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); + System.out.println("Purchased domain " + domain.name()); + + //============================================================ + // Create root DNS zone + + System.out.println("Creating root DNS zone " + domainName + "..."); + DnsZone dnsZone = azureResourceManager.dnsZones().define(domainName) + .withExistingResourceGroup(rgName) + .create(); + System.out.println("Created root DNS zone " + dnsZone.name()); + + //============================================================ + // Create CNAME DNS record + + System.out.println("Creating CNAME DNS record " + cnameRecordName + "..."); + dnsZone.update() + .withCNameRecordSet(cnameRecordName, cdnEndpointName + ".azureedge.net") + .apply(); + System.out.println("Created CNAME DNS record"); + + //============================================================ + // Create CDN profile + + System.out.println("Creating CDN profile " + cdnProfileName + "..."); + CdnProfile cdnProfile = azureResourceManager.cdnProfiles().define(cdnProfileName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withStandardAkamaiSku() + .create(); + System.out.println("Created CDN profile " + cdnProfile.name()); + + //============================================================ + // Create CDN endpoint + + System.out.println("Creating CDN endpoint " + cdnEndpointName + "..."); + cdnProfile.update() + .defineNewEndpoint(cdnEndpointName) + .withOrigin("origin1", "www.someDomain.net") + .withHttpAllowed(true) + .withHttpsAllowed(true) + .attach() + .apply(); + + Map cdnEndpoints = cdnProfile.endpoints(); + CdnEndpoint cdnEndpoint = cdnEndpoints.get(cdnEndpointName); + System.out.println("Created CDN endpoint " + cdnEndpoint.name()); + + //============================================================ + // Associate the custom domain with CDN endpoint + + System.out.println("Associating the custom domain with CDN endpoint " + cdnEndpoint.name()); + cdnProfile.update() + .updateEndpoint(cdnEndpointName) + .withCustomDomain(customDomain) + .parent() + .apply(); + cdnEndpoints = cdnProfile.endpoints(); + cdnEndpoint = cdnEndpoints.get(cdnEndpointName); + System.out.println("Associated the custom domain with CDN endpoint " + cdnEndpoint.name()); + + System.out.println("Listing custom domains associated with CDN endpoint " + cdnEndpoint.name() + "..."); + for (String attachedDomain : cdnEndpoint.customDomains()) { + System.out.println(attachedDomain); + } + System.out.println("Listed custom domains."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java index ea3435a9f5be..579db3534dc7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithAzureFileShareMount.java @@ -1,151 +1,151 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerinstance.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//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.resourcemanager.storage.models.StorageAccount; -//import com.azure.storage.file.share.ShareClient; -//import com.azure.storage.file.share.ShareClientBuilder; -//import com.azure.storage.file.share.models.ShareFileItem; -// -//import java.time.Duration; -// -///** -// * Azure Container Instance sample for managing container instances with Azure File Share mount. -// * - Create an Azure container instance using Docker image "seanmckenna/aci-hellofiles" with a mount to a new file share -// * - Test that the container app can be reached via "curl" like HTTP GET calls -// * - Retrieve container log content -// */ -//public class ManageContainerInstanceWithAzureFileShareMount { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); -// final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); -// final String shareName = Utils.randomResourceName(azureResourceManager, "fileshare", 20); -// final String containerImageName = "seanmckenna/aci-hellofiles"; -// final String volumeMountName = "aci-helloshare"; -// -// try { -// -// //============================================================= -// // Create a container group with one container instance of default CPU core count and memory size -// // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously -// // as read/write shared container volume. -// -// ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .withNewAzureFileShareVolume(volumeMountName, shareName) -// .defineContainerInstance(aciName) -// .withImage(containerImageName) -// .withExternalTcpPort(80) -// .withVolumeMountSetting(volumeMountName, "/aci/logs/") -// .attach() -// .withDnsPrefix(aciName) -// .create(); -// -// Utils.print(containerGroup); -// -// //============================================================= -// // Check that the container instance is up and running -// -// // warm up -// System.out.println("Warming up " + containerGroup.ipAddress()); -// Utils.sendGetRequest("http://" + containerGroup.ipAddress()); -// ResourceManagerUtils.sleep(Duration.ofSeconds(30)); -// System.out.println("CURLing " + containerGroup.ipAddress()); -// System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); -// -// //============================================================= -// // Check the container instance logs -// -// String logContent = containerGroup.getLogContent(aciName); -// System.out.format("Logs for container instance: %s%n%s", aciName, logContent); -// -// //============================================================= -// // List the file share content -// -// String storageAccountName = containerGroup.volumes().get(volumeMountName).azureFile().storageAccountName(); -// StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); -// ShareClient shareClient = new ShareClientBuilder() -// .connectionString(ResourceManagerUtils.getStorageConnectionString( -// storageAccountName, -// storageAccount.getKeys().get(0).value(), -// azureResourceManager.containerGroups().manager().environment() -// )) -// .shareName(shareName) -// .buildClient(); -// -// Iterable shareContent = shareClient.getRootDirectoryClient().listFilesAndDirectories(); -// -// for (ShareFileItem item : shareContent) { -// System.out.format("Found shared file %s:%n", item.getName()); -// } -// -// //============================================================= -// // Remove the container group -// -// azureResourceManager.containerGroups().deleteById(containerGroup.id()); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerinstance.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +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.resourcemanager.storage.models.StorageAccount; +import com.azure.storage.file.share.ShareClient; +import com.azure.storage.file.share.ShareClientBuilder; +import com.azure.storage.file.share.models.ShareFileItem; + +import java.time.Duration; + +/** + * Azure Container Instance sample for managing container instances with Azure File Share mount. + * - Create an Azure container instance using Docker image "seanmckenna/aci-hellofiles" with a mount to a new file share + * - Test that the container app can be reached via "curl" like HTTP GET calls + * - Retrieve container log content + */ +public class ManageContainerInstanceWithAzureFileShareMount { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); + final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); + final String shareName = Utils.randomResourceName(azureResourceManager, "fileshare", 20); + final String containerImageName = "seanmckenna/aci-hellofiles"; + final String volumeMountName = "aci-helloshare"; + + try { + + //============================================================= + // Create a container group with one container instance of default CPU core count and memory size + // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously + // as read/write shared container volume. + + ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withNewAzureFileShareVolume(volumeMountName, shareName) + .defineContainerInstance(aciName) + .withImage(containerImageName) + .withExternalTcpPort(80) + .withVolumeMountSetting(volumeMountName, "/aci/logs/") + .attach() + .withDnsPrefix(aciName) + .create(); + + Utils.print(containerGroup); + + //============================================================= + // Check that the container instance is up and running + + // warm up + System.out.println("Warming up " + containerGroup.ipAddress()); + Utils.sendGetRequest("http://" + containerGroup.ipAddress()); + ResourceManagerUtils.sleep(Duration.ofSeconds(30)); + System.out.println("CURLing " + containerGroup.ipAddress()); + System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); + + //============================================================= + // Check the container instance logs + + String logContent = containerGroup.getLogContent(aciName); + System.out.format("Logs for container instance: %s%n%s", aciName, logContent); + + //============================================================= + // List the file share content + + String storageAccountName = containerGroup.volumes().get(volumeMountName).azureFile().storageAccountName(); + StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(rgName, storageAccountName); + ShareClient shareClient = new ShareClientBuilder() + .connectionString(ResourceManagerUtils.getStorageConnectionString( + storageAccountName, + storageAccount.getKeys().get(0).value(), + azureResourceManager.containerGroups().manager().environment() + )) + .shareName(shareName) + .buildClient(); + + Iterable shareContent = shareClient.getRootDirectoryClient().listFilesAndDirectories(); + + for (ShareFileItem item : shareContent) { + System.out.format("Found shared file %s:%n", item.getName()); + } + + //============================================================= + // Remove the container group + + azureResourceManager.containerGroups().deleteById(containerGroup.id()); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java index 66acda150649..5ee66d3c79b4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithManualAzureFileShareMountCreation.java @@ -1,167 +1,167 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerinstance.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//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.resourcemanager.storage.models.StorageAccount; -//import com.azure.resourcemanager.storage.models.StorageAccountKey; -//import com.azure.storage.file.share.ShareClient; -//import com.azure.storage.file.share.ShareClientBuilder; -//import com.azure.storage.file.share.models.ShareFileItem; -// -//import java.time.Duration; -// -///** -// * Azure Container Instance sample for managing container instances with Azure File Share mount. -// * - Create a storage account and an Azure file share resource -// * - Create an Azure container instance using Docker image "seanmckenna/aci-hellofiles" with a mount to the file share from above -// * - Test that the container app can be reached via "curl" like HTTP GET calls -// * - Retrieve container log content -// */ -//public class ManageContainerInstanceWithManualAzureFileShareMountCreation { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); -// final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); -// final String saName = Utils.randomResourceName(azureResourceManager, "sa", 20); -// final String shareName = Utils.randomResourceName(azureResourceManager, "fileshare", 20); -// final String containerImageName = "seanmckenna/aci-hellofiles"; -// final String volumeMountName = "aci-helloshare"; -// -// try { -// -// //============================================================= -// // Create a new storage account and an Azure file share resource -// -// StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .create(); -// -// StorageAccountKey storageAccountKey = storageAccount.getKeys().get(0); -// -// ShareClient shareClient = new ShareClientBuilder() -// .connectionString(ResourceManagerUtils.getStorageConnectionString( -// saName, -// storageAccountKey.value(), -// azureResourceManager.containerGroups().manager().environment() -// )) -// .shareName(shareName) -// .buildClient(); -// shareClient.create(); -// -// //============================================================= -// // Create a container group with one container instance of default CPU core count and memory size -// // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously -// // as read/write shared container volume. -// -// ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .defineVolume(volumeMountName) -// .withExistingReadWriteAzureFileShare(shareName) -// .withStorageAccountName(saName) -// .withStorageAccountKey(storageAccountKey.value()) -// .attach() -// .defineContainerInstance(aciName) -// .withImage(containerImageName) -// .withExternalTcpPort(80) -// .withVolumeMountSetting(volumeMountName, "/aci/logs/") -// .attach() -// .withDnsPrefix(aciName) -// .create(); -// -// Utils.print(containerGroup); -// -// //============================================================= -// // Check that the container instance is up and running -// -// // warm up -// System.out.println("Warming up " + containerGroup.ipAddress()); -// Utils.sendGetRequest("http://" + containerGroup.ipAddress()); -// ResourceManagerUtils.sleep(Duration.ofSeconds(15)); -// System.out.println("CURLing " + containerGroup.ipAddress()); -// System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); -// -// //============================================================= -// // Check the container instance logs -// -// String logContent = containerGroup.getLogContent(aciName); -// System.out.format("Logs for container instance: %s%n%s", aciName, logContent); -// -// //============================================================= -// // Remove the container group -// -// azureResourceManager.containerGroups().deleteById(containerGroup.id()); -// -// //============================================================= -// // List the file share content -// -// Iterable shareContent = shareClient.getRootDirectoryClient().listFilesAndDirectories(); -// -// for (ShareFileItem item : shareContent) { -// System.out.format("Found shared file %s:%n", item.getName()); -// } -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerinstance.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +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.resourcemanager.storage.models.StorageAccount; +import com.azure.resourcemanager.storage.models.StorageAccountKey; +import com.azure.storage.file.share.ShareClient; +import com.azure.storage.file.share.ShareClientBuilder; +import com.azure.storage.file.share.models.ShareFileItem; + +import java.time.Duration; + +/** + * Azure Container Instance sample for managing container instances with Azure File Share mount. + * - Create a storage account and an Azure file share resource + * - Create an Azure container instance using Docker image "seanmckenna/aci-hellofiles" with a mount to the file share from above + * - Test that the container app can be reached via "curl" like HTTP GET calls + * - Retrieve container log content + */ +public class ManageContainerInstanceWithManualAzureFileShareMountCreation { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); + final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); + final String saName = Utils.randomResourceName(azureResourceManager, "sa", 20); + final String shareName = Utils.randomResourceName(azureResourceManager, "fileshare", 20); + final String containerImageName = "seanmckenna/aci-hellofiles"; + final String volumeMountName = "aci-helloshare"; + + try { + + //============================================================= + // Create a new storage account and an Azure file share resource + + StorageAccount storageAccount = azureResourceManager.storageAccounts().define(saName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .create(); + + StorageAccountKey storageAccountKey = storageAccount.getKeys().get(0); + + ShareClient shareClient = new ShareClientBuilder() + .connectionString(ResourceManagerUtils.getStorageConnectionString( + saName, + storageAccountKey.value(), + azureResourceManager.containerGroups().manager().environment() + )) + .shareName(shareName) + .buildClient(); + shareClient.create(); + + //============================================================= + // Create a container group with one container instance of default CPU core count and memory size + // using public Docker image "seanmckenna/aci-hellofiles" which mounts the file share created previously + // as read/write shared container volume. + + ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .defineVolume(volumeMountName) + .withExistingReadWriteAzureFileShare(shareName) + .withStorageAccountName(saName) + .withStorageAccountKey(storageAccountKey.value()) + .attach() + .defineContainerInstance(aciName) + .withImage(containerImageName) + .withExternalTcpPort(80) + .withVolumeMountSetting(volumeMountName, "/aci/logs/") + .attach() + .withDnsPrefix(aciName) + .create(); + + Utils.print(containerGroup); + + //============================================================= + // Check that the container instance is up and running + + // warm up + System.out.println("Warming up " + containerGroup.ipAddress()); + Utils.sendGetRequest("http://" + containerGroup.ipAddress()); + ResourceManagerUtils.sleep(Duration.ofSeconds(15)); + System.out.println("CURLing " + containerGroup.ipAddress()); + System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); + + //============================================================= + // Check the container instance logs + + String logContent = containerGroup.getLogContent(aciName); + System.out.format("Logs for container instance: %s%n%s", aciName, logContent); + + //============================================================= + // Remove the container group + + azureResourceManager.containerGroups().deleteById(containerGroup.id()); + + //============================================================= + // List the file share content + + Iterable shareContent = shareClient.getRootDirectoryClient().listFilesAndDirectories(); + + for (ShareFileItem item : shareContent) { + System.out.format("Found shared file %s:%n", item.getName()); + } + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java index cbe3ba74c64e..04bdd63327c7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceWithMultipleContainerImages.java @@ -1,136 +1,136 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerinstance.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; -//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 java.time.Duration; -// -///** -// * Azure Container Instance sample for managing container instances. -// * - Create an Azure container group with two container instances using Docker images "microsoft/aci-helloworld" and "microsoft/aci-tutorial-sidecar" -// * - Set the container group restart policy to "never" -// * - Test that the container app can be reached via "curl" like HTTP GET calls -// * - Retrieve container log content -// * - Delete the container group resource -// */ -//public class ManageContainerInstanceWithMultipleContainerImages { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); -// final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); -// final String containerImageName1 = "microsoft/aci-helloworld"; -// final String containerImageName2 = "microsoft/aci-tutorial-sidecar"; -// -// try { -// //============================================================= -// // Create a container group with two container instances -// -// ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .withoutVolume() -// .defineContainerInstance(aciName + "-1") -// .withImage(containerImageName1) -// .withExternalTcpPort(80) -// .withCpuCoreCount(.5) -// .withMemorySizeInGB(0.8) -// .attach() -// .defineContainerInstance(aciName + "-2") -// .withImage(containerImageName2) -// .withoutPorts() -// .withCpuCoreCount(.5) -// .withMemorySizeInGB(0.8) -// .attach() -// .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) -// .withDnsPrefix(aciName) -// .create(); -// -// Utils.print(containerGroup); -// -// //============================================================= -// // Check that the container instance is up and running -// -// // warm up -// System.out.println("Warming up " + containerGroup.ipAddress()); -// Utils.sendGetRequest("http://" + containerGroup.ipAddress()); -// ResourceManagerUtils.sleep(Duration.ofSeconds(15)); -// System.out.println("CURLing " + containerGroup.ipAddress()); -// System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); -// -// //============================================================= -// // Check the container instance logs -// -// String logContent = containerGroup.getLogContent(aciName + "-1"); -// System.out.format("Logs for container instance: %s%n%s", aciName + "-1", logContent); -// logContent = containerGroup.getLogContent(aciName + "-2"); -// System.out.format("Logs for container instance: %s%n%s", aciName + "-2", logContent); -// -// //============================================================= -// // Remove the container group -// -// azureResourceManager.containerGroups().deleteById(containerGroup.id()); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerinstance.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; +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 java.time.Duration; + +/** + * Azure Container Instance sample for managing container instances. + * - Create an Azure container group with two container instances using Docker images "microsoft/aci-helloworld" and "microsoft/aci-tutorial-sidecar" + * - Set the container group restart policy to "never" + * - Test that the container app can be reached via "curl" like HTTP GET calls + * - Retrieve container log content + * - Delete the container group resource + */ +public class ManageContainerInstanceWithMultipleContainerImages { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACI", 15); + final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); + final String containerImageName1 = "microsoft/aci-helloworld"; + final String containerImageName2 = "microsoft/aci-tutorial-sidecar"; + + try { + //============================================================= + // Create a container group with two container instances + + ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withoutVolume() + .defineContainerInstance(aciName + "-1") + .withImage(containerImageName1) + .withExternalTcpPort(80) + .withCpuCoreCount(.5) + .withMemorySizeInGB(0.8) + .attach() + .defineContainerInstance(aciName + "-2") + .withImage(containerImageName2) + .withoutPorts() + .withCpuCoreCount(.5) + .withMemorySizeInGB(0.8) + .attach() + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withDnsPrefix(aciName) + .create(); + + Utils.print(containerGroup); + + //============================================================= + // Check that the container instance is up and running + + // warm up + System.out.println("Warming up " + containerGroup.ipAddress()); + Utils.sendGetRequest("http://" + containerGroup.ipAddress()); + ResourceManagerUtils.sleep(Duration.ofSeconds(15)); + System.out.println("CURLing " + containerGroup.ipAddress()); + System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); + + //============================================================= + // Check the container instance logs + + String logContent = containerGroup.getLogContent(aciName + "-1"); + System.out.format("Logs for container instance: %s%n%s", aciName + "-1", logContent); + logContent = containerGroup.getLogContent(aciName + "-2"); + System.out.format("Logs for container instance: %s%n%s", aciName + "-2", logContent); + + //============================================================= + // Remove the container group + + azureResourceManager.containerGroups().deleteById(containerGroup.id()); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java index 1e792ace938c..5c4661310444 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerinstance/samples/ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.java @@ -1,528 +1,528 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerinstance.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.resourcemanager.containerservice.models.AgentPoolMode; -//import com.azure.resourcemanager.containerservice.models.ContainerServiceVMSizeTypes; -//import com.azure.resourcemanager.containerservice.models.KubernetesCluster; -//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.DockerUtils; -//import com.azure.resourcemanager.samples.SSHShell; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.CreateContainerResponse; -//import com.github.dockerjava.api.command.PullImageResultCallback; -//import com.github.dockerjava.api.exception.NotFoundException; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.api.model.Container; -//import com.github.dockerjava.api.model.Image; -//import com.github.dockerjava.core.command.PushImageResultCallback; -//import com.jcraft.jsch.JSchException; -//import io.fabric8.kubernetes.api.model.LoadBalancerIngress; -//import io.fabric8.kubernetes.api.model.Namespace; -//import io.fabric8.kubernetes.api.model.NamespaceBuilder; -//import io.fabric8.kubernetes.api.model.Pod; -//import io.fabric8.kubernetes.api.model.ReplicationController; -//import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; -//import io.fabric8.kubernetes.api.model.Secret; -//import io.fabric8.kubernetes.api.model.SecretBuilder; -//import io.fabric8.kubernetes.api.model.Service; -//import io.fabric8.kubernetes.api.model.ServiceBuilder; -//import io.fabric8.kubernetes.client.Config; -//import io.fabric8.kubernetes.client.DefaultKubernetesClient; -//import io.fabric8.kubernetes.client.KubernetesClient; -//import org.apache.commons.codec.binary.Base64; -// -//import java.io.BufferedWriter; -//import java.io.File; -//import java.io.FileOutputStream; -//import java.io.IOException; -//import java.io.OutputStreamWriter; -//import java.nio.charset.StandardCharsets; -//import java.nio.file.Files; -//import java.nio.file.Paths; -//import java.time.Duration; -//import java.util.Arrays; -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -// -///** -// * Azure Container Instance sample for managing container instances. -// * - Create an Azure Container Registry to be used for holding private Docker container images -// * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine -// * to be used for this sample -// * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry -// * - Pull a test image from the public Docker repo (tomcat:8) to be used as a sample for pushing/pulling -// * to/from an Azure Container Registry -// * - Create an Azure container group with a container instance using the container image that was pushed to the -// * container registry created above -// * - Test that the container app can be reached via "curl" like HTTP GET calls -// * - Retrieve container log content -// * - Create a SSH private/public key to be used when creating a container service -// * - Create an Azure Container Service with Kubernetes orchestration -// * - Log in via the SSH client and download the Kubernetes config -// * - Create a Kubernetes client using the Kubernetes config file downloaded from one of the virtual machine managers -// * - Create a Kubernetes namespace -// * - Create a Kubernetes secret of type "docker-registry" using the Azure Container Registry credentials from above -// * - Create a Kubernetes replication controller using a container image from the Azure private registry from above -// * and a load balancer service that will expose the app to the world -// */ -//public class ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @param clientId secondary service principal client ID -// * @param secret secondary service principal secret -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, InterruptedException, JSchException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgaci", 15); -// final Region region = Region.US_EAST2; -// -// final String acrName = Utils.randomResourceName(azureResourceManager, "acr", 20); -// -// final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); -// final String containerImageName = "microsoft/aci-helloworld"; -// final String containerImageTag = "latest"; -// final String dockerContainerName = "sample-hello"; -// -// final String acsName = Utils.randomResourceName(azureResourceManager, "acssample", 30); -// String servicePrincipalClientId = clientId; // replace with a real service principal client id -// String servicePrincipalSecret = secret; // and corresponding secret -// final String rootUserName = "acsuser"; -// String acsSecretName = "mysecret112233"; -// String acsNamespace = "acrsample"; -// String acsLbIngressName = "lb-acrsample"; -// -// try { -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// Date t1 = new Date(); -// -// Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .create(); -// -// Date t2 = new Date(); -// System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// //============================================================= -// // Pull a temp image from public Docker repo and create a temporary container from that image -// // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR -// -// dockerClient.pullImageCmd(containerImageName) -// .withTag(containerImageTag) -// .withAuthConfig(new AuthConfig()) -// .exec(new PullImageResultCallback()) -// .awaitCompletion(); -// System.out.println("List local Docker images:"); -// List images = dockerClient.listImagesCmd().withShowAll(true).exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// -// CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(containerImageName + ":" + containerImageTag) -// .withName(dockerContainerName) -// .exec(); -// System.out.println("List Docker containers:"); -// List dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// //============================================================= -// // Commit the new container -// -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; -// dockerClient.commitCmd(dockerContainerInstance.getId()) -// .withRepository(privateRepoUrl) -// .withTag("latest").exec(); -// -// // We can now remove the temporary container instance -// dockerClient.removeContainerCmd(dockerContainerInstance.getId()) -// .withForce(true) -// .exec(); -// -// //============================================================= -// // Push the new Docker image to the Azure Container Registry -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PushImageResultCallback()).awaitSuccess(); -// -// // Remove the temp image from the local Docker host -// try { -// dockerClient.removeImageCmd(containerImageName + ":" + containerImageTag).withForce(true).exec(); -// } catch (NotFoundException e) { -// // just ignore if not exist -// } -// -// //============================================================= -// // Create a container group with one container instance of default CPU core count and memory size -// // using public Docker image "microsoft/aci-helloworld" and mounts a new file share as read/write -// // shared container volume. -// -// ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withLinux() -// .withPrivateImageRegistry(azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) -// .withoutVolume() -// .defineContainerInstance(aciName) -// .withImage(privateRepoUrl) -// .withExternalTcpPort(80) -// .attach() -// .withDnsPrefix(aciName) -// .create(); -// -// Utils.print(containerGroup); -// -// //============================================================= -// // Check that the container instance is up and running -// -// // warm up -// System.out.println("Warming up " + containerGroup.ipAddress()); -// Utils.sendGetRequest("http://" + containerGroup.ipAddress()); -// ResourceManagerUtils.sleep(Duration.ofSeconds(15)); -// System.out.println("CURLing " + containerGroup.ipAddress()); -// System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); -// -// //============================================================= -// // Check the container instance logs -// -// String logContent = containerGroup.getLogContent(aciName); -// System.out.format("Logs for container instance: %s%n%s", aciName, logContent); -// -// //============================================================= -// // If service principal client id and secret are not set via the local variables, attempt to read the service -// // principal client id and secret from a secondary ".azureauth" file set through an environment variable. -// // -// // If the environment variable was not set then reuse the main service principal set for running this sample. -// -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { -// servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); -// servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { -// String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); -// -// if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { -// envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); -// } -// -// servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); -// servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); -// } -// } -// -// -// //============================================================= -// // Create an SSH private/public key pair to be used when creating the container service -// -// System.out.println("Creating an SSH private and public key pair"); -// -// SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); -// System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); -// System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); -// -// -// //============================================================= -// // Create an Azure Container Service with Kubernetes orchestration -// -// System.out.println("Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); -// -// t1 = new Date(); -// -// KubernetesCluster azureKubernetesCluster = azureResourceManager.kubernetesClusters().define(acsName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withDefaultVersion() -// .withRootUsername(rootUserName) -// .withSshKey(sshKeys.getSshPublicKey()) -// .withServicePrincipalClientId(servicePrincipalClientId) -// .withServicePrincipalSecret(servicePrincipalSecret) -// .defineAgentPool("agentpool") -// .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) -// .withAgentPoolVirtualMachineCount(1) -// .withAgentPoolMode(AgentPoolMode.SYSTEM) -//// .withDnsPrefix("dns-ap-" + acsName) -// .attach() -// .withDnsPrefix("dns-" + acsName) -// .create(); -// -// t2 = new Date(); -// System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureKubernetesCluster.id()); -// Utils.print(azureKubernetesCluster); -// -// ResourceManagerUtils.sleep(Duration.ofMinutes(2)); -// -// -// //============================================================= -// // Download the Kubernetes config file from one of the master virtual machines -// -// azureKubernetesCluster = azureResourceManager.kubernetesClusters().getByResourceGroup(rgName, acsName); -// System.out.println("Found Kubernetes master at: " + azureKubernetesCluster.fqdn()); -// -// byte[] kubeConfigContent = azureKubernetesCluster.adminKubeConfigContent(); -// System.out.println("Found Kubernetes config:%n" + Arrays.toString(kubeConfigContent)); -// -// -// //============================================================= -// // Instantiate the Kubernetes client using the downloaded ".kube/config" file content -// // The Kubernetes client API requires setting an environment variable pointing at a real file; -// // we will create a temporary file that will be deleted automatically when the sample exits -// -// File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); -// tempKubeConfigFile.deleteOnExit(); -// try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { -// buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); -// } -// -// System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath()); -// Config config = new Config(); -// KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); -// -// // Wait for 15 minutes for kube endpoint to be available -// ResourceManagerUtils.sleep(Duration.ofMinutes(15)); -// -// -// //============================================================= -// // List all the nodes available in the Kubernetes cluster -// -// System.out.println(kubernetesClient.nodes().list()); -// -// -// //============================================================= -// // Create a namespace where all the sample Kubernetes resources will be created -// -// Namespace ns = new NamespaceBuilder() -// .withNewMetadata() -// .withName(acsNamespace) -// .addToLabels("acr", "sample") -// .endMetadata() -// .build(); -// try { -// System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); -// } catch (Exception e) { -// System.err.println(e.getMessage()); -// } -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) { -// System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); -// } -// -// -// //============================================================= -// // Create a secret of type "docker-repository" that will be used for downloading the container image from -// // our Azure private container repo -// -// String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); -// HashMap secretData = new HashMap<>(1); -// String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", -// azureRegistry.loginServerUrl(), -// basicAuth, -// "acrsample@azure.com"); -// -// dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); -// secretData.put(".dockercfg", dockerCfg); -// SecretBuilder secretBuilder = new SecretBuilder() -// .withNewMetadata() -// .withName(acsSecretName) -// .withNamespace(acsNamespace) -// .endMetadata() -// .withData(secretData) -// .withType("kubernetes.io/dockercfg"); -// -// System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build())); -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// for (Secret kubeS : kubernetesClient.secrets().inNamespace(acsNamespace).list().getItems()) { -// System.out.println("\tFound secret: " + kubeS); -// } -// -// -// //============================================================= -// // Create a replication controller for our image stored in the Azure Container Registry -// -// ReplicationController rc = new ReplicationControllerBuilder() -// .withNewMetadata() -// .withName("acrsample-rc") -// .withNamespace(acsNamespace) -// .addToLabels("acrsample-myimg", "myimg") -// .endMetadata() -// .withNewSpec() -// .withReplicas(2) -// .withNewTemplate() -// .withNewMetadata() -// .addToLabels("acrsample-myimg", "myimg") -// .endMetadata() -// .withNewSpec() -// .addNewImagePullSecret(acsSecretName) -// .addNewContainer() -// .withName("acrsample-pod-myimg") -// .withImage(privateRepoUrl) -// .addNewPort() -// .withContainerPort(80) -// .endPort() -// .endContainer() -// .endSpec() -// .endTemplate() -// .endSpec() -// .build(); -// -// System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc)); -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get(); -// System.out.println("Found replication controller: " + rc.toString()); -// -// for (Pod pod : kubernetesClient.pods().inNamespace(acsNamespace).list().getItems()) { -// System.out.println("\tFound Kubernetes pods: " + pod.toString()); -// } -// -// -// //============================================================= -// // Create a Load Balancer service that will expose the service to the world -// -// Service lbService = new ServiceBuilder() -// .withNewMetadata() -// .withName(acsLbIngressName) -// .withNamespace(acsNamespace) -// .endMetadata() -// .withNewSpec() -// .withType("LoadBalancer") -// .addNewPort() -// .withPort(80) -// .withProtocol("TCP") -// .endPort() -// .addToSelector("acrsample-myimg", "myimg") -// .endSpec() -// .build(); -// -// System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(acsNamespace).create(lbService)); -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get()); -// -// -// //============================================================= -// // Wait until the external IP becomes available -// -// String serviceIP = null; -// -// int timeout = 30 * 60 * 1000; // 30 minutes -// String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"; -// -// while (timeout > 0) { -// try { -// List lbIngressList = kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress(); -// if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { -// serviceIP = lbIngressList.get(0).getIp(); -// System.out.println("\tFound ingress IP: " + serviceIP); -// timeout = 0; -// } -// } catch (Exception e) { -// System.err.println(e.getMessage()); -// } -// -// if (timeout > 0) { -// timeout -= 30000; // 30 seconds -// ResourceManagerUtils.sleep(Duration.ofSeconds(30)); -// } -// } -// -// //============================================================= -// // Check that the service is up and running -// -// if (serviceIP != null) { -// // warm up -// System.out.println("Warming up " + serviceIP); -// Utils.sendGetRequest("http://" + serviceIP); -// ResourceManagerUtils.sleep(Duration.ofSeconds(15)); -// System.out.println("CURLing " + serviceIP); -// System.out.println(Utils.sendGetRequest("http://" + serviceIP)); -// } else { -// System.out.println("ERROR: service unavailable"); -// } -// -// // Clean-up -// kubernetesClient.namespaces().delete(ns); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager, "", ""); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerinstance.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.resourcemanager.containerservice.models.AgentPoolMode; +import com.azure.resourcemanager.containerservice.models.ContainerServiceVMSizeTypes; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster; +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.DockerUtils; +import com.azure.resourcemanager.samples.SSHShell; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.core.command.PushImageResultCallback; +import com.jcraft.jsch.JSchException; +import io.fabric8.kubernetes.api.model.LoadBalancerIngress; +import io.fabric8.kubernetes.api.model.Namespace; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.ReplicationController; +import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClient; +import org.apache.commons.codec.binary.Base64; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +/** + * Azure Container Instance sample for managing container instances. + * - Create an Azure Container Registry to be used for holding private Docker container images + * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine + * to be used for this sample + * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry + * - Pull a test image from the public Docker repo (tomcat:8) to be used as a sample for pushing/pulling + * to/from an Azure Container Registry + * - Create an Azure container group with a container instance using the container image that was pushed to the + * container registry created above + * - Test that the container app can be reached via "curl" like HTTP GET calls + * - Retrieve container log content + * - Create a SSH private/public key to be used when creating a container service + * - Create an Azure Container Service with Kubernetes orchestration + * - Log in via the SSH client and download the Kubernetes config + * - Create a Kubernetes client using the Kubernetes config file downloaded from one of the virtual machine managers + * - Create a Kubernetes namespace + * - Create a Kubernetes secret of type "docker-registry" using the Azure Container Registry credentials from above + * - Create a Kubernetes replication controller using a container image from the Azure private registry from above + * and a load balancer service that will expose the app to the world + */ +public class ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @param clientId secondary service principal client ID + * @param secret secondary service principal secret + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, InterruptedException, JSchException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgaci", 15); + final Region region = Region.US_EAST2; + + final String acrName = Utils.randomResourceName(azureResourceManager, "acr", 20); + + final String aciName = Utils.randomResourceName(azureResourceManager, "acisample", 20); + final String containerImageName = "microsoft/aci-helloworld"; + final String containerImageTag = "latest"; + final String dockerContainerName = "sample-hello"; + + final String acsName = Utils.randomResourceName(azureResourceManager, "acssample", 30); + String servicePrincipalClientId = clientId; // replace with a real service principal client id + String servicePrincipalSecret = secret; // and corresponding secret + final String rootUserName = "acsuser"; + String acsSecretName = "mysecret112233"; + String acsNamespace = "acrsample"; + String acsLbIngressName = "lb-acrsample"; + + try { + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + Date t1 = new Date(); + + Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); + + Date t2 = new Date(); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + //============================================================= + // Pull a temp image from public Docker repo and create a temporary container from that image + // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR + + dockerClient.pullImageCmd(containerImageName) + .withTag(containerImageTag) + .withAuthConfig(new AuthConfig()) + .exec(new PullImageResultCallback()) + .awaitCompletion(); + System.out.println("List local Docker images:"); + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + + CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(containerImageName + ":" + containerImageTag) + .withName(dockerContainerName) + .exec(); + System.out.println("List Docker containers:"); + List dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + //============================================================= + // Commit the new container + + String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; + dockerClient.commitCmd(dockerContainerInstance.getId()) + .withRepository(privateRepoUrl) + .withTag("latest").exec(); + + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()) + .withForce(true) + .exec(); + + //============================================================= + // Push the new Docker image to the Azure Container Registry + + dockerClient.pushImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PushImageResultCallback()).awaitSuccess(); + + // Remove the temp image from the local Docker host + try { + dockerClient.removeImageCmd(containerImageName + ":" + containerImageTag).withForce(true).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + + //============================================================= + // Create a container group with one container instance of default CPU core count and memory size + // using public Docker image "microsoft/aci-helloworld" and mounts a new file share as read/write + // shared container volume. + + ContainerGroup containerGroup = azureResourceManager.containerGroups().define(aciName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withLinux() + .withPrivateImageRegistry(azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)) + .withoutVolume() + .defineContainerInstance(aciName) + .withImage(privateRepoUrl) + .withExternalTcpPort(80) + .attach() + .withDnsPrefix(aciName) + .create(); + + Utils.print(containerGroup); + + //============================================================= + // Check that the container instance is up and running + + // warm up + System.out.println("Warming up " + containerGroup.ipAddress()); + Utils.sendGetRequest("http://" + containerGroup.ipAddress()); + ResourceManagerUtils.sleep(Duration.ofSeconds(15)); + System.out.println("CURLing " + containerGroup.ipAddress()); + System.out.println(Utils.sendGetRequest("http://" + containerGroup.ipAddress())); + + //============================================================= + // Check the container instance logs + + String logContent = containerGroup.getLogContent(aciName); + System.out.format("Logs for container instance: %s%n%s", aciName, logContent); + + //============================================================= + // If service principal client id and secret are not set via the local variables, attempt to read the service + // principal client id and secret from a secondary ".azureauth" file set through an environment variable. + // + // If the environment variable was not set then reuse the main service principal set for running this sample. + + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); + servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); + + if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); + } + + servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); + servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); + } + } + + + //============================================================= + // Create an SSH private/public key pair to be used when creating the container service + + System.out.println("Creating an SSH private and public key pair"); + + SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); + System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); + System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); + + + //============================================================= + // Create an Azure Container Service with Kubernetes orchestration + + System.out.println("Creating an Azure Container Service with Kubernetes ochestration and one agent (virtual machine)"); + + t1 = new Date(); + + KubernetesCluster azureKubernetesCluster = azureResourceManager.kubernetesClusters().define(acsName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername(rootUserName) + .withSshKey(sshKeys.getSshPublicKey()) + .withServicePrincipalClientId(servicePrincipalClientId) + .withServicePrincipalSecret(servicePrincipalSecret) + .defineAgentPool("agentpool") + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) +// .withDnsPrefix("dns-ap-" + acsName) + .attach() + .withDnsPrefix("dns-" + acsName) + .create(); + + t2 = new Date(); + System.out.println("Created Azure Container Service: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureKubernetesCluster.id()); + Utils.print(azureKubernetesCluster); + + ResourceManagerUtils.sleep(Duration.ofMinutes(2)); + + + //============================================================= + // Download the Kubernetes config file from one of the master virtual machines + + azureKubernetesCluster = azureResourceManager.kubernetesClusters().getByResourceGroup(rgName, acsName); + System.out.println("Found Kubernetes master at: " + azureKubernetesCluster.fqdn()); + + byte[] kubeConfigContent = azureKubernetesCluster.adminKubeConfigContent(); + System.out.println("Found Kubernetes config:%n" + Arrays.toString(kubeConfigContent)); + + + //============================================================= + // Instantiate the Kubernetes client using the downloaded ".kube/config" file content + // The Kubernetes client API requires setting an environment variable pointing at a real file; + // we will create a temporary file that will be deleted automatically when the sample exits + + File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); + tempKubeConfigFile.deleteOnExit(); + try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { + buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); + } + + System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath()); + Config config = new Config(); + KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); + + // Wait for 15 minutes for kube endpoint to be available + ResourceManagerUtils.sleep(Duration.ofMinutes(15)); + + + //============================================================= + // List all the nodes available in the Kubernetes cluster + + System.out.println(kubernetesClient.nodes().list()); + + + //============================================================= + // Create a namespace where all the sample Kubernetes resources will be created + + Namespace ns = new NamespaceBuilder() + .withNewMetadata() + .withName(acsNamespace) + .addToLabels("acr", "sample") + .endMetadata() + .build(); + try { + System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) { + System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); + } + + + //============================================================= + // Create a secret of type "docker-repository" that will be used for downloading the container image from + // our Azure private container repo + + String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + HashMap secretData = new HashMap<>(1); + String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", + azureRegistry.loginServerUrl(), + basicAuth, + "acrsample@azure.com"); + + dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); + secretData.put(".dockercfg", dockerCfg); + SecretBuilder secretBuilder = new SecretBuilder() + .withNewMetadata() + .withName(acsSecretName) + .withNamespace(acsNamespace) + .endMetadata() + .withData(secretData) + .withType("kubernetes.io/dockercfg"); + + System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(acsNamespace).create(secretBuilder.build())); + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + for (Secret kubeS : kubernetesClient.secrets().inNamespace(acsNamespace).list().getItems()) { + System.out.println("\tFound secret: " + kubeS); + } + + + //============================================================= + // Create a replication controller for our image stored in the Azure Container Registry + + ReplicationController rc = new ReplicationControllerBuilder() + .withNewMetadata() + .withName("acrsample-rc") + .withNamespace(acsNamespace) + .addToLabels("acrsample-myimg", "myimg") + .endMetadata() + .withNewSpec() + .withReplicas(2) + .withNewTemplate() + .withNewMetadata() + .addToLabels("acrsample-myimg", "myimg") + .endMetadata() + .withNewSpec() + .addNewImagePullSecret(acsSecretName) + .addNewContainer() + .withName("acrsample-pod-myimg") + .withImage(privateRepoUrl) + .addNewPort() + .withContainerPort(80) + .endPort() + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + + System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(acsNamespace).create(rc)); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + rc = kubernetesClient.replicationControllers().inNamespace(acsNamespace).withName("acrsample-rc").get(); + System.out.println("Found replication controller: " + rc.toString()); + + for (Pod pod : kubernetesClient.pods().inNamespace(acsNamespace).list().getItems()) { + System.out.println("\tFound Kubernetes pods: " + pod.toString()); + } + + + //============================================================= + // Create a Load Balancer service that will expose the service to the world + + Service lbService = new ServiceBuilder() + .withNewMetadata() + .withName(acsLbIngressName) + .withNamespace(acsNamespace) + .endMetadata() + .withNewSpec() + .withType("LoadBalancer") + .addNewPort() + .withPort(80) + .withProtocol("TCP") + .endPort() + .addToSelector("acrsample-myimg", "myimg") + .endSpec() + .build(); + + System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(acsNamespace).create(lbService)); + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get()); + + + //============================================================= + // Wait until the external IP becomes available + + String serviceIP = null; + + int timeout = 30 * 60 * 1000; // 30 minutes + String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"; + + while (timeout > 0) { + try { + List lbIngressList = kubernetesClient.services().inNamespace(acsNamespace).withName(acsLbIngressName).get().getStatus().getLoadBalancer().getIngress(); + if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { + serviceIP = lbIngressList.get(0).getIp(); + System.out.println("\tFound ingress IP: " + serviceIP); + timeout = 0; + } + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + if (timeout > 0) { + timeout -= 30000; // 30 seconds + ResourceManagerUtils.sleep(Duration.ofSeconds(30)); + } + } + + //============================================================= + // Check that the service is up and running + + if (serviceIP != null) { + // warm up + System.out.println("Warming up " + serviceIP); + Utils.sendGetRequest("http://" + serviceIP); + ResourceManagerUtils.sleep(Duration.ofSeconds(15)); + System.out.println("CURLing " + serviceIP); + System.out.println(Utils.sendGetRequest("http://" + serviceIP)); + } else { + System.out.println("ERROR: service unavailable"); + } + + // Clean-up + kubernetesClient.namespaces().delete(ns); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager, "", ""); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java index 0d772b03415c..6c9c8799c653 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistry.java @@ -1,205 +1,205 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerregistry.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.DockerUtils; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.CreateContainerResponse; -//import com.github.dockerjava.api.exception.NotFoundException; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.api.model.Container; -//import com.github.dockerjava.api.model.Image; -//import com.github.dockerjava.core.command.PullImageResultCallback; -//import com.github.dockerjava.core.command.PushImageResultCallback; -// -//import java.io.IOException; -//import java.util.Date; -//import java.util.List; -// -///** -// * Azure Container Registry sample for managing container registry. -// * - Create an Azure Container Registry to be used for holding the Docker images -// * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine -// * to be used for this sample -// * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry -// * - Pull a test image from the public Docker repo (hello-world:latest) to be used as a sample for pushing/pulling -// * to/from an Azure Container Registry -// * - Create a new Docker container from an image that was pulled from Azure Container Registry -// */ -//public class ManageContainerRegistry { -// -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); -// final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); -// final Region region = Region.US_EAST; -// final String dockerImageName = "hello-world"; -// final String dockerImageTag = "latest"; -// final String dockerContainerName = "sample-hello"; -// -// try { -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// Date t1 = new Date(); -// -// Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .create(); -// -// Date t2 = new Date(); -// System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// //============================================================= -// // Pull a temp image from public Docker repo and create a temporary container from that image -// // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR -// -// dockerClient.pullImageCmd(dockerImageName) -// .withTag(dockerImageTag) -// .withAuthConfig(new AuthConfig()) // anonymous -// .exec(new PullImageResultCallback()) -// .awaitSuccess(); -// System.out.println("List local Docker images:"); -// List images = dockerClient.listImagesCmd().withShowAll(true).exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// -// CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) -// .withName(dockerContainerName) -// .withCmd("/hello") -// .exec(); -// System.out.println("List Docker containers:"); -// List dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// //============================================================= -// // Commit the new container -// -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; -// dockerClient.commitCmd(dockerContainerInstance.getId()) -// .withRepository(privateRepoUrl) -// .withTag("latest").exec(); -// -// // We can now remove the temporary container instance -// dockerClient.removeContainerCmd(dockerContainerInstance.getId()) -// .withForce(true) -// .exec(); -// -// //============================================================= -// // Push the new Docker image to the Azure Container Registry -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .exec(new PushImageResultCallback()).awaitSuccess(); -// -// // Remove the temp image from the local Docker host -// try { -// dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); -// } catch (NotFoundException e) { -// // just ignore if not exist -// } -// -// //============================================================= -// // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally -// -// dockerClient.pullImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PullImageResultCallback()).awaitSuccess(); -// System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); -// images = dockerClient.listImagesCmd() -// .withShowAll(true) -// .exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// dockerClient.createContainerCmd(privateRepoUrl) -// .withName(dockerContainerName + "-private") -// .withCmd("/hello").exec(); -// System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); -// dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerregistry.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.DockerUtils; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.core.command.PullImageResultCallback; +import com.github.dockerjava.core.command.PushImageResultCallback; + +import java.io.IOException; +import java.util.Date; +import java.util.List; + +/** + * Azure Container Registry sample for managing container registry. + * - Create an Azure Container Registry to be used for holding the Docker images + * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine + * to be used for this sample + * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry + * - Pull a test image from the public Docker repo (hello-world:latest) to be used as a sample for pushing/pulling + * to/from an Azure Container Registry + * - Create a new Docker container from an image that was pulled from Azure Container Registry + */ +public class ManageContainerRegistry { + + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); + final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); + final Region region = Region.US_EAST; + final String dockerImageName = "hello-world"; + final String dockerImageTag = "latest"; + final String dockerContainerName = "sample-hello"; + + try { + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + Date t1 = new Date(); + + Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); + + Date t2 = new Date(); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + //============================================================= + // Pull a temp image from public Docker repo and create a temporary container from that image + // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR + + dockerClient.pullImageCmd(dockerImageName) + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) // anonymous + .exec(new PullImageResultCallback()) + .awaitSuccess(); + System.out.println("List local Docker images:"); + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + + CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .withCmd("/hello") + .exec(); + System.out.println("List Docker containers:"); + List dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + //============================================================= + // Commit the new container + + String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; + dockerClient.commitCmd(dockerContainerInstance.getId()) + .withRepository(privateRepoUrl) + .withTag("latest").exec(); + + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()) + .withForce(true) + .exec(); + + //============================================================= + // Push the new Docker image to the Azure Container Registry + + dockerClient.pushImageCmd(privateRepoUrl) + .exec(new PushImageResultCallback()).awaitSuccess(); + + // Remove the temp image from the local Docker host + try { + dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + + //============================================================= + // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally + + dockerClient.pullImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PullImageResultCallback()).awaitSuccess(); + System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); + images = dockerClient.listImagesCmd() + .withShowAll(true) + .exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + dockerClient.createContainerCmd(privateRepoUrl) + .withName(dockerContainerName + "-private") + .withCmd("/hello").exec(); + System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); + dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java index 380cb19e1094..daae7e6e3827 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/containerregistry/samples/ManageContainerRegistryWithWebhooks.java @@ -1,224 +1,224 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.containerregistry.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.resourcemanager.containerregistry.models.Webhook; -//import com.azure.resourcemanager.containerregistry.models.WebhookAction; -//import com.azure.resourcemanager.containerregistry.models.WebhookEventInfo; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.DockerUtils; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.CreateContainerResponse; -//import com.github.dockerjava.api.command.PullImageResultCallback; -//import com.github.dockerjava.api.exception.NotFoundException; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.api.model.Container; -//import com.github.dockerjava.api.model.Image; -//import com.github.dockerjava.core.command.PushImageResultCallback; -// -//import java.io.IOException; -//import java.util.Date; -//import java.util.List; -//import java.util.stream.Collectors; -// -///** -// * Azure Container Registry sample for managing container registry with webhooks. -// * - Create an Azure Container Registry and setup couple Webhooks to be triggered on registry related actions (push, delete) -// * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine -// * to be used for this sample -// * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry -// * - Pull a test image from the public Docker repo (hello-world:latest) to be used as a sample for pushing/pulling -// * to/from an Azure Container Registry -// * - List the container registry webhook event notifications after pushing a container image to the registry -// */ -//public class ManageContainerRegistryWithWebhooks { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); -// final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); -// final Region region = Region.US_WEST_CENTRAL; -// final String dockerImageName = "hello-world"; -// final String dockerImageTag = "latest"; -// final String dockerContainerName = "sample-hello"; -// final String webhookName1 = "webhookbing1"; -// final String webhookName2 = "webhookbing2"; -// final String webhookServiceUri1 = "https://www.bing.com"; -// final String webhookServiceUri2 = "https://www.bing.com"; -// -// -// try { -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// Date t1 = new Date(); -// -// Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .defineWebhook(webhookName1) -// .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) -// .withServiceUri(webhookServiceUri1) -// .withTag("tag", "value") -// .withCustomHeader("name", "value") -// .attach() -// .defineWebhook(webhookName2) -// .withTriggerWhen(WebhookAction.PUSH) -// .withServiceUri(webhookServiceUri2) -// .enabled(false) -// .withRepositoriesScope("") -// .attach() -// .withTag("tag1", "value1") -// .create(); -// -// Date t2 = new Date(); -// System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// -// //============================================================= -// // Ping the container registry webhook to validate it works as expected -// -// Webhook webhook = azureRegistry.webhooks().get(webhookName1); -// webhook.ping(); -// List webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); -// System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); -// for (WebhookEventInfo webhookEventInfo : webhookEvents) { -// System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); -// } -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// //============================================================= -// // Pull a temp image from public Docker repo and create a temporary container from that image -// // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR -// -// dockerClient.pullImageCmd(dockerImageName) -// .withTag(dockerImageTag) -// .withAuthConfig(new AuthConfig()) // anonymous -// .exec(new PullImageResultCallback()) -// .awaitCompletion(); -// System.out.println("List local Docker images:"); -// List images = dockerClient.listImagesCmd().withShowAll(true).exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// -// CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) -// .withName(dockerContainerName) -// .withCmd("/hello") -// .exec(); -// System.out.println("List Docker containers:"); -// List dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// //============================================================= -// // Commit the new container -// -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; -// dockerClient.commitCmd(dockerContainerInstance.getId()) -// .withRepository(privateRepoUrl) -// .withTag("latest").exec(); -// -// // We can now remove the temporary container instance -// dockerClient.removeContainerCmd(dockerContainerInstance.getId()) -// .withForce(true) -// .exec(); -// -// //============================================================= -// // Push the new Docker image to the Azure Container Registry -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PushImageResultCallback()).awaitSuccess(); -// -// // Remove the temp image from the local Docker host -// try { -// dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); -// } catch (NotFoundException e) { -// // just ignore if not exist -// } -// -// //============================================================= -// // Gets the container registry webhook after pushing a container image and list the event notifications -// -// webhook = azureRegistry.webhooks().get(webhookName1); -// webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); -// System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); -// for (WebhookEventInfo webhookEventInfo : webhookEvents) { -// System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); -// } -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.containerregistry.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.resourcemanager.containerregistry.models.Webhook; +import com.azure.resourcemanager.containerregistry.models.WebhookAction; +import com.azure.resourcemanager.containerregistry.models.WebhookEventInfo; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.DockerUtils; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.core.command.PushImageResultCallback; + +import java.io.IOException; +import java.util.Date; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Azure Container Registry sample for managing container registry with webhooks. + * - Create an Azure Container Registry and setup couple Webhooks to be triggered on registry related actions (push, delete) + * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine + * to be used for this sample + * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry + * - Pull a test image from the public Docker repo (hello-world:latest) to be used as a sample for pushing/pulling + * to/from an Azure Container Registry + * - List the container registry webhook event notifications after pushing a container image to the registry + */ +public class ManageContainerRegistryWithWebhooks { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException, InterruptedException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgACR", 15); + final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); + final Region region = Region.US_WEST_CENTRAL; + final String dockerImageName = "hello-world"; + final String dockerImageTag = "latest"; + final String dockerContainerName = "sample-hello"; + final String webhookName1 = "webhookbing1"; + final String webhookName2 = "webhookbing2"; + final String webhookServiceUri1 = "https://www.bing.com"; + final String webhookServiceUri2 = "https://www.bing.com"; + + + try { + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + Date t1 = new Date(); + + Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .defineWebhook(webhookName1) + .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) + .withServiceUri(webhookServiceUri1) + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() + .defineWebhook(webhookName2) + .withTriggerWhen(WebhookAction.PUSH) + .withServiceUri(webhookServiceUri2) + .enabled(false) + .withRepositoriesScope("") + .attach() + .withTag("tag1", "value1") + .create(); + + Date t2 = new Date(); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + + //============================================================= + // Ping the container registry webhook to validate it works as expected + + Webhook webhook = azureRegistry.webhooks().get(webhookName1); + webhook.ping(); + List webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); + System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); + for (WebhookEventInfo webhookEventInfo : webhookEvents) { + System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); + } + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + //============================================================= + // Pull a temp image from public Docker repo and create a temporary container from that image + // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR + + dockerClient.pullImageCmd(dockerImageName) + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) // anonymous + .exec(new PullImageResultCallback()) + .awaitCompletion(); + System.out.println("List local Docker images:"); + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + + CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .withCmd("/hello") + .exec(); + System.out.println("List Docker containers:"); + List dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + //============================================================= + // Commit the new container + + String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; + dockerClient.commitCmd(dockerContainerInstance.getId()) + .withRepository(privateRepoUrl) + .withTag("latest").exec(); + + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()) + .withForce(true) + .exec(); + + //============================================================= + // Push the new Docker image to the Azure Container Registry + + dockerClient.pushImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PushImageResultCallback()).awaitSuccess(); + + // Remove the temp image from the local Docker host + try { + dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + + //============================================================= + // Gets the container registry webhook after pushing a container image and list the event notifications + + webhook = azureRegistry.webhooks().get(webhookName1); + webhookEvents = webhook.listEvents().stream().collect(Collectors.toList()); + System.out.format("Found %d webhook events for: %s with container service: %s/n", webhookEvents.size(), webhook.name(), azureRegistry.name()); + for (WebhookEventInfo webhookEventInfo : webhookEvents) { + System.out.print("\t" + webhookEventInfo.eventResponseMessage().content()); + } + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java index f9837a513220..4b864b7a212e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHub.java @@ -1,204 +1,204 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.eventhubs.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.eventhubs.models.EventHub; -//import com.azure.resourcemanager.eventhubs.models.EventHubConsumerGroup; -//import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.storage.models.StorageAccount; -//import com.azure.resourcemanager.storage.models.StorageAccountSkuType; -// -///** -// * Azure Event Hub sample for managing event hub - -// * - Create an event hub namespace -// * - Create an event hub in the namespace with data capture enabled along with a consumer group and rule -// * - List consumer groups in the event hub -// * - Create a second event hub in the namespace -// * - Create a consumer group in the second event hub -// * - List consumer groups in the second event hub -// * - Create an event hub namespace along with event hub. -// */ -//public class ManageEventHub { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); -// final String namespaceName1 = Utils.randomResourceName(azureResourceManager, "ns", 14); -// final String namespaceName2 = Utils.randomResourceName(azureResourceManager, "ns", 14); -// final String storageAccountName = Utils.randomResourceName(azureResourceManager, "stg", 14); -// final String eventHubName1 = Utils.randomResourceName(azureResourceManager, "eh", 14); -// final String eventHubName2 = Utils.randomResourceName(azureResourceManager, "eh", 14); -// try { -// -// //============================================================ -// // Create an event hub namespace -// // -// System.out.println("Creating a namespace"); -// -// EventHubNamespace namespace1 = azureResourceManager.eventHubNamespaces() -// .define(namespaceName1) -// .withRegion(Region.US_EAST2) -// .withNewResourceGroup(rgName) -// .create(); -// -// Utils.print(namespace1); -// System.out.println("Created a namespace"); -// //============================================================ -// // Create an event hub in the namespace with data capture enabled, with consumer group and auth rule -// // -// -// Creatable storageAccountCreatable = azureResourceManager.storageAccounts() -// .define(storageAccountName) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withSku(StorageAccountSkuType.STANDARD_LRS); -// -// System.out.println("Creating an event hub with data capture enabled with a consumer group and rule in it"); -// -// EventHub eventHub1 = azureResourceManager.eventHubs() -// .define(eventHubName1) -// .withExistingNamespace(namespace1) -// // Optional - configure data capture -// .withNewStorageAccountForCapturedData(storageAccountCreatable, "datacpt") -// .withDataCaptureEnabled() -// // Optional - create one consumer group in event hub -// .withNewConsumerGroup("cg1", "sometadata") -// // Optional - create an authorization rule for event hub -// .withNewListenRule("listenrule1") -// .create(); -// -// System.out.println("Created an event hub with data capture enabled with a consumer group and rule in it"); -// Utils.print(eventHub1); -// -// //============================================================ -// // Retrieve consumer groups in the event hub -// // -// System.out.println("Retrieving consumer groups"); -// -// PagedIterable consumerGroups = eventHub1.listConsumerGroups(); -// -// System.out.println("Retrieved consumer groups"); -// for (EventHubConsumerGroup group : consumerGroups) { -// Utils.print(group); -// } -// -// //============================================================ -// // Create another event hub in the namespace using event hub accessor in namespace accessor -// // -// -// System.out.println("Creating another event hub in the namespace"); -// -// EventHub eventHub2 = azureResourceManager.eventHubNamespaces() -// .eventHubs() -// .define(eventHubName2) -// .withExistingNamespace(namespace1) -// .create(); -// -// System.out.println("Created second event hub"); -// Utils.print(eventHub2); -// -// //============================================================ -// // Create a consumer group in the event hub using consumer group accessor in event hub accessor -// // -// -// System.out.println("Creating a consumer group in the second event hub"); -// -// EventHubConsumerGroup consumerGroup2 = azureResourceManager.eventHubNamespaces() -// .eventHubs() -// .consumerGroups() -// .define("cg2") -// .withExistingEventHub(eventHub2) -// // Optional -// .withUserMetadata("sometadata") -// .create(); -// -// System.out.println("Created a consumer group in the second event hub"); -// Utils.print(consumerGroup2); -// -// //============================================================ -// // Retrieve consumer groups in the event hub -// // -// System.out.println("Retrieving consumer groups in the second event hub"); -// -// consumerGroups = eventHub2.listConsumerGroups(); -// -// System.out.println("Retrieved consumer groups in the seoond event hub"); -// for (EventHubConsumerGroup group : consumerGroups) { -// Utils.print(group); -// } -// -// //============================================================ -// // Create an event hub namespace with event hub -// // -// -// System.out.println("Creating an event hub namespace along with event hub"); -// -// EventHubNamespace namespace2 = azureResourceManager.eventHubNamespaces() -// .define(namespaceName2) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withNewEventHub(eventHubName2) -// .create(); -// -// System.out.println("Created an event hub namespace along with event hub"); -// Utils.print(namespace2); -// for (EventHub eh : namespace2.listEventHubs()) { -// Utils.print(eh); -// } -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().deleteByName(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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.eventhubs.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.eventhubs.models.EventHub; +import com.azure.resourcemanager.eventhubs.models.EventHubConsumerGroup; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.storage.models.StorageAccount; +import com.azure.resourcemanager.storage.models.StorageAccountSkuType; + +/** + * Azure Event Hub sample for managing event hub - + * - Create an event hub namespace + * - Create an event hub in the namespace with data capture enabled along with a consumer group and rule + * - List consumer groups in the event hub + * - Create a second event hub in the namespace + * - Create a consumer group in the second event hub + * - List consumer groups in the second event hub + * - Create an event hub namespace along with event hub. + */ +public class ManageEventHub { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String namespaceName1 = Utils.randomResourceName(azureResourceManager, "ns", 14); + final String namespaceName2 = Utils.randomResourceName(azureResourceManager, "ns", 14); + final String storageAccountName = Utils.randomResourceName(azureResourceManager, "stg", 14); + final String eventHubName1 = Utils.randomResourceName(azureResourceManager, "eh", 14); + final String eventHubName2 = Utils.randomResourceName(azureResourceManager, "eh", 14); + try { + + //============================================================ + // Create an event hub namespace + // + System.out.println("Creating a namespace"); + + EventHubNamespace namespace1 = azureResourceManager.eventHubNamespaces() + .define(namespaceName1) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .create(); + + Utils.print(namespace1); + System.out.println("Created a namespace"); + //============================================================ + // Create an event hub in the namespace with data capture enabled, with consumer group and auth rule + // + + Creatable storageAccountCreatable = azureResourceManager.storageAccounts() + .define(storageAccountName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withSku(StorageAccountSkuType.STANDARD_LRS); + + System.out.println("Creating an event hub with data capture enabled with a consumer group and rule in it"); + + EventHub eventHub1 = azureResourceManager.eventHubs() + .define(eventHubName1) + .withExistingNamespace(namespace1) + // Optional - configure data capture + .withNewStorageAccountForCapturedData(storageAccountCreatable, "datacpt") + .withDataCaptureEnabled() + // Optional - create one consumer group in event hub + .withNewConsumerGroup("cg1", "sometadata") + // Optional - create an authorization rule for event hub + .withNewListenRule("listenrule1") + .create(); + + System.out.println("Created an event hub with data capture enabled with a consumer group and rule in it"); + Utils.print(eventHub1); + + //============================================================ + // Retrieve consumer groups in the event hub + // + System.out.println("Retrieving consumer groups"); + + PagedIterable consumerGroups = eventHub1.listConsumerGroups(); + + System.out.println("Retrieved consumer groups"); + for (EventHubConsumerGroup group : consumerGroups) { + Utils.print(group); + } + + //============================================================ + // Create another event hub in the namespace using event hub accessor in namespace accessor + // + + System.out.println("Creating another event hub in the namespace"); + + EventHub eventHub2 = azureResourceManager.eventHubNamespaces() + .eventHubs() + .define(eventHubName2) + .withExistingNamespace(namespace1) + .create(); + + System.out.println("Created second event hub"); + Utils.print(eventHub2); + + //============================================================ + // Create a consumer group in the event hub using consumer group accessor in event hub accessor + // + + System.out.println("Creating a consumer group in the second event hub"); + + EventHubConsumerGroup consumerGroup2 = azureResourceManager.eventHubNamespaces() + .eventHubs() + .consumerGroups() + .define("cg2") + .withExistingEventHub(eventHub2) + // Optional + .withUserMetadata("sometadata") + .create(); + + System.out.println("Created a consumer group in the second event hub"); + Utils.print(consumerGroup2); + + //============================================================ + // Retrieve consumer groups in the event hub + // + System.out.println("Retrieving consumer groups in the second event hub"); + + consumerGroups = eventHub2.listConsumerGroups(); + + System.out.println("Retrieved consumer groups in the seoond event hub"); + for (EventHubConsumerGroup group : consumerGroups) { + Utils.print(group); + } + + //============================================================ + // Create an event hub namespace with event hub + // + + System.out.println("Creating an event hub namespace along with event hub"); + + EventHubNamespace namespace2 = azureResourceManager.eventHubNamespaces() + .define(namespaceName2) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withNewEventHub(eventHubName2) + .create(); + + System.out.println("Created an event hub namespace along with event hub"); + Utils.print(namespace2); + for (EventHub eh : namespace2.listEventHubs()) { + Utils.print(eh); + } + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().deleteByName(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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java index afb48e0fd65f..3c9f79dff554 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubEvents.java @@ -1,157 +1,157 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.eventhubs.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; -//import com.azure.resourcemanager.cosmos.models.DatabaseAccountKind; -//import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; -//import com.azure.resourcemanager.eventhubs.models.EventHubNamespaceAuthorizationRule; -//import com.azure.resourcemanager.monitor.models.DiagnosticSetting; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -// -//import java.time.Duration; -// -///** -// * Stream Azure Service Logs and Metrics for consumption through Event Hub. -// * - Create a DocumentDB instance -// * - Creates a Event Hub namespace and an Event Hub in it -// * - Retrieve the root namespace authorization rule -// * - Enable diagnostics on a existing cosmosDB to stream events to event hub -// */ -//public class ManageEventHubEvents { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final Region region = Region.US_EAST; -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgEvHb", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "ns", 24); -// final String eventHubName = "FirstEventHub"; -// String diagnosticSettingId = null; -// -// try { -// //============================================================= -// // Creates a Cosmos DB. -// // -// CosmosDBAccount docDb = azureResourceManager.cosmosDBAccounts() -// .define(namespaceName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withKind(DatabaseAccountKind.MONGO_DB) -// .withEventualConsistency() -// .withWriteReplication(Region.US_WEST) -// .withReadReplication(Region.US_CENTRAL) -// .create(); -// -// System.out.println("Created a DocumentDb instance."); -// Utils.print(docDb); -// //============================================================= -// // Creates a Event Hub namespace and an Event Hub in it. -// // -// -// System.out.println("Creating event hub namespace and event hub"); -// -// EventHubNamespace namespace = azureResourceManager.eventHubNamespaces() -// .define(namespaceName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .withNewEventHub(eventHubName) -// .create(); -// -// System.out.println(String.format("Created event hub namespace %s and event hub %s ", namespace.name(), eventHubName)); -// System.out.println(); -// Utils.print(namespace); -// -// //============================================================= -// // Retrieve the root namespace authorization rule. -// // -// -// System.out.println("Retrieving the namespace authorization rule"); -// -// EventHubNamespaceAuthorizationRule eventHubAuthRule = azureResourceManager.eventHubNamespaces().authorizationRules() -// .getByName(namespace.resourceGroupName(), namespace.name(), "RootManageSharedAccessKey"); -// -// System.out.println("Namespace authorization rule Retrieved"); -// -// //============================================================= -// // Enable diagnostics on a cosmosDB to stream events to event hub -// // -// -// System.out.println("Enabling diagnostics events of a cosmosdb to stream to event hub"); -// -// // Store Id of created Diagnostic settings only for clean-up -// DiagnosticSetting ds = azureResourceManager.diagnosticSettings() -// .define("DiaEventHub") -// .withResource(docDb.id()) -// .withEventHub(eventHubAuthRule.id(), eventHubName) -// .withLog("DataPlaneRequests", 0) -// .withLog("MongoRequests", 0) -// .withMetric("AllMetrics", Duration.ofMinutes(5), 0) -// .create(); -// -// Utils.print(ds); -// diagnosticSettingId = ds.id(); -// -// System.out.println("Streaming of diagnostics events to event hub is enabled"); -// -// //============================================================= -// // Listen for events from event hub using Event Hub dataplane APIs. -// -// return true; -// } finally { -// try { -// if (diagnosticSettingId != null) { -// System.out.println("Deleting Diagnostic Setting: " + diagnosticSettingId); -// azureResourceManager.diagnosticSettings().deleteById(diagnosticSettingId); -// } -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.eventhubs.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; +import com.azure.resourcemanager.cosmos.models.DatabaseAccountKind; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespaceAuthorizationRule; +import com.azure.resourcemanager.monitor.models.DiagnosticSetting; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; + +import java.time.Duration; + +/** + * Stream Azure Service Logs and Metrics for consumption through Event Hub. + * - Create a DocumentDB instance + * - Creates a Event Hub namespace and an Event Hub in it + * - Retrieve the root namespace authorization rule + * - Enable diagnostics on a existing cosmosDB to stream events to event hub + */ +public class ManageEventHubEvents { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final Region region = Region.US_EAST; + final String rgName = Utils.randomResourceName(azureResourceManager, "rgEvHb", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "ns", 24); + final String eventHubName = "FirstEventHub"; + String diagnosticSettingId = null; + + try { + //============================================================= + // Creates a Cosmos DB. + // + CosmosDBAccount docDb = azureResourceManager.cosmosDBAccounts() + .define(namespaceName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withKind(DatabaseAccountKind.MONGO_DB) + .withEventualConsistency() + .withWriteReplication(Region.US_WEST) + .withReadReplication(Region.US_CENTRAL) + .create(); + + System.out.println("Created a DocumentDb instance."); + Utils.print(docDb); + //============================================================= + // Creates a Event Hub namespace and an Event Hub in it. + // + + System.out.println("Creating event hub namespace and event hub"); + + EventHubNamespace namespace = azureResourceManager.eventHubNamespaces() + .define(namespaceName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withNewEventHub(eventHubName) + .create(); + + System.out.println(String.format("Created event hub namespace %s and event hub %s ", namespace.name(), eventHubName)); + System.out.println(); + Utils.print(namespace); + + //============================================================= + // Retrieve the root namespace authorization rule. + // + + System.out.println("Retrieving the namespace authorization rule"); + + EventHubNamespaceAuthorizationRule eventHubAuthRule = azureResourceManager.eventHubNamespaces().authorizationRules() + .getByName(namespace.resourceGroupName(), namespace.name(), "RootManageSharedAccessKey"); + + System.out.println("Namespace authorization rule Retrieved"); + + //============================================================= + // Enable diagnostics on a cosmosDB to stream events to event hub + // + + System.out.println("Enabling diagnostics events of a cosmosdb to stream to event hub"); + + // Store Id of created Diagnostic settings only for clean-up + DiagnosticSetting ds = azureResourceManager.diagnosticSettings() + .define("DiaEventHub") + .withResource(docDb.id()) + .withEventHub(eventHubAuthRule.id(), eventHubName) + .withLog("DataPlaneRequests", 0) + .withLog("MongoRequests", 0) + .withMetric("AllMetrics", Duration.ofMinutes(5), 0) + .create(); + + Utils.print(ds); + diagnosticSettingId = ds.id(); + + System.out.println("Streaming of diagnostics events to event hub is enabled"); + + //============================================================= + // Listen for events from event hub using Event Hub dataplane APIs. + + return true; + } finally { + try { + if (diagnosticSettingId != null) { + System.out.println("Deleting Diagnostic Setting: " + diagnosticSettingId); + azureResourceManager.diagnosticSettings().deleteById(diagnosticSettingId); + } + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java index ba0db7e0fb3a..37a7697d4bc8 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/eventhubs/samples/ManageEventHubGeoDisasterRecovery.java @@ -1,194 +1,194 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.eventhubs.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationKey; -//import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationRule; -//import com.azure.resourcemanager.eventhubs.models.EventHub; -//import com.azure.resourcemanager.eventhubs.models.EventHubDisasterRecoveryPairing; -//import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; -//import com.azure.resourcemanager.eventhubs.models.ProvisioningStateDR; -//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.resources.models.ResourceGroup; -//import com.azure.resourcemanager.samples.Utils; -// -//import java.time.Duration; -// -///** -// * Azure Event Hub sample for managing geo disaster recovery pairing - -// * - Create two event hub namespaces -// * - Create a pairing between two namespaces -// * - Create an event hub in the primary namespace and retrieve it from the secondary namespace -// * - Retrieve the pairing connection string -// * - Fail over so that secondary namespace become primary. -// */ -//public class ManageEventHubGeoDisasterRecovery { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); -// final String primaryNamespaceName = Utils.randomResourceName(azureResourceManager, "ns", 14); -// final String secondaryNamespaceName = Utils.randomResourceName(azureResourceManager, "ns", 14); -// final String geoDRName = Utils.randomResourceName(azureResourceManager, "geodr", 14); -// final String eventHubName = Utils.randomResourceName(azureResourceManager, "eh", 14); -// boolean isFailOverSucceeded = false; -// EventHubDisasterRecoveryPairing pairing = null; -// -// try { -// -// //============================================================ -// // Create resource group for the namespaces and recovery pairings -// // -// ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) -// .withRegion(Region.US_SOUTH_CENTRAL) -// .create(); -// -// System.out.println("Creating primary event hub namespace " + primaryNamespaceName); -// -// EventHubNamespace primaryNamespace = azureResourceManager.eventHubNamespaces() -// .define(primaryNamespaceName) -// .withRegion(Region.US_SOUTH_CENTRAL) -// .withExistingResourceGroup(resourceGroup) -// .create(); -// -// System.out.println("Primary event hub namespace created"); -// Utils.print(primaryNamespace); -// -// System.out.println("Creating secondary event hub namespace " + primaryNamespaceName); -// -// EventHubNamespace secondaryNamespace = azureResourceManager.eventHubNamespaces() -// .define(secondaryNamespaceName) -// .withRegion(Region.US_NORTH_CENTRAL) -// .withExistingResourceGroup(resourceGroup) -// .create(); -// -// System.out.println("Secondary event hub namespace created"); -// Utils.print(secondaryNamespace); -// -// //============================================================ -// // Create primary and secondary namespaces and recovery pairing -// // -// System.out.println("Creating geo-disaster recovery pairing " + geoDRName); -// -// pairing = azureResourceManager.eventHubDisasterRecoveryPairings() -// .define(geoDRName) -// .withExistingPrimaryNamespace(primaryNamespace) -// .withExistingSecondaryNamespace(secondaryNamespace) -// .create(); -// -// while (pairing.provisioningState() != ProvisioningStateDR.SUCCEEDED) { -// pairing = pairing.refresh(); -// ResourceManagerUtils.sleep(Duration.ofSeconds(15)); -// if (pairing.provisioningState() == ProvisioningStateDR.FAILED) { -// throw new IllegalStateException("Provisioning state of the pairing is FAILED"); -// } -// } -// -// System.out.println("Created geo-disaster recovery pairing " + geoDRName); -// Utils.print(pairing); -// -// //============================================================ -// // Create an event hub and consumer group in primary namespace -// // -// -// System.out.println("Creating an event hub and consumer group in primary namespace"); -// -// EventHub eventHubInPrimaryNamespace = azureResourceManager.eventHubs() -// .define(eventHubName) -// .withExistingNamespace(primaryNamespace) -// .withNewConsumerGroup("consumerGrp1") -// .create(); -// -// System.out.println("Created event hub and consumer group in primary namespace"); -// Utils.print(eventHubInPrimaryNamespace); -// -// System.out.println("Waiting for 60 seconds to allow metadata to sync across primary and secondary"); -// ResourceManagerUtils.sleep(Duration.ofMinutes(1)); // Wait for syncing to finish -// -// System.out.println("Retrieving the event hubs in secondary namespace"); -// -// EventHub eventHubInSecondaryNamespace = azureResourceManager.eventHubs().getByName(rgName, secondaryNamespaceName, eventHubName); -// -// System.out.println("Retrieved the event hubs in secondary namespace"); -// Utils.print(eventHubInSecondaryNamespace); -// -// //============================================================ -// // Retrieving the connection string -// // -// PagedIterable rules = pairing.listAuthorizationRules(); -// for (DisasterRecoveryPairingAuthorizationRule rule : rules) { -// DisasterRecoveryPairingAuthorizationKey key = rule.getKeys(); -// Utils.print(key); -// } -// -// System.out.println("Initiating fail over"); -// -// pairing.failOver(); -// isFailOverSucceeded = true; -// -// System.out.println("Fail over initiated"); -// return true; -// } finally { -// try { -// try { -// // It is necessary to break pairing before deleting resource group -// // -// if (pairing != null && !isFailOverSucceeded) { -// pairing.breakPairing(); -// } -// } catch (Exception ex) { -// System.out.println("Pairing breaking failed:" + ex.getMessage()); -// } -// -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.eventhubs.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationKey; +import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationRule; +import com.azure.resourcemanager.eventhubs.models.EventHub; +import com.azure.resourcemanager.eventhubs.models.EventHubDisasterRecoveryPairing; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; +import com.azure.resourcemanager.eventhubs.models.ProvisioningStateDR; +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.resources.models.ResourceGroup; +import com.azure.resourcemanager.samples.Utils; + +import java.time.Duration; + +/** + * Azure Event Hub sample for managing geo disaster recovery pairing - + * - Create two event hub namespaces + * - Create a pairing between two namespaces + * - Create an event hub in the primary namespace and retrieve it from the secondary namespace + * - Retrieve the pairing connection string + * - Fail over so that secondary namespace become primary. + */ +public class ManageEventHubGeoDisasterRecovery { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String primaryNamespaceName = Utils.randomResourceName(azureResourceManager, "ns", 14); + final String secondaryNamespaceName = Utils.randomResourceName(azureResourceManager, "ns", 14); + final String geoDRName = Utils.randomResourceName(azureResourceManager, "geodr", 14); + final String eventHubName = Utils.randomResourceName(azureResourceManager, "eh", 14); + boolean isFailOverSucceeded = false; + EventHubDisasterRecoveryPairing pairing = null; + + try { + + //============================================================ + // Create resource group for the namespaces and recovery pairings + // + ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) + .withRegion(Region.US_SOUTH_CENTRAL) + .create(); + + System.out.println("Creating primary event hub namespace " + primaryNamespaceName); + + EventHubNamespace primaryNamespace = azureResourceManager.eventHubNamespaces() + .define(primaryNamespaceName) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(resourceGroup) + .create(); + + System.out.println("Primary event hub namespace created"); + Utils.print(primaryNamespace); + + System.out.println("Creating secondary event hub namespace " + primaryNamespaceName); + + EventHubNamespace secondaryNamespace = azureResourceManager.eventHubNamespaces() + .define(secondaryNamespaceName) + .withRegion(Region.US_NORTH_CENTRAL) + .withExistingResourceGroup(resourceGroup) + .create(); + + System.out.println("Secondary event hub namespace created"); + Utils.print(secondaryNamespace); + + //============================================================ + // Create primary and secondary namespaces and recovery pairing + // + System.out.println("Creating geo-disaster recovery pairing " + geoDRName); + + pairing = azureResourceManager.eventHubDisasterRecoveryPairings() + .define(geoDRName) + .withExistingPrimaryNamespace(primaryNamespace) + .withExistingSecondaryNamespace(secondaryNamespace) + .create(); + + while (pairing.provisioningState() != ProvisioningStateDR.SUCCEEDED) { + pairing = pairing.refresh(); + ResourceManagerUtils.sleep(Duration.ofSeconds(15)); + if (pairing.provisioningState() == ProvisioningStateDR.FAILED) { + throw new IllegalStateException("Provisioning state of the pairing is FAILED"); + } + } + + System.out.println("Created geo-disaster recovery pairing " + geoDRName); + Utils.print(pairing); + + //============================================================ + // Create an event hub and consumer group in primary namespace + // + + System.out.println("Creating an event hub and consumer group in primary namespace"); + + EventHub eventHubInPrimaryNamespace = azureResourceManager.eventHubs() + .define(eventHubName) + .withExistingNamespace(primaryNamespace) + .withNewConsumerGroup("consumerGrp1") + .create(); + + System.out.println("Created event hub and consumer group in primary namespace"); + Utils.print(eventHubInPrimaryNamespace); + + System.out.println("Waiting for 60 seconds to allow metadata to sync across primary and secondary"); + ResourceManagerUtils.sleep(Duration.ofMinutes(1)); // Wait for syncing to finish + + System.out.println("Retrieving the event hubs in secondary namespace"); + + EventHub eventHubInSecondaryNamespace = azureResourceManager.eventHubs().getByName(rgName, secondaryNamespaceName, eventHubName); + + System.out.println("Retrieved the event hubs in secondary namespace"); + Utils.print(eventHubInSecondaryNamespace); + + //============================================================ + // Retrieving the connection string + // + PagedIterable rules = pairing.listAuthorizationRules(); + for (DisasterRecoveryPairingAuthorizationRule rule : rules) { + DisasterRecoveryPairingAuthorizationKey key = rule.getKeys(); + Utils.print(key); + } + + System.out.println("Initiating fail over"); + + pairing.failOver(); + isFailOverSucceeded = true; + + System.out.println("Fail over initiated"); + return true; + } finally { + try { + try { + // It is necessary to break pairing before deleting resource group + // + if (pairing != null && !isFailOverSucceeded) { + pairing.breakPairing(); + } + } catch (Exception ex) { + System.out.println("Pairing breaking failed:" + ex.getMessage()); + } + + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java index d84bedb7c2cb..26411af8fc8b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/kubernetescluster/samples/DeployImageFromContainerRegistryToKubernetes.java @@ -1,480 +1,480 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.kubernetescluster.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.containerregistry.models.AccessKeyType; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.resourcemanager.containerservice.models.AgentPoolMode; -//import com.azure.resourcemanager.containerservice.models.ContainerServiceVMSizeTypes; -//import com.azure.resourcemanager.containerservice.models.KubernetesCluster; -//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.DockerUtils; -//import com.azure.resourcemanager.samples.SSHShell; -//import com.azure.resourcemanager.samples.Utils; -//import com.github.dockerjava.api.DockerClient; -//import com.github.dockerjava.api.command.CreateContainerResponse; -//import com.github.dockerjava.api.command.PullImageResultCallback; -//import com.github.dockerjava.api.exception.NotFoundException; -//import com.github.dockerjava.api.model.AuthConfig; -//import com.github.dockerjava.api.model.Container; -//import com.github.dockerjava.api.model.Image; -//import com.github.dockerjava.core.command.PushImageResultCallback; -//import com.jcraft.jsch.JSchException; -//import io.fabric8.kubernetes.api.model.LoadBalancerIngress; -//import io.fabric8.kubernetes.api.model.Namespace; -//import io.fabric8.kubernetes.api.model.NamespaceBuilder; -//import io.fabric8.kubernetes.api.model.Pod; -//import io.fabric8.kubernetes.api.model.ReplicationController; -//import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; -//import io.fabric8.kubernetes.api.model.Secret; -//import io.fabric8.kubernetes.api.model.SecretBuilder; -//import io.fabric8.kubernetes.api.model.Service; -//import io.fabric8.kubernetes.api.model.ServiceBuilder; -//import io.fabric8.kubernetes.client.Config; -//import io.fabric8.kubernetes.client.DefaultKubernetesClient; -//import io.fabric8.kubernetes.client.KubernetesClient; -//import org.apache.commons.codec.binary.Base64; -// -//import java.io.BufferedWriter; -//import java.io.File; -//import java.io.FileOutputStream; -//import java.io.IOException; -//import java.io.OutputStreamWriter; -//import java.nio.charset.StandardCharsets; -//import java.nio.file.Files; -//import java.nio.file.Paths; -//import java.time.Duration; -//import java.util.Date; -//import java.util.HashMap; -//import java.util.List; -// -///** -// * Azure Container Registry sample for deploying a container image to Azure Container Service with Kubernetes orchestration. -// * - Create an Azure Container Registry to be used for holding the Docker images -// * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine to be used for this sample -// * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry -// * - Pull a test image from the public Docker repo (tomcat:8) to be used as a sample for pushing/pulling to/from an Azure Container Registry -// * - Create a new Docker container from an image that was pulled from Azure Container Registry -// * - Create a SSH private/public key to be used when creating a container service -// * - Create an Azure Container Service (AKS) resource -// * - Log in via the SSH client and download the Kubernetes config -// * - Create a Kubernetes client using the Kubernetes config file downloaded from one of the virtual machine managers -// * - Create a Kubernetes namespace -// * - Create a Kubernetes secret of type "docker-registry" using the Azure Container Registry credentials from above -// * - Create a Kubernetes replication controller using a container image from the Azure private registry from above and a load balancer service that will expose the app to the world -// */ -//public class DeployImageFromContainerRegistryToKubernetes { -// /** -// * Main function which runs the actual sample. -// * -// * @param azureResourceManager instance of the azure client -// * @param clientId secondary service principal client ID -// * @param secret secondary service principal secret -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, JSchException, InterruptedException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgaks", 15); -// final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); -// final String aksName = Utils.randomResourceName(azureResourceManager, "akssample", 30); -// final String rootUserName = "aksuser"; -// final Region region = Region.US_EAST; -// final String dockerImageName = "nginx"; -// final String dockerImageTag = "latest"; -// final String dockerContainerName = "acrsample-nginx"; -// String aksSecretName = "mysecret112233"; -// String aksNamespace = "acrsample"; -// String aksLbIngressName = "lb-acrsample"; -// String servicePrincipalClientId = clientId; // replace with a real service principal client id -// String servicePrincipalSecret = secret; // and corresponding secret -// -// try { -// -// //============================================================= -// // If service principal client id and secret are not set via the local variables, attempt to read the service -// // principal client id and secret from a secondary ".azureauth" file set through an environment variable. -// // -// // If the environment variable was not set then reuse the main service principal set for running this sample. -// -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { -// servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); -// servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { -// String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); -// -// if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { -// envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); -// } -// -// servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); -// servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); -// } -// } -// -// -// //============================================================= -// // Create an SSH private/public key pair to be used when creating the container service -// -// System.out.println("Creating an SSH private and public key pair"); -// -// SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); -// System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); -// System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); -// -// -// //============================================================= -// // Create an Azure Container Service (AKS) with managed Kubernetes clusters -// -// System.out.println("Creating an Azure Container Service with managed Kubernetes cluster and one agent pool with one virtual machine"); -// -// Date t1 = new Date(); -// -// KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withDefaultVersion() -// .withRootUsername(rootUserName) -// .withSshKey(sshKeys.getSshPublicKey()) -// .withServicePrincipalClientId(servicePrincipalClientId) -// .withServicePrincipalSecret(servicePrincipalSecret) -// .defineAgentPool("agentpool") -// .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) -// .withAgentPoolVirtualMachineCount(1) -// .withAgentPoolMode(AgentPoolMode.SYSTEM) -// .attach() -// .withDnsPrefix("dns-" + aksName) -// .create(); -// -// Date t2 = new Date(); -// System.out.println("Created Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); -// Utils.print(kubernetesCluster); -// -// -// //============================================================= -// // Create an Azure Container Registry to store and manage private Docker container images -// -// System.out.println("Creating an Azure Container Registry"); -// -// t1 = new Date(); -// -// Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .create(); -// -// t2 = new Date(); -// System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); -// Utils.print(azureRegistry); -// -// -// //============================================================= -// // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry -// -// RegistryCredentials acrCredentials = azureRegistry.getCredentials(); -// DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, -// azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); -// -// -// //============================================================= -// // Pull a temp image from public Docker repo and create a temporary container from that image -// // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR -// -// dockerClient.pullImageCmd(dockerImageName) -// .withTag(dockerImageTag) -// .withAuthConfig(new AuthConfig()) -// .exec(new PullImageResultCallback()) -// .awaitCompletion(); -// System.out.println("List local Docker images:"); -// List images = dockerClient.listImagesCmd().withShowAll(true).exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// -// CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) -// .withName(dockerContainerName) -// .withCmd("/hello") -// .exec(); -// System.out.println("List Docker containers:"); -// List dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// -// //============================================================= -// // Commit the new container -// -// String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; -// dockerClient.commitCmd(dockerContainerInstance.getId()) -// .withRepository(privateRepoUrl) -// .withTag("latest").exec(); -// -// // We can now remove the temporary container instance -// dockerClient.removeContainerCmd(dockerContainerInstance.getId()) -// .withForce(true) -// .exec(); -// -// -// //============================================================= -// // Push the new Docker image to the Azure Container Registry -// -// dockerClient.pushImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PushImageResultCallback()).awaitSuccess(); -// -// // Remove the temp image from the local Docker host -// try { -// dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); -// } catch (NotFoundException e) { -// // just ignore if not exist -// } -// -// -// //============================================================= -// // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally -// -// dockerClient.pullImageCmd(privateRepoUrl) -// .withAuthConfig(dockerClient.authConfig()) -// .exec(new PullImageResultCallback()).awaitCompletion(); -// System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); -// images = dockerClient.listImagesCmd() -// .withShowAll(true) -// .exec(); -// for (Image image : images) { -// System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); -// } -// dockerClient.createContainerCmd(privateRepoUrl) -// .withName(dockerContainerName + "-private") -// .withCmd("/hello").exec(); -// System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); -// dockerContainers = dockerClient.listContainersCmd() -// .withShowAll(true) -// .exec(); -// for (Container container : dockerContainers) { -// System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); -// } -// -// -// //============================================================= -// // Instantiate the Kubernetes client using the ".kube/config" file content from the Kubernetes cluster -// // The Kubernetes client API requires setting an environment variable pointing at a real file; -// // we will create a temporary file that will be deleted automatically when the sample exits -// -// kubernetesCluster = azureResourceManager.kubernetesClusters().getByResourceGroup(rgName, aksName); -// System.out.println("Found Kubernetes master at: " + kubernetesCluster.fqdn()); -// -// byte[] kubeConfigContent = kubernetesCluster.adminKubeConfigContent(); -// File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); -// tempKubeConfigFile.deleteOnExit(); -// try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { -// buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); -// } -// -// System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath()); -// Config config = new Config(); -// KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); -// -// -// //============================================================= -// // List all the nodes available in the Kubernetes cluster -// -// System.out.println(kubernetesClient.nodes().list()); -// -// -// //============================================================= -// // Create a namespace where all the sample Kubernetes resources will be created -// -// Namespace ns = new NamespaceBuilder() -// .withNewMetadata() -// .withName(aksNamespace) -// .addToLabels("acr", "sample") -// .endMetadata() -// .build(); -// try { -// System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); -// } catch (Exception e) { -// System.err.println(e.getMessage()); -// } -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) { -// System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); -// } -// -// -// //============================================================= -// // Create a secret of type "docker-repository" that will be used for downloading the container image from -// // our Azure private container repo -// -// String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); -// HashMap secretData = new HashMap<>(1); -// String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", -// azureRegistry.loginServerUrl(), -// basicAuth, -// "acrsample@azure.com"); -// -// dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); -// secretData.put(".dockercfg", dockerCfg); -// SecretBuilder secretBuilder = new SecretBuilder() -// .withNewMetadata() -// .withName(aksSecretName) -// .withNamespace(aksNamespace) -// .endMetadata() -// .withData(secretData) -// .withType("kubernetes.io/dockercfg"); -// -// System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(aksNamespace).create(secretBuilder.build())); -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// for (Secret kubeS : kubernetesClient.secrets().inNamespace(aksNamespace).list().getItems()) { -// System.out.println("\tFound secret: " + kubeS); -// } -// -// -// //============================================================= -// // Create a replication controller for our image stored in the Azure Container Registry -// -// ReplicationController rc = new ReplicationControllerBuilder() -// .withNewMetadata() -// .withName("acrsample-rc") -// .withNamespace(aksNamespace) -// .addToLabels("acrsample-nginx", "nginx") -// .endMetadata() -// .withNewSpec() -// .withReplicas(2) -// .withNewTemplate() -// .withNewMetadata() -// .addToLabels("acrsample-nginx", "nginx") -// .endMetadata() -// .withNewSpec() -// .addNewImagePullSecret(aksSecretName) -// .addNewContainer() -// .withName("acrsample-pod-nginx") -// .withImage(privateRepoUrl) -// .addNewPort() -// .withContainerPort(80) -// .endPort() -// .endContainer() -// .endSpec() -// .endTemplate() -// .endSpec() -// .build(); -// -// System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(aksNamespace).create(rc)); -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// rc = kubernetesClient.replicationControllers().inNamespace(aksNamespace).withName("acrsample-rc").get(); -// System.out.println("Found replication controller: " + rc.toString()); -// -// for (Pod pod : kubernetesClient.pods().inNamespace(aksNamespace).list().getItems()) { -// System.out.println("\tFound Kubernetes pods: " + pod.toString()); -// } -// -// -// //============================================================= -// // Create a Load Balancer service that will expose the service to the world -// -// Service lbService = new ServiceBuilder() -// .withNewMetadata() -// .withName(aksLbIngressName) -// .withNamespace(aksNamespace) -// .endMetadata() -// .withNewSpec() -// .withType("LoadBalancer") -// .addNewPort() -// .withPort(80) -// .withProtocol("TCP") -// .endPort() -// .addToSelector("acrsample-nginx", "nginx") -// .endSpec() -// .build(); -// -// System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(aksNamespace).create(lbService)); -// -// ResourceManagerUtils.sleep(Duration.ofSeconds(5)); -// -// System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get()); -// -// -// //============================================================= -// // Wait until the external IP becomes available -// -// int timeout = 30 * 60 * 1000; // 30 minutes -// String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"; -// -// while (timeout > 0) { -// try { -// List lbIngressList = kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get().getStatus().getLoadBalancer().getIngress(); -// if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { -// System.out.println("\tFound ingress IP: " + lbIngressList.get(0).getIp()); -// timeout = 0; -// } -// } catch (Exception e) { -// } -// -// if (timeout > 0) { -// timeout -= 30000; // 30 seconds -// ResourceManagerUtils.sleep(Duration.ofSeconds(30)); -// } -// } -// -// // Clean-up -// kubernetesClient.namespaces().delete(ns); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager, "", ""); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.kubernetescluster.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.resourcemanager.containerservice.models.AgentPoolMode; +import com.azure.resourcemanager.containerservice.models.ContainerServiceVMSizeTypes; +import com.azure.resourcemanager.containerservice.models.KubernetesCluster; +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.DockerUtils; +import com.azure.resourcemanager.samples.SSHShell; +import com.azure.resourcemanager.samples.Utils; +import com.github.dockerjava.api.DockerClient; +import com.github.dockerjava.api.command.CreateContainerResponse; +import com.github.dockerjava.api.command.PullImageResultCallback; +import com.github.dockerjava.api.exception.NotFoundException; +import com.github.dockerjava.api.model.AuthConfig; +import com.github.dockerjava.api.model.Container; +import com.github.dockerjava.api.model.Image; +import com.github.dockerjava.core.command.PushImageResultCallback; +import com.jcraft.jsch.JSchException; +import io.fabric8.kubernetes.api.model.LoadBalancerIngress; +import io.fabric8.kubernetes.api.model.Namespace; +import io.fabric8.kubernetes.api.model.NamespaceBuilder; +import io.fabric8.kubernetes.api.model.Pod; +import io.fabric8.kubernetes.api.model.ReplicationController; +import io.fabric8.kubernetes.api.model.ReplicationControllerBuilder; +import io.fabric8.kubernetes.api.model.Secret; +import io.fabric8.kubernetes.api.model.SecretBuilder; +import io.fabric8.kubernetes.api.model.Service; +import io.fabric8.kubernetes.api.model.ServiceBuilder; +import io.fabric8.kubernetes.client.Config; +import io.fabric8.kubernetes.client.DefaultKubernetesClient; +import io.fabric8.kubernetes.client.KubernetesClient; +import org.apache.commons.codec.binary.Base64; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStreamWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.time.Duration; +import java.util.Date; +import java.util.HashMap; +import java.util.List; + +/** + * Azure Container Registry sample for deploying a container image to Azure Container Service with Kubernetes orchestration. + * - Create an Azure Container Registry to be used for holding the Docker images + * - If a local Docker engine cannot be found, create a Linux virtual machine that will host a Docker engine to be used for this sample + * - Use Docker Java to create a Docker client that will push/pull an image to/from Azure Container Registry + * - Pull a test image from the public Docker repo (tomcat:8) to be used as a sample for pushing/pulling to/from an Azure Container Registry + * - Create a new Docker container from an image that was pulled from Azure Container Registry + * - Create a SSH private/public key to be used when creating a container service + * - Create an Azure Container Service (AKS) resource + * - Log in via the SSH client and download the Kubernetes config + * - Create a Kubernetes client using the Kubernetes config file downloaded from one of the virtual machine managers + * - Create a Kubernetes namespace + * - Create a Kubernetes secret of type "docker-registry" using the Azure Container Registry credentials from above + * - Create a Kubernetes replication controller using a container image from the Azure private registry from above and a load balancer service that will expose the app to the world + */ +public class DeployImageFromContainerRegistryToKubernetes { + /** + * Main function which runs the actual sample. + * + * @param azureResourceManager instance of the azure client + * @param clientId secondary service principal client ID + * @param secret secondary service principal secret + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId, String secret) throws IOException, JSchException, InterruptedException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgaks", 15); + final String acrName = Utils.randomResourceName(azureResourceManager, "acrsample", 20); + final String aksName = Utils.randomResourceName(azureResourceManager, "akssample", 30); + final String rootUserName = "aksuser"; + final Region region = Region.US_EAST; + final String dockerImageName = "nginx"; + final String dockerImageTag = "latest"; + final String dockerContainerName = "acrsample-nginx"; + String aksSecretName = "mysecret112233"; + String aksNamespace = "acrsample"; + String aksLbIngressName = "lb-acrsample"; + String servicePrincipalClientId = clientId; // replace with a real service principal client id + String servicePrincipalSecret = secret; // and corresponding secret + + try { + + //============================================================= + // If service principal client id and secret are not set via the local variables, attempt to read the service + // principal client id and secret from a secondary ".azureauth" file set through an environment variable. + // + // If the environment variable was not set then reuse the main service principal set for running this sample. + + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); + servicePrincipalSecret = System.getenv("AZURE_CLIENT_SECRET"); + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty() || servicePrincipalSecret == null || servicePrincipalSecret.isEmpty()) { + String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); + + if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); + } + + servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); + servicePrincipalSecret = Utils.getSecondaryServicePrincipalSecret(envSecondaryServicePrincipal); + } + } + + + //============================================================= + // Create an SSH private/public key pair to be used when creating the container service + + System.out.println("Creating an SSH private and public key pair"); + + SSHShell.SshPublicPrivateKey sshKeys = SSHShell.generateSSHKeys("", "ACS"); + System.out.println("SSH private key value: %n" + sshKeys.getSshPrivateKey()); + System.out.println("SSH public key value: %n" + sshKeys.getSshPublicKey()); + + + //============================================================= + // Create an Azure Container Service (AKS) with managed Kubernetes clusters + + System.out.println("Creating an Azure Container Service with managed Kubernetes cluster and one agent pool with one virtual machine"); + + Date t1 = new Date(); + + KubernetesCluster kubernetesCluster = azureResourceManager.kubernetesClusters().define(aksName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withDefaultVersion() + .withRootUsername(rootUserName) + .withSshKey(sshKeys.getSshPublicKey()) + .withServicePrincipalClientId(servicePrincipalClientId) + .withServicePrincipalSecret(servicePrincipalSecret) + .defineAgentPool("agentpool") + .withVirtualMachineSize(ContainerServiceVMSizeTypes.STANDARD_D2_V2) + .withAgentPoolVirtualMachineCount(1) + .withAgentPoolMode(AgentPoolMode.SYSTEM) + .attach() + .withDnsPrefix("dns-" + aksName) + .create(); + + Date t2 = new Date(); + System.out.println("Created Azure Container Service (AKS) resource: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + kubernetesCluster.id()); + Utils.print(kubernetesCluster); + + + //============================================================= + // Create an Azure Container Registry to store and manage private Docker container images + + System.out.println("Creating an Azure Container Registry"); + + t1 = new Date(); + + Registry azureRegistry = azureResourceManager.containerRegistries().define(acrName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .create(); + + t2 = new Date(); + System.out.println("Created Azure Container Registry: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + azureRegistry.id()); + Utils.print(azureRegistry); + + + //============================================================= + // Create a Docker client that will be used to push/pull images to/from the Azure Container Registry + + RegistryCredentials acrCredentials = azureRegistry.getCredentials(); + DockerClient dockerClient = DockerUtils.createDockerClient(azureResourceManager, rgName, region, + azureRegistry.loginServerUrl(), acrCredentials.username(), acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)); + + + //============================================================= + // Pull a temp image from public Docker repo and create a temporary container from that image + // These steps can be replaced and instead build a custom image using a Dockerfile and the app's JAR + + dockerClient.pullImageCmd(dockerImageName) + .withTag(dockerImageTag) + .withAuthConfig(new AuthConfig()) + .exec(new PullImageResultCallback()) + .awaitCompletion(); + System.out.println("List local Docker images:"); + List images = dockerClient.listImagesCmd().withShowAll(true).exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + + CreateContainerResponse dockerContainerInstance = dockerClient.createContainerCmd(dockerImageName + ":" + dockerImageTag) + .withName(dockerContainerName) + .withCmd("/hello") + .exec(); + System.out.println("List Docker containers:"); + List dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + + //============================================================= + // Commit the new container + + String privateRepoUrl = azureRegistry.loginServerUrl() + "/samples/" + dockerContainerName; + dockerClient.commitCmd(dockerContainerInstance.getId()) + .withRepository(privateRepoUrl) + .withTag("latest").exec(); + + // We can now remove the temporary container instance + dockerClient.removeContainerCmd(dockerContainerInstance.getId()) + .withForce(true) + .exec(); + + + //============================================================= + // Push the new Docker image to the Azure Container Registry + + dockerClient.pushImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PushImageResultCallback()).awaitSuccess(); + + // Remove the temp image from the local Docker host + try { + dockerClient.removeImageCmd(dockerImageName + ":" + dockerImageTag).withForce(true).exec(); + } catch (NotFoundException e) { + // just ignore if not exist + } + + + //============================================================= + // Verify that the image we saved in the Azure Container registry can be pulled and instantiated locally + + dockerClient.pullImageCmd(privateRepoUrl) + .withAuthConfig(dockerClient.authConfig()) + .exec(new PullImageResultCallback()).awaitCompletion(); + System.out.println("List local Docker images after pulling sample image from the Azure Container Registry:"); + images = dockerClient.listImagesCmd() + .withShowAll(true) + .exec(); + for (Image image : images) { + System.out.format("\tFound Docker image %s (%s)%n", image.getRepoTags()[0], image.getId()); + } + dockerClient.createContainerCmd(privateRepoUrl) + .withName(dockerContainerName + "-private") + .withCmd("/hello").exec(); + System.out.println("List Docker containers after instantiating container from the Azure Container Registry sample image:"); + dockerContainers = dockerClient.listContainersCmd() + .withShowAll(true) + .exec(); + for (Container container : dockerContainers) { + System.out.format("\tFound Docker container %s (%s)%n", container.getImage(), container.getId()); + } + + + //============================================================= + // Instantiate the Kubernetes client using the ".kube/config" file content from the Kubernetes cluster + // The Kubernetes client API requires setting an environment variable pointing at a real file; + // we will create a temporary file that will be deleted automatically when the sample exits + + kubernetesCluster = azureResourceManager.kubernetesClusters().getByResourceGroup(rgName, aksName); + System.out.println("Found Kubernetes master at: " + kubernetesCluster.fqdn()); + + byte[] kubeConfigContent = kubernetesCluster.adminKubeConfigContent(); + File tempKubeConfigFile = File.createTempFile("kube", ".config", new File(System.getProperty("java.io.tmpdir"))); + tempKubeConfigFile.deleteOnExit(); + try (BufferedWriter buffOut = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempKubeConfigFile), StandardCharsets.UTF_8))) { + buffOut.write(new String(kubeConfigContent, StandardCharsets.UTF_8)); + } + + System.setProperty(Config.KUBERNETES_KUBECONFIG_FILE, tempKubeConfigFile.getPath()); + Config config = new Config(); + KubernetesClient kubernetesClient = new DefaultKubernetesClient(config); + + + //============================================================= + // List all the nodes available in the Kubernetes cluster + + System.out.println(kubernetesClient.nodes().list()); + + + //============================================================= + // Create a namespace where all the sample Kubernetes resources will be created + + Namespace ns = new NamespaceBuilder() + .withNewMetadata() + .withName(aksNamespace) + .addToLabels("acr", "sample") + .endMetadata() + .build(); + try { + System.out.println("Created namespace" + kubernetesClient.namespaces().create(ns)); + } catch (Exception e) { + System.err.println(e.getMessage()); + } + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + for (Namespace namespace : kubernetesClient.namespaces().list().getItems()) { + System.out.println("\tFound Kubernetes namespace: " + namespace.toString()); + } + + + //============================================================= + // Create a secret of type "docker-repository" that will be used for downloading the container image from + // our Azure private container repo + + String basicAuth = new String(Base64.encodeBase64((acrCredentials.username() + ":" + acrCredentials.accessKeys().get(AccessKeyType.PRIMARY)).getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); + HashMap secretData = new HashMap<>(1); + String dockerCfg = String.format("{ \"%s\": { \"auth\": \"%s\", \"email\": \"%s\" } }", + azureRegistry.loginServerUrl(), + basicAuth, + "acrsample@azure.com"); + + dockerCfg = new String(Base64.encodeBase64(dockerCfg.getBytes("UTF-8")), "UTF-8"); + secretData.put(".dockercfg", dockerCfg); + SecretBuilder secretBuilder = new SecretBuilder() + .withNewMetadata() + .withName(aksSecretName) + .withNamespace(aksNamespace) + .endMetadata() + .withData(secretData) + .withType("kubernetes.io/dockercfg"); + + System.out.println("Creating new secret: " + kubernetesClient.secrets().inNamespace(aksNamespace).create(secretBuilder.build())); + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + for (Secret kubeS : kubernetesClient.secrets().inNamespace(aksNamespace).list().getItems()) { + System.out.println("\tFound secret: " + kubeS); + } + + + //============================================================= + // Create a replication controller for our image stored in the Azure Container Registry + + ReplicationController rc = new ReplicationControllerBuilder() + .withNewMetadata() + .withName("acrsample-rc") + .withNamespace(aksNamespace) + .addToLabels("acrsample-nginx", "nginx") + .endMetadata() + .withNewSpec() + .withReplicas(2) + .withNewTemplate() + .withNewMetadata() + .addToLabels("acrsample-nginx", "nginx") + .endMetadata() + .withNewSpec() + .addNewImagePullSecret(aksSecretName) + .addNewContainer() + .withName("acrsample-pod-nginx") + .withImage(privateRepoUrl) + .addNewPort() + .withContainerPort(80) + .endPort() + .endContainer() + .endSpec() + .endTemplate() + .endSpec() + .build(); + + System.out.println("Creating a replication controller: " + kubernetesClient.replicationControllers().inNamespace(aksNamespace).create(rc)); + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + rc = kubernetesClient.replicationControllers().inNamespace(aksNamespace).withName("acrsample-rc").get(); + System.out.println("Found replication controller: " + rc.toString()); + + for (Pod pod : kubernetesClient.pods().inNamespace(aksNamespace).list().getItems()) { + System.out.println("\tFound Kubernetes pods: " + pod.toString()); + } + + + //============================================================= + // Create a Load Balancer service that will expose the service to the world + + Service lbService = new ServiceBuilder() + .withNewMetadata() + .withName(aksLbIngressName) + .withNamespace(aksNamespace) + .endMetadata() + .withNewSpec() + .withType("LoadBalancer") + .addNewPort() + .withPort(80) + .withProtocol("TCP") + .endPort() + .addToSelector("acrsample-nginx", "nginx") + .endSpec() + .build(); + + System.out.println("Creating a service: " + kubernetesClient.services().inNamespace(aksNamespace).create(lbService)); + + ResourceManagerUtils.sleep(Duration.ofSeconds(5)); + + System.out.println("\tFound service: " + kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get()); + + + //============================================================= + // Wait until the external IP becomes available + + int timeout = 30 * 60 * 1000; // 30 minutes + String matchIPV4 = "^(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)(\\.(25[0-5]|2[0-4]\\d|[0-1]?\\d?\\d)){3}$"; + + while (timeout > 0) { + try { + List lbIngressList = kubernetesClient.services().inNamespace(aksNamespace).withName(aksLbIngressName).get().getStatus().getLoadBalancer().getIngress(); + if (lbIngressList != null && !lbIngressList.isEmpty() && lbIngressList.get(0) != null && lbIngressList.get(0).getIp().matches(matchIPV4)) { + System.out.println("\tFound ingress IP: " + lbIngressList.get(0).getIp()); + timeout = 0; + } + } catch (Exception e) { + } + + if (timeout > 0) { + timeout -= 30000; // 30 seconds + ResourceManagerUtils.sleep(Duration.ofSeconds(30)); + } + } + + // Clean-up + kubernetesClient.namespaces().delete(ns); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager, "", ""); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java index 97f83eee19cb..8830fd922ae4 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/privatedns/samples/ManagePrivateDns.java @@ -1,207 +1,207 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.privatedns.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.compute.models.InstanceViewStatus; -//import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; -//import com.azure.resourcemanager.compute.models.RunCommandResult; -//import com.azure.resourcemanager.compute.models.VirtualMachine; -//import com.azure.resourcemanager.network.models.Network; -//import com.azure.resourcemanager.privatedns.models.PrivateDnsZone; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.resources.models.ResourceGroup; -//import com.azure.resourcemanager.samples.Utils; -// -//import java.util.Arrays; -// -///** -// * Azure private DNS sample for managing private DNS zones. -// * - Creates a private DNS zone (private.contoso.com) -// * - Creates a virtual network -// * - Link a virtual network -// * - Creates test virtual machines -// * - Creates an additional private DNS record -// * - Test the private DNS zone -// */ -//public class ManagePrivateDns { -// -// private static final String CUSTOM_DOMAIN_NAME = "private.contoso.com"; -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); -// final String vnetName = Utils.randomResourceName(azureResourceManager, "vnetwork-1", 24); -// final String subnetName = Utils.randomResourceName(azureResourceManager, "subnet-1", 24); -// final String linkName = Utils.randomResourceName(azureResourceManager, "vnlink-1", 24); -// final String vm1Name = Utils.randomResourceName(azureResourceManager, "vm1-", 24); -// final String vm2Name = Utils.randomResourceName(azureResourceManager, "vm2-", 24); -// final String rsName = Utils.randomResourceName(azureResourceManager, "recordset1-", 24); -// final String userName = "tirekicker"; -// final String password = Utils.password(); -// -// try { -// ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) -// .withRegion(Region.US_WEST) -// .create(); -// -// //============================================================ -// // Creates a private DNS Zone -// -// System.out.println("Creating private DNS zone " + CUSTOM_DOMAIN_NAME + "..."); -// PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define(CUSTOM_DOMAIN_NAME) -// .withExistingResourceGroup(resourceGroup) -// .create(); -// -// System.out.println("Created private DNS zone " + privateDnsZone.name()); -// Utils.print(privateDnsZone); -// -// //============================================================ -// // Creates a virtual network -// -// System.out.println("Creating virtual network " + vnetName + "..."); -// Network network = azureResourceManager.networks().define(vnetName) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withAddressSpace("10.2.0.0/16") -// .withSubnet(subnetName, "10.2.0.0/24") -// .create(); -// System.out.println("Created virtual network " + network.name()); -// Utils.print(network); -// -// //============================================================ -// // Links a virtual network -// -// System.out.println("Creating virtual network link " + linkName -// + " within private zone " + privateDnsZone.name() + " ..."); -// privateDnsZone.update() -// .defineVirtualNetworkLink(linkName) -// .enableAutoRegistration() -// .withVirtualNetworkId(network.id()) -// .withETagCheck() -// .attach() -// .apply(); -// System.out.println("Linked a virtual network " + network.id()); -// -// //============================================================ -// // Creates test virtual machines -// -// System.out.println("Creating first virtual machine " + vm1Name + "..."); -// VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines().define(vm1Name) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withExistingPrimaryNetwork(network) -// .withSubnet(subnetName) -// .withPrimaryPrivateIPAddressDynamic() -// .withoutPrimaryPublicIPAddress() -// .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) -// .withAdminUsername(userName) -// .withAdminPassword(password) -// .create(); -// System.out.println("Created first virtual machine " + virtualMachine1.name()); -// Utils.print(virtualMachine1); -// -// System.out.println("Starting first virtual machine " + virtualMachine1.name() + "..."); -// virtualMachine1.start(); -// System.out.println("Started first virtual machine " + virtualMachine1.name()); -// -// System.out.println("Creating second virtual machine " + vm2Name + "..."); -// VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines().define(vm2Name) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withExistingPrimaryNetwork(network) -// .withSubnet(subnetName) -// .withPrimaryPrivateIPAddressDynamic() -// .withoutPrimaryPublicIPAddress() -// .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) -// .withAdminUsername(userName) -// .withAdminPassword(password) -// .create(); -// System.out.println("Created second virtual machine " + virtualMachine2.name()); -// -// System.out.println("Starting second virtual machine " + virtualMachine2.name() + "..."); -// virtualMachine2.start(); -// System.out.println("Started second virtual machine " + virtualMachine2.name()); -// -// //============================================================ -// // Creates an additional private DNS record -// -// System.out.println("Creating additional record set " + rsName + "..."); -// privateDnsZone.update() -// .defineARecordSet(rsName) -// .withIPv4Address(virtualMachine1.getPrimaryNetworkInterface().primaryPrivateIP()) -// .attach() -// .apply(); -// System.out.println("Created additional record set " + rsName); -// Utils.print(privateDnsZone); -// -// //============================================================ -// // Tests the private DNS zone -// -// String script1 = "New-NetFirewallRule -DisplayName \"Allow ICMPv4-In\" -Protocol ICMPv4"; -// System.out.println("Preparing first command: " + script1); -// -// String script2 = "ping " + virtualMachine1.computerName() + "." + CUSTOM_DOMAIN_NAME; -// System.out.println("Preparing second command: " + script2); -// -// String script3 = "ping " + rsName + "." + CUSTOM_DOMAIN_NAME; -// System.out.println("Preparing third command: " + script3); -// -// System.out.println("Starting to run commands..."); -// RunCommandResult result = virtualMachine2.runPowerShellScript(Arrays.asList(script1, script2, script3), null); -// for (InstanceViewStatus status : result.value()) { -// System.out.println(status.message()); -// } -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.privatedns.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.InstanceViewStatus; +import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; +import com.azure.resourcemanager.compute.models.RunCommandResult; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.privatedns.models.PrivateDnsZone; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.resources.models.ResourceGroup; +import com.azure.resourcemanager.samples.Utils; + +import java.util.Arrays; + +/** + * Azure private DNS sample for managing private DNS zones. + * - Creates a private DNS zone (private.contoso.com) + * - Creates a virtual network + * - Link a virtual network + * - Creates test virtual machines + * - Creates an additional private DNS record + * - Test the private DNS zone + */ +public class ManagePrivateDns { + + private static final String CUSTOM_DOMAIN_NAME = "private.contoso.com"; + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV", 24); + final String vnetName = Utils.randomResourceName(azureResourceManager, "vnetwork-1", 24); + final String subnetName = Utils.randomResourceName(azureResourceManager, "subnet-1", 24); + final String linkName = Utils.randomResourceName(azureResourceManager, "vnlink-1", 24); + final String vm1Name = Utils.randomResourceName(azureResourceManager, "vm1-", 24); + final String vm2Name = Utils.randomResourceName(azureResourceManager, "vm2-", 24); + final String rsName = Utils.randomResourceName(azureResourceManager, "recordset1-", 24); + final String userName = "tirekicker"; + final String password = Utils.password(); + + try { + ResourceGroup resourceGroup = azureResourceManager.resourceGroups().define(rgName) + .withRegion(Region.US_WEST) + .create(); + + //============================================================ + // Creates a private DNS Zone + + System.out.println("Creating private DNS zone " + CUSTOM_DOMAIN_NAME + "..."); + PrivateDnsZone privateDnsZone = azureResourceManager.privateDnsZones().define(CUSTOM_DOMAIN_NAME) + .withExistingResourceGroup(resourceGroup) + .create(); + + System.out.println("Created private DNS zone " + privateDnsZone.name()); + Utils.print(privateDnsZone); + + //============================================================ + // Creates a virtual network + + System.out.println("Creating virtual network " + vnetName + "..."); + Network network = azureResourceManager.networks().define(vnetName) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withAddressSpace("10.2.0.0/16") + .withSubnet(subnetName, "10.2.0.0/24") + .create(); + System.out.println("Created virtual network " + network.name()); + Utils.print(network); + + //============================================================ + // Links a virtual network + + System.out.println("Creating virtual network link " + linkName + + " within private zone " + privateDnsZone.name() + " ..."); + privateDnsZone.update() + .defineVirtualNetworkLink(linkName) + .enableAutoRegistration() + .withVirtualNetworkId(network.id()) + .withETagCheck() + .attach() + .apply(); + System.out.println("Linked a virtual network " + network.id()); + + //============================================================ + // Creates test virtual machines + + System.out.println("Creating first virtual machine " + vm1Name + "..."); + VirtualMachine virtualMachine1 = azureResourceManager.virtualMachines().define(vm1Name) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnetName) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .create(); + System.out.println("Created first virtual machine " + virtualMachine1.name()); + Utils.print(virtualMachine1); + + System.out.println("Starting first virtual machine " + virtualMachine1.name() + "..."); + virtualMachine1.start(); + System.out.println("Started first virtual machine " + virtualMachine1.name()); + + System.out.println("Creating second virtual machine " + vm2Name + "..."); + VirtualMachine virtualMachine2 = azureResourceManager.virtualMachines().define(vm2Name) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(subnetName) + .withPrimaryPrivateIPAddressDynamic() + .withoutPrimaryPublicIPAddress() + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(userName) + .withAdminPassword(password) + .create(); + System.out.println("Created second virtual machine " + virtualMachine2.name()); + + System.out.println("Starting second virtual machine " + virtualMachine2.name() + "..."); + virtualMachine2.start(); + System.out.println("Started second virtual machine " + virtualMachine2.name()); + + //============================================================ + // Creates an additional private DNS record + + System.out.println("Creating additional record set " + rsName + "..."); + privateDnsZone.update() + .defineARecordSet(rsName) + .withIPv4Address(virtualMachine1.getPrimaryNetworkInterface().primaryPrivateIP()) + .attach() + .apply(); + System.out.println("Created additional record set " + rsName); + Utils.print(privateDnsZone); + + //============================================================ + // Tests the private DNS zone + + String script1 = "New-NetFirewallRule -DisplayName \"Allow ICMPv4-In\" -Protocol ICMPv4"; + System.out.println("Preparing first command: " + script1); + + String script2 = "ping " + virtualMachine1.computerName() + "." + CUSTOM_DOMAIN_NAME; + System.out.println("Preparing second command: " + script2); + + String script3 = "ping " + rsName + "." + CUSTOM_DOMAIN_NAME; + System.out.println("Preparing third command: " + script3); + + System.out.println("Starting to run commands..."); + RunCommandResult result = virtualMachine2.runPowerShellScript(Arrays.asList(script1, script2, script3), null); + for (InstanceViewStatus status : result.value()) { + System.out.println(status.message()); + } + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java index 345e691b5fa9..1d2547352fac 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/rediscache/samples/ManageRedisCache.java @@ -1,194 +1,194 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.rediscache.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.redis.models.DayOfWeek; -//import com.azure.resourcemanager.redis.models.RebootType; -//import com.azure.resourcemanager.redis.models.RedisAccessKeys; -//import com.azure.resourcemanager.redis.models.RedisCache; -//import com.azure.resourcemanager.redis.models.RedisCachePremium; -//import com.azure.resourcemanager.redis.models.RedisKeyType; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -// -///** -// * Azure Redis sample for managing Redis Cache: -// * - Create a Redis Cache and print out hostname. -// * - Get access keys. -// * - Regenerate access keys. -// * - Create another 2 Redis Caches with Premium Sku. -// * - List all Redis Caches in a resource group – for each cache with Premium Sku: -// * - set Redis patch schedule to Monday at 5 am. -// * - update shard count. -// * - enable non-SSL port. -// * - modify max memory policy and reserved settings. -// * - restart it. -// * - Clean up all resources. -// */ -// -//public final class ManageRedisCache { -// -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String redisCacheName1 = Utils.randomResourceName(azureResourceManager, "rc1", 20); -// final String redisCacheName2 = Utils.randomResourceName(azureResourceManager, "rc2", 20); -// final String redisCacheName3 = Utils.randomResourceName(azureResourceManager, "rc3", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRCMC", 20); -// try { -// // ============================================================ -// // Define a redis cache -// -// System.out.println("Creating a Redis Cache"); -// -// Creatable redisCache1Definition = azureResourceManager.redisCaches().define(redisCacheName1) -// .withRegion(Region.US_CENTRAL) -// .withNewResourceGroup(rgName) -// .withBasicSku(); -// -// // ============================================================ -// // Define two more Redis caches -// -// Creatable redisCache2Definition = azureResourceManager.redisCaches().define(redisCacheName2) -// .withRegion(Region.US_CENTRAL) -// .withNewResourceGroup(rgName) -// .withPremiumSku() -// .withShardCount(3); -// -// Creatable redisCache3Definition = azureResourceManager.redisCaches().define(redisCacheName3) -// .withRegion(Region.US_CENTRAL) -// .withNewResourceGroup(rgName) -// .withPremiumSku(2) -// .withShardCount(3); -// -// // ============================================================ -// // Create all the caches in parallel to save time -// -// System.out.println("Creating three Redis Caches in parallel... (this will take several minutes)"); -// -// @SuppressWarnings("unchecked") -// CreatedResources createdCaches = azureResourceManager.redisCaches().create( -// redisCache1Definition, -// redisCache2Definition, -// redisCache3Definition); -// -// System.out.println("Created Redis caches:"); -// RedisCache redisCache1 = createdCaches.get(redisCache1Definition.key()); -// -// for (RedisCache redisCache : createdCaches.values()) { -// Utils.print(redisCache); -// System.out.println(); -// } -// -// // ============================================================ -// // Get | regenerate Redis Cache access keys -// -// System.out.println("Getting the first Redis cache's access keys"); -// RedisAccessKeys redisAccessKeys = redisCache1.keys(); -// Utils.print(redisAccessKeys); -// -// System.out.println("Regenerating secondary Redis cache access key"); -// redisAccessKeys = redisCache1.regenerateKey(RedisKeyType.SECONDARY); -// Utils.print(redisAccessKeys); -// -// // ============================================================ -// // List Redis Caches inside the resource group -// -// System.out.println("Listing Redis Caches"); -// -// PagedIterable caches = azureResourceManager.redisCaches().listByResourceGroup(rgName); -// -// // Walk through all the caches -// for (RedisCache redis : caches) { -// // If the instance of the Redis Cache is Premium Sku -// if (redis.isPremium()) { -// RedisCachePremium premium = redis.asPremium(); -// -// // Update each Premium Sku Redis Cache instance -// System.out.println("Updating Premium Redis Cache"); -// premium.update() -// .withPatchSchedule(DayOfWeek.MONDAY, 5) -// .withShardCount(4) -// .withNonSslPort() -// .withRedisConfiguration("maxmemory-policy", "allkeys-random") -// .withRedisConfiguration("maxmemory-reserved", "20") -// .apply(); -// -// System.out.println("Updated Redis Cache:"); -// Utils.print(premium); -// -// // Restart Redis Cache -// System.out.println("Restarting updated Redis Cache"); -// premium.forceReboot(RebootType.ALL_NODES, 1); -// -// System.out.println("Redis Cache restart scheduled"); -// } -// } -// -// // ============================================================ -// // Delete a Redis Cache -// -// System.out.println("Deleting a Redis Cache - " + redisCache1.name()); -// -// azureResourceManager.redisCaches().deleteById(redisCache1.id()); -// -// System.out.println("Deleted Redis Cache"); -// return true; -// } finally { -// if (azureResourceManager.resourceGroups().getByName(rgName) != null) { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().deleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } else { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageRedisCache() { -// } -//} +package com.azure.resourcemanager.rediscache.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.redis.models.DayOfWeek; +import com.azure.resourcemanager.redis.models.RebootType; +import com.azure.resourcemanager.redis.models.RedisAccessKeys; +import com.azure.resourcemanager.redis.models.RedisCache; +import com.azure.resourcemanager.redis.models.RedisCachePremium; +import com.azure.resourcemanager.redis.models.RedisKeyType; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.resourcemanager.resources.fluentcore.model.CreatedResources; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; + +/** + * Azure Redis sample for managing Redis Cache: + * - Create a Redis Cache and print out hostname. + * - Get access keys. + * - Regenerate access keys. + * - Create another 2 Redis Caches with Premium Sku. + * - List all Redis Caches in a resource group – for each cache with Premium Sku: + * - set Redis patch schedule to Monday at 5 am. + * - update shard count. + * - enable non-SSL port. + * - modify max memory policy and reserved settings. + * - restart it. + * - Clean up all resources. + */ + +public final class ManageRedisCache { + + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String redisCacheName1 = Utils.randomResourceName(azureResourceManager, "rc1", 20); + final String redisCacheName2 = Utils.randomResourceName(azureResourceManager, "rc2", 20); + final String redisCacheName3 = Utils.randomResourceName(azureResourceManager, "rc3", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRCMC", 20); + try { + // ============================================================ + // Define a redis cache + + System.out.println("Creating a Redis Cache"); + + Creatable redisCache1Definition = azureResourceManager.redisCaches().define(redisCacheName1) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withBasicSku(); + + // ============================================================ + // Define two more Redis caches + + Creatable redisCache2Definition = azureResourceManager.redisCaches().define(redisCacheName2) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku() + .withShardCount(3); + + Creatable redisCache3Definition = azureResourceManager.redisCaches().define(redisCacheName3) + .withRegion(Region.US_CENTRAL) + .withNewResourceGroup(rgName) + .withPremiumSku(2) + .withShardCount(3); + + // ============================================================ + // Create all the caches in parallel to save time + + System.out.println("Creating three Redis Caches in parallel... (this will take several minutes)"); + + @SuppressWarnings("unchecked") + CreatedResources createdCaches = azureResourceManager.redisCaches().create( + redisCache1Definition, + redisCache2Definition, + redisCache3Definition); + + System.out.println("Created Redis caches:"); + RedisCache redisCache1 = createdCaches.get(redisCache1Definition.key()); + + for (RedisCache redisCache : createdCaches.values()) { + Utils.print(redisCache); + System.out.println(); + } + + // ============================================================ + // Get | regenerate Redis Cache access keys + + System.out.println("Getting the first Redis cache's access keys"); + RedisAccessKeys redisAccessKeys = redisCache1.keys(); + Utils.print(redisAccessKeys); + + System.out.println("Regenerating secondary Redis cache access key"); + redisAccessKeys = redisCache1.regenerateKey(RedisKeyType.SECONDARY); + Utils.print(redisAccessKeys); + + // ============================================================ + // List Redis Caches inside the resource group + + System.out.println("Listing Redis Caches"); + + PagedIterable caches = azureResourceManager.redisCaches().listByResourceGroup(rgName); + + // Walk through all the caches + for (RedisCache redis : caches) { + // If the instance of the Redis Cache is Premium Sku + if (redis.isPremium()) { + RedisCachePremium premium = redis.asPremium(); + + // Update each Premium Sku Redis Cache instance + System.out.println("Updating Premium Redis Cache"); + premium.update() + .withPatchSchedule(DayOfWeek.MONDAY, 5) + .withShardCount(4) + .withNonSslPort() + .withRedisConfiguration("maxmemory-policy", "allkeys-random") + .withRedisConfiguration("maxmemory-reserved", "20") + .apply(); + + System.out.println("Updated Redis Cache:"); + Utils.print(premium); + + // Restart Redis Cache + System.out.println("Restarting updated Redis Cache"); + premium.forceReboot(RebootType.ALL_NODES, 1); + + System.out.println("Redis Cache restart scheduled"); + } + } + + // ============================================================ + // Delete a Redis Cache + + System.out.println("Deleting a Redis Cache - " + redisCache1.name()); + + azureResourceManager.redisCaches().deleteById(redisCache1.id()); + + System.out.println("Deleted Redis Cache"); + return true; + } finally { + if (azureResourceManager.resourceGroups().getByName(rgName) != null) { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().deleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } else { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageRedisCache() { + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java index 93a3eb756d96..f5579d40fa36 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/samples/Utils.java @@ -21,13 +21,18 @@ 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.appplatform.models.ConfigServerProperties; +import com.azure.resourcemanager.appplatform.models.ConfigServerState; +import com.azure.resourcemanager.appplatform.models.MonitoringSettingProperties; +import com.azure.resourcemanager.appplatform.models.MonitoringSettingState; +import com.azure.resourcemanager.appplatform.models.SpringApp; +import com.azure.resourcemanager.appplatform.models.SpringService; import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; import com.azure.resourcemanager.appservice.models.AppServiceDomain; import com.azure.resourcemanager.appservice.models.AppServicePlan; @@ -54,6 +59,15 @@ 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.containerinstance.models.Container; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerinstance.models.ContainerPort; +import com.azure.resourcemanager.containerinstance.models.EnvironmentVariable; +import com.azure.resourcemanager.containerinstance.models.Volume; +import com.azure.resourcemanager.containerinstance.models.VolumeMount; +import com.azure.resourcemanager.containerregistry.models.AccessKeyType; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; import com.azure.resourcemanager.containerservice.models.KubernetesCluster; import com.azure.resourcemanager.cosmos.models.CosmosDBAccount; import com.azure.resourcemanager.cosmos.models.DatabaseAccountListKeysResult; @@ -63,8 +77,8 @@ 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.MxRecord; import com.azure.resourcemanager.dns.models.NsRecordSet; import com.azure.resourcemanager.dns.models.PtrRecordSet; import com.azure.resourcemanager.dns.models.SoaRecord; @@ -73,6 +87,13 @@ 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.eventhubs.models.AccessRights; +import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationKey; +import com.azure.resourcemanager.eventhubs.models.DisasterRecoveryPairingAuthorizationRule; +import com.azure.resourcemanager.eventhubs.models.EventHub; +import com.azure.resourcemanager.eventhubs.models.EventHubConsumerGroup; +import com.azure.resourcemanager.eventhubs.models.EventHubDisasterRecoveryPairing; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespace; import com.azure.resourcemanager.keyvault.models.AccessPolicy; import com.azure.resourcemanager.keyvault.models.CertificatePermissions; import com.azure.resourcemanager.keyvault.models.KeyPermissions; @@ -140,12 +161,45 @@ 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.privatedns.models.PrivateDnsZone; +import com.azure.resourcemanager.privatedns.models.VirtualNetworkLink; +import com.azure.resourcemanager.redis.models.RedisAccessKeys; +import com.azure.resourcemanager.redis.models.RedisCache; +import com.azure.resourcemanager.redis.models.RedisCachePremium; +import com.azure.resourcemanager.redis.models.ScheduleEntry; +import com.azure.core.management.Region; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.resources.models.ResourceGroup; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.Queue; +import com.azure.resourcemanager.servicebus.models.QueueAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; +import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; +import com.azure.resourcemanager.servicebus.models.Topic; +import com.azure.resourcemanager.servicebus.models.TopicAuthorizationRule; +import com.azure.resourcemanager.sql.models.ElasticPoolActivity; +import com.azure.resourcemanager.sql.models.ElasticPoolDatabaseActivity; +import com.azure.resourcemanager.sql.models.PartnerInfo; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseMetric; +import com.azure.resourcemanager.sql.models.SqlDatabaseMetricValue; +import com.azure.resourcemanager.sql.models.SqlDatabaseUsageMetric; +import com.azure.resourcemanager.sql.models.SqlElasticPool; +import com.azure.resourcemanager.sql.models.SqlFailoverGroup; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlServerKey; +import com.azure.resourcemanager.sql.models.SqlSubscriptionUsageMetric; +import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; 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 com.azure.resourcemanager.trafficmanager.models.TrafficManagerAzureEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerExternalEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; import reactor.core.publisher.Flux; @@ -667,58 +721,58 @@ 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\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. + * + * @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("'"); + } + } + } -// /** -// * 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()); -// } + 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. @@ -1113,80 +1167,80 @@ public static void print(WebSiteBase resource) { 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 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. @@ -1322,156 +1376,156 @@ public static void print(DnsZone dnsZone) { 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 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). @@ -1690,286 +1744,286 @@ public static String cmdInvocation(String[] command, } -// /** -// * 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()); -// } + /** + * 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()); + } /** - * Print an application gateway. + * Prints information for the passed SQL Database. * - * @param resource an application gateway + * @param database database to be printed */ - public static void print(ApplicationGateway resource) { - StringBuilder info = new StringBuilder(); - info.append("Application gateway: ").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\tSKU: ").append(resource.sku().toString()) - .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\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); + 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()); - // Show IP configs - Map ipConfigs = resource.ipConfigurations(); - info.append("\n\tIP configurations: ").append(ipConfigs.size()); - 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()); - } + 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) { + StringBuilder info = new StringBuilder(); + info.append("Application gateway: ").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\tSKU: ").append(resource.sku().toString()) + .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\tDisabled SSL protocols: ").append(resource.disabledSslProtocols().toString()); + + // Show IP configs + Map ipConfigs = resource.ipConfigurations(); + info.append("\n\tIP configurations: ").append(ipConfigs.size()); + 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()); + } // Show frontends Map frontends = resource.frontends(); @@ -2244,215 +2298,215 @@ private static void uploadFileViaFtp(PublishingProfile profile, String fileName, } } -// /** -// * 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 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. @@ -2775,193 +2829,193 @@ 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()); -// -// 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()); -// } + /** + * 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()); + } /** @@ -3203,83 +3257,83 @@ public static void print(MetricAlert metricAlert) { System.out.println(info.toString()); } -// /** -// * 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()); -// } + /** + * 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. diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java index 253e0d36daed..44d3ea66a507 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeAdvanceFeatures.java @@ -1,228 +1,228 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.servicebus.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.messaging.servicebus.ServiceBusClientBuilder; -//import com.azure.messaging.servicebus.ServiceBusMessage; -//import com.azure.messaging.servicebus.ServiceBusSenderClient; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; -//import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; -//import com.azure.resourcemanager.servicebus.models.NamespaceSku; -//import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; -//import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; -//import com.azure.resourcemanager.servicebus.models.Topic; -//import com.azure.resourcemanager.servicebus.models.TopicAuthorizationRule; -// -//import java.time.Duration; -// -///** -// * Azure Service Bus basic scenario sample. -// * - Create namespace. -// * - Create a service bus subscription in the topic with session and dead-letter enabled. -// * - Create another subscription in the topic with auto deletion of idle entities. -// * - Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. -// * - Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. -// * - Get the keys from default authorization rule to connect to topic. -// * - Send a "Hello" message to topic using Data plan sdk for Service Bus. -// * - Delete a topic -// * - Delete namespace -// */ -//public final class ServiceBusPublishSubscribeAdvanceFeatures { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// // New resources -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB04_", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); -// final String topic1Name = Utils.randomResourceName(azureResourceManager, "topic1_", 24); -// final String topic2Name = Utils.randomResourceName(azureResourceManager, "topic2_", 24); -// final String subscription1Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); -// final String subscription2Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); -// final String subscription3Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); -// final String sendRuleName = "SendRule"; -// final String manageRuleName = "ManageRule"; -// -// try { -// //============================================================ -// // Create a namespace. -// -// System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); -// -// ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() -// .define(namespaceName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withSku(NamespaceSku.STANDARD) -// .withNewTopic(topic1Name, 1024) -// .create(); -// -// System.out.println("Created service bus " + serviceBusNamespace.name()); -// Utils.print(serviceBusNamespace); -// -// System.out.println("Created topic following topic along with namespace " + namespaceName); -// -// Topic firstTopic = serviceBusNamespace.topics().getByName(topic1Name); -// Utils.print(firstTopic); -// -// //============================================================ -// // Create a service bus subscription in the topic with session and dead-letter enabled. -// -// System.out.println("Creating subscription " + subscription1Name + " in topic " + topic1Name + "..."); -// ServiceBusSubscription firstSubscription = firstTopic.subscriptions().define(subscription1Name) -// .withSession() -// .withDefaultMessageTTL(Duration.ofMinutes(20)) -// .withMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20) -// .withExpiredMessageMovedToDeadLetterSubscription() -// .withMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException() -// .create(); -// System.out.println("Created subscription " + subscription1Name + " in topic " + topic1Name + "..."); -// -// Utils.print(firstSubscription); -// -// //============================================================ -// // Create another subscription in the topic with auto deletion of idle entities. -// System.out.println("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "..."); -// -// ServiceBusSubscription secondSubscription = firstTopic.subscriptions().define(subscription2Name) -// .withSession() -// .withDeleteOnIdleDurationInMinutes(20) -// .create(); -// System.out.println("Created subscription " + subscription2Name + " in topic " + topic1Name + "..."); -// -// Utils.print(secondSubscription); -// -// //============================================================ -// // Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. -// -// System.out.println("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features..."); -// -// Topic secondTopic = serviceBusNamespace.topics().define(topic2Name) -// .withNewSendRule(sendRuleName) -// .withPartitioning() -// .withNewSubscription(subscription3Name) -// .create(); -// -// System.out.println("Created second topic in namespace"); -// -// Utils.print(secondTopic); -// -// System.out.println("Creating following authorization rules in second topic "); -// -// PagedIterable authorizationRules = secondTopic.authorizationRules().list(); -// for (TopicAuthorizationRule authorizationRule: authorizationRules) { -// Utils.print(authorizationRule); -// } -// -// //============================================================ -// // Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. -// System.out.println("Updating second topic " + topic2Name + "..."); -// -// secondTopic = secondTopic.update() -// .withDeleteOnIdleDurationInMinutes(5) -// .withoutAuthorizationRule(sendRuleName) -// .withNewManageRule(manageRuleName) -// .apply(); -// -// System.out.println("Updated second topic to change its auto deletion time"); -// -// Utils.print(secondTopic); -// System.out.println("Updated following authorization rules in second topic, new list of authorization rules are "); -// -// authorizationRules = secondTopic.authorizationRules().list(); -// for (TopicAuthorizationRule authorizationRule: authorizationRules) { -// Utils.print(authorizationRule); -// } -// -// //============================================================= -// // Get connection string for default authorization rule of namespace -// -// PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); -// System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); -// -// -// for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { -// Utils.print(namespaceAuthorizationRule); -// } -// -// System.out.println("Getting keys for authorization rule ..."); -// -// AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); -// Utils.print(keys); -// -// //============================================================= -// // Send a message to topic. -// ServiceBusSenderClient sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .topicName(topic1Name) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); -// sender.close(); -// -// //============================================================= -// // Delete a topic and namespace -// System.out.println("Deleting topic " + topic1Name + "in namespace " + namespaceName + "..."); -// serviceBusNamespace.topics().deleteByName(topic1Name); -// System.out.println("Deleted topic " + topic1Name + "..."); -// -// System.out.println("Deleting namespace " + namespaceName + "..."); -// // This will delete the namespace and topic within it. -// azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); -// System.out.println("Deleted namespace " + namespaceName + "..."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.servicebus.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderClient; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.NamespaceSku; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; +import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; +import com.azure.resourcemanager.servicebus.models.Topic; +import com.azure.resourcemanager.servicebus.models.TopicAuthorizationRule; + +import java.time.Duration; + +/** + * Azure Service Bus basic scenario sample. + * - Create namespace. + * - Create a service bus subscription in the topic with session and dead-letter enabled. + * - Create another subscription in the topic with auto deletion of idle entities. + * - Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. + * - Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. + * - Get the keys from default authorization rule to connect to topic. + * - Send a "Hello" message to topic using Data plan sdk for Service Bus. + * - Delete a topic + * - Delete namespace + */ +public final class ServiceBusPublishSubscribeAdvanceFeatures { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + // New resources + final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB04_", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); + final String topic1Name = Utils.randomResourceName(azureResourceManager, "topic1_", 24); + final String topic2Name = Utils.randomResourceName(azureResourceManager, "topic2_", 24); + final String subscription1Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); + final String subscription2Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); + final String subscription3Name = Utils.randomResourceName(azureResourceManager, "subs_", 24); + final String sendRuleName = "SendRule"; + final String manageRuleName = "ManageRule"; + + try { + //============================================================ + // Create a namespace. + + System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); + + ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() + .define(namespaceName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withSku(NamespaceSku.STANDARD) + .withNewTopic(topic1Name, 1024) + .create(); + + System.out.println("Created service bus " + serviceBusNamespace.name()); + Utils.print(serviceBusNamespace); + + System.out.println("Created topic following topic along with namespace " + namespaceName); + + Topic firstTopic = serviceBusNamespace.topics().getByName(topic1Name); + Utils.print(firstTopic); + + //============================================================ + // Create a service bus subscription in the topic with session and dead-letter enabled. + + System.out.println("Creating subscription " + subscription1Name + " in topic " + topic1Name + "..."); + ServiceBusSubscription firstSubscription = firstTopic.subscriptions().define(subscription1Name) + .withSession() + .withDefaultMessageTTL(Duration.ofMinutes(20)) + .withMessageMovedToDeadLetterSubscriptionOnMaxDeliveryCount(20) + .withExpiredMessageMovedToDeadLetterSubscription() + .withMessageMovedToDeadLetterSubscriptionOnFilterEvaluationException() + .create(); + System.out.println("Created subscription " + subscription1Name + " in topic " + topic1Name + "..."); + + Utils.print(firstSubscription); + + //============================================================ + // Create another subscription in the topic with auto deletion of idle entities. + System.out.println("Creating another subscription " + subscription2Name + " in topic " + topic1Name + "..."); + + ServiceBusSubscription secondSubscription = firstTopic.subscriptions().define(subscription2Name) + .withSession() + .withDeleteOnIdleDurationInMinutes(20) + .create(); + System.out.println("Created subscription " + subscription2Name + " in topic " + topic1Name + "..."); + + Utils.print(secondSubscription); + + //============================================================ + // Create second topic with new Send Authorization rule, partitioning enabled and a new Service bus Subscription. + + System.out.println("Creating second topic " + topic2Name + ", with De-duplication and AutoDeleteOnIdle features..."); + + Topic secondTopic = serviceBusNamespace.topics().define(topic2Name) + .withNewSendRule(sendRuleName) + .withPartitioning() + .withNewSubscription(subscription3Name) + .create(); + + System.out.println("Created second topic in namespace"); + + Utils.print(secondTopic); + + System.out.println("Creating following authorization rules in second topic "); + + PagedIterable authorizationRules = secondTopic.authorizationRules().list(); + for (TopicAuthorizationRule authorizationRule: authorizationRules) { + Utils.print(authorizationRule); + } + + //============================================================ + // Update second topic to change time for AutoDeleteOnIdle time, without Send rule and with a new manage authorization rule. + System.out.println("Updating second topic " + topic2Name + "..."); + + secondTopic = secondTopic.update() + .withDeleteOnIdleDurationInMinutes(5) + .withoutAuthorizationRule(sendRuleName) + .withNewManageRule(manageRuleName) + .apply(); + + System.out.println("Updated second topic to change its auto deletion time"); + + Utils.print(secondTopic); + System.out.println("Updated following authorization rules in second topic, new list of authorization rules are "); + + authorizationRules = secondTopic.authorizationRules().list(); + for (TopicAuthorizationRule authorizationRule: authorizationRules) { + Utils.print(authorizationRule); + } + + //============================================================= + // Get connection string for default authorization rule of namespace + + PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); + System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + + + for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + Utils.print(namespaceAuthorizationRule); + } + + System.out.println("Getting keys for authorization rule ..."); + + AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); + Utils.print(keys); + + //============================================================= + // Send a message to topic. + ServiceBusSenderClient sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .topicName(topic1Name) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); + sender.close(); + + //============================================================= + // Delete a topic and namespace + System.out.println("Deleting topic " + topic1Name + "in namespace " + namespaceName + "..."); + serviceBusNamespace.topics().deleteByName(topic1Name); + System.out.println("Deleted topic " + topic1Name + "..."); + + System.out.println("Deleting namespace " + namespaceName + "..."); + // This will delete the namespace and topic within it. + azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); + System.out.println("Deleted namespace " + namespaceName + "..."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java index 078c28637348..804dc1f4d91e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusPublishSubscribeBasic.java @@ -1,212 +1,212 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.servicebus.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.messaging.servicebus.ServiceBusClientBuilder; -//import com.azure.messaging.servicebus.ServiceBusMessage; -//import com.azure.messaging.servicebus.ServiceBusSenderClient; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; -//import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; -//import com.azure.resourcemanager.servicebus.models.NamespaceSku; -//import com.azure.resourcemanager.servicebus.models.Policykey; -//import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; -//import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; -//import com.azure.resourcemanager.servicebus.models.Topic; -// -///** -// * Azure Service Bus basic scenario sample. -// * - Create namespace. -// * - Create a topic. -// * - Update topic with new size and a new ServiceBus subscription. -// * - Create another ServiceBus subscription in the topic. -// * - List topic -// * - List ServiceBus subscriptions -// * - Get default authorization rule. -// * - Regenerate the keys in the authorization rule. -// * - Send a message to topic using Data plan sdk for Service Bus. -// * - Delete one ServiceBus subscription as part of update of topic. -// * - Delete another ServiceBus subscription. -// * - Delete topic -// * - Delete namespace -// */ -//public final class ServiceBusPublishSubscribeBasic { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// // New resources -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB02_", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); -// final String topicName = Utils.randomResourceName(azureResourceManager, "topic_", 24); -// final String subscription1Name = Utils.randomResourceName(azureResourceManager, "sub1_", 24); -// final String subscription2Name = Utils.randomResourceName(azureResourceManager, "sub2_", 24); -// -// try { -// //============================================================ -// // Create a namespace. -// -// System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); -// -// ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() -// .define(namespaceName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withSku(NamespaceSku.STANDARD) -// .create(); -// -// System.out.println("Created service bus " + serviceBusNamespace.name()); -// Utils.print(serviceBusNamespace); -// -// //============================================================ -// // Create a topic in namespace -// -// System.out.println("Creating topic " + topicName + " in namespace " + namespaceName + "..."); -// -// Topic topic = serviceBusNamespace.topics().define(topicName) -// .withSizeInMB(2048) -// .create(); -// -// System.out.println("Created second queue in namespace"); -// -// Utils.print(topic); -// -// //============================================================ -// // Get and update topic with new size and a subscription -// System.out.println("Updating topic " + topicName + " with new size and a subscription..."); -// topic = serviceBusNamespace.topics().getByName(topicName); -// topic = topic.update() -// .withNewSubscription(subscription1Name) -// .withSizeInMB(3072) -// .apply(); -// -// System.out.println("Updated topic to change its size in MB along with a subscription"); -// -// Utils.print(topic); -// -// ServiceBusSubscription firstSubscription = topic.subscriptions().getByName(subscription1Name); -// Utils.print(firstSubscription); -// //============================================================ -// // Create a subscription -// System.out.println("Adding second subscription" + subscription2Name + " to topic " + topicName + "..."); -// ServiceBusSubscription secondSubscription = topic.subscriptions().define(subscription2Name).withDeleteOnIdleDurationInMinutes(10).create(); -// System.out.println("Added second subscription" + subscription2Name + " to topic " + topicName + "..."); -// -// Utils.print(secondSubscription); -// -// //============================================================= -// // List topics in namespaces -// -// PagedIterable topics = serviceBusNamespace.topics().list(); -// System.out.println("Number of topics in namespace :" + Utils.getSize(topics)); -// -// for (Topic topicInNamespace : topics) { -// Utils.print(topicInNamespace); -// } -// -// //============================================================= -// // List all subscriptions for topic in namespaces -// -// PagedIterable subscriptions = topic.subscriptions().list(); -// System.out.println("Number of subscriptions to topic: " + Utils.getSize(subscriptions)); -// -// for (ServiceBusSubscription subscription : subscriptions) { -// Utils.print(subscription); -// } -// -// //============================================================= -// // Get connection string for default authorization rule of namespace -// -// PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); -// System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); -// -// -// for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { -// Utils.print(namespaceAuthorizationRule); -// } -// -// System.out.println("Getting keys for authorization rule ..."); -// -// AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); -// Utils.print(keys); -// System.out.println("Regenerating secondary key for authorization rule ..."); -// keys = namespaceAuthorizationRules.iterator().next().regenerateKey(Policykey.SECONDARY_KEY); -// Utils.print(keys); -// -// //============================================================= -// // Send a message to topic. -// ServiceBusSenderClient sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .topicName(topicName) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); -// sender.close(); -// -// //============================================================= -// // Delete a queue and namespace -// System.out.println("Deleting subscription " + subscription1Name + " in topic " + topicName + " via update flow..."); -// topic = topic.update().withoutSubscription(subscription1Name).apply(); -// System.out.println("Deleted subscription " + subscription1Name + "..."); -// -// System.out.println("Number of subscriptions in the topic after deleting first subscription: " + topic.subscriptionCount()); -// -// System.out.println("Deleting namespace " + namespaceName + "..."); -// // This will delete the namespace and queue within it. -// azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); -// System.out.println("Deleted namespace " + namespaceName + "..."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.servicebus.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderClient; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.NamespaceSku; +import com.azure.resourcemanager.servicebus.models.Policykey; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; +import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; +import com.azure.resourcemanager.servicebus.models.Topic; + +/** + * Azure Service Bus basic scenario sample. + * - Create namespace. + * - Create a topic. + * - Update topic with new size and a new ServiceBus subscription. + * - Create another ServiceBus subscription in the topic. + * - List topic + * - List ServiceBus subscriptions + * - Get default authorization rule. + * - Regenerate the keys in the authorization rule. + * - Send a message to topic using Data plan sdk for Service Bus. + * - Delete one ServiceBus subscription as part of update of topic. + * - Delete another ServiceBus subscription. + * - Delete topic + * - Delete namespace + */ +public final class ServiceBusPublishSubscribeBasic { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + // New resources + final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB02_", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); + final String topicName = Utils.randomResourceName(azureResourceManager, "topic_", 24); + final String subscription1Name = Utils.randomResourceName(azureResourceManager, "sub1_", 24); + final String subscription2Name = Utils.randomResourceName(azureResourceManager, "sub2_", 24); + + try { + //============================================================ + // Create a namespace. + + System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); + + ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() + .define(namespaceName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withSku(NamespaceSku.STANDARD) + .create(); + + System.out.println("Created service bus " + serviceBusNamespace.name()); + Utils.print(serviceBusNamespace); + + //============================================================ + // Create a topic in namespace + + System.out.println("Creating topic " + topicName + " in namespace " + namespaceName + "..."); + + Topic topic = serviceBusNamespace.topics().define(topicName) + .withSizeInMB(2048) + .create(); + + System.out.println("Created second queue in namespace"); + + Utils.print(topic); + + //============================================================ + // Get and update topic with new size and a subscription + System.out.println("Updating topic " + topicName + " with new size and a subscription..."); + topic = serviceBusNamespace.topics().getByName(topicName); + topic = topic.update() + .withNewSubscription(subscription1Name) + .withSizeInMB(3072) + .apply(); + + System.out.println("Updated topic to change its size in MB along with a subscription"); + + Utils.print(topic); + + ServiceBusSubscription firstSubscription = topic.subscriptions().getByName(subscription1Name); + Utils.print(firstSubscription); + //============================================================ + // Create a subscription + System.out.println("Adding second subscription" + subscription2Name + " to topic " + topicName + "..."); + ServiceBusSubscription secondSubscription = topic.subscriptions().define(subscription2Name).withDeleteOnIdleDurationInMinutes(10).create(); + System.out.println("Added second subscription" + subscription2Name + " to topic " + topicName + "..."); + + Utils.print(secondSubscription); + + //============================================================= + // List topics in namespaces + + PagedIterable topics = serviceBusNamespace.topics().list(); + System.out.println("Number of topics in namespace :" + Utils.getSize(topics)); + + for (Topic topicInNamespace : topics) { + Utils.print(topicInNamespace); + } + + //============================================================= + // List all subscriptions for topic in namespaces + + PagedIterable subscriptions = topic.subscriptions().list(); + System.out.println("Number of subscriptions to topic: " + Utils.getSize(subscriptions)); + + for (ServiceBusSubscription subscription : subscriptions) { + Utils.print(subscription); + } + + //============================================================= + // Get connection string for default authorization rule of namespace + + PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); + System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + + + for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + Utils.print(namespaceAuthorizationRule); + } + + System.out.println("Getting keys for authorization rule ..."); + + AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); + Utils.print(keys); + System.out.println("Regenerating secondary key for authorization rule ..."); + keys = namespaceAuthorizationRules.iterator().next().regenerateKey(Policykey.SECONDARY_KEY); + Utils.print(keys); + + //============================================================= + // Send a message to topic. + ServiceBusSenderClient sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .topicName(topicName) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello World").setMessageId("1")); + sender.close(); + + //============================================================= + // Delete a queue and namespace + System.out.println("Deleting subscription " + subscription1Name + " in topic " + topicName + " via update flow..."); + topic = topic.update().withoutSubscription(subscription1Name).apply(); + System.out.println("Deleted subscription " + subscription1Name + "..."); + + System.out.println("Number of subscriptions in the topic after deleting first subscription: " + topic.subscriptionCount()); + + System.out.println("Deleting namespace " + namespaceName + "..."); + // This will delete the namespace and queue within it. + azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); + System.out.println("Deleted namespace " + namespaceName + "..."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java index 317422099d5a..7a82ad27aec9 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueAdvanceFeatures.java @@ -1,204 +1,204 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.servicebus.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.messaging.servicebus.ServiceBusClientBuilder; -//import com.azure.messaging.servicebus.ServiceBusMessage; -//import com.azure.messaging.servicebus.ServiceBusSenderClient; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; -//import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; -//import com.azure.resourcemanager.servicebus.models.NamespaceSku; -//import com.azure.resourcemanager.servicebus.models.Queue; -//import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; -// -//import java.time.Duration; -// -///** -// * Azure Service Bus basic scenario sample. -// * - Create namespace. -// * - Add a queue in namespace with features session and dead-lettering. -// * - Create another queue with auto-forwarding to first queue. [Remove] -// * - Create another queue with dead-letter auto-forwarding to first queue. [Remove] -// * - Create second queue with Deduplication and AutoDeleteOnIdle feature -// * - Update second queue to change time for AutoDeleteOnIdle. -// * - Update first queue to disable dead-letter forwarding and with new Send authorization rule -// * - Update queue to remove the Send Authorization rule. -// * - Get default authorization rule. -// * - Get the keys from authorization rule to connect to queue. -// * - Send a "Hello" message to queue using Data plan sdk for Service Bus. -// * - Delete queue -// * - Delete namespace -// */ -//public final class ServiceBusQueueAdvanceFeatures { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// // New resources -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB04_", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); -// final String queue1Name = Utils.randomResourceName(azureResourceManager, "queue1_", 24); -// final String queue2Name = Utils.randomResourceName(azureResourceManager, "queue2_", 24); -// final String sendRuleName = "SendRule"; -// -// try { -// //============================================================ -// // Create a namespace. -// -// System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); -// -// ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() -// .define(namespaceName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withSku(NamespaceSku.STANDARD) -// .create(); -// -// System.out.println("Created service bus " + serviceBusNamespace.name()); -// Utils.print(serviceBusNamespace); -// -// //============================================================ -// // Add a queue in namespace with features session and dead-lettering. -// System.out.println("Creating first queue " + queue1Name + ", with session, time to live and move to dead-letter queue features..."); -// -// Queue firstQueue = serviceBusNamespace.queues().define(queue1Name) -// .withSession() -// .withDefaultMessageTTL(Duration.ofMinutes(10)) -// .withExpiredMessageMovedToDeadLetterQueue() -// .withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(40) -// .create(); -// Utils.print(firstQueue); -// -// //============================================================ -// // Create second queue with Deduplication and AutoDeleteOnIdle feature -// -// System.out.println("Creating second queue " + queue2Name + ", with De-duplication and AutoDeleteOnIdle features..."); -// -// Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) -// .withSizeInMB(2048) -// .withDuplicateMessageDetection(Duration.ofMinutes(10)) -// .withDeleteOnIdleDurationInMinutes(10) -// .create(); -// -// System.out.println("Created second queue in namespace"); -// -// Utils.print(secondQueue); -// -// //============================================================ -// // Update second queue to change time for AutoDeleteOnIdle. -// -// secondQueue = secondQueue.update() -// .withDeleteOnIdleDurationInMinutes(5) -// .apply(); -// -// System.out.println("Updated second queue to change its auto deletion time"); -// -// Utils.print(secondQueue); -// -// //============================================================= -// // Update first queue to disable dead-letter forwarding and with new Send authorization rule -// secondQueue = firstQueue.update() -// .withoutExpiredMessageMovedToDeadLetterQueue() -// .withNewSendRule(sendRuleName) -// .apply(); -// -// System.out.println("Updated first queue to change dead-letter forwarding"); -// -// Utils.print(secondQueue); -// -// //============================================================= -// // Get connection string for default authorization rule of namespace -// -// PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); -// System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); -// -// -// for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { -// Utils.print(namespaceAuthorizationRule); -// } -// -// System.out.println("Getting keys for authorization rule ..."); -// -// AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); -// Utils.print(keys); -// -// //============================================================= -// // Update first queue to remove Send Authorization rule. -// firstQueue.update().withoutAuthorizationRule(sendRuleName).apply(); -// -// //============================================================= -// // Send a message to queue. -// ServiceBusSenderClient sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .queueName(queue1Name) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello").setSessionId("23424")); -// sender.close(); -// -// //============================================================= -// // Delete a queue and namespace -// System.out.println("Deleting queue " + queue1Name + "in namespace " + namespaceName + "..."); -// serviceBusNamespace.queues().deleteByName(queue1Name); -// System.out.println("Deleted queue " + queue1Name + "..."); -// -// System.out.println("Deleting namespace " + namespaceName + "..."); -// // This will delete the namespace and queue within it. -// azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); -// System.out.println("Deleted namespace " + namespaceName + "..."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.servicebus.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderClient; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.NamespaceSku; +import com.azure.resourcemanager.servicebus.models.Queue; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; + +import java.time.Duration; + +/** + * Azure Service Bus basic scenario sample. + * - Create namespace. + * - Add a queue in namespace with features session and dead-lettering. + * - Create another queue with auto-forwarding to first queue. [Remove] + * - Create another queue with dead-letter auto-forwarding to first queue. [Remove] + * - Create second queue with Deduplication and AutoDeleteOnIdle feature + * - Update second queue to change time for AutoDeleteOnIdle. + * - Update first queue to disable dead-letter forwarding and with new Send authorization rule + * - Update queue to remove the Send Authorization rule. + * - Get default authorization rule. + * - Get the keys from authorization rule to connect to queue. + * - Send a "Hello" message to queue using Data plan sdk for Service Bus. + * - Delete queue + * - Delete namespace + */ +public final class ServiceBusQueueAdvanceFeatures { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + // New resources + final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB04_", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); + final String queue1Name = Utils.randomResourceName(azureResourceManager, "queue1_", 24); + final String queue2Name = Utils.randomResourceName(azureResourceManager, "queue2_", 24); + final String sendRuleName = "SendRule"; + + try { + //============================================================ + // Create a namespace. + + System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); + + ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() + .define(namespaceName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withSku(NamespaceSku.STANDARD) + .create(); + + System.out.println("Created service bus " + serviceBusNamespace.name()); + Utils.print(serviceBusNamespace); + + //============================================================ + // Add a queue in namespace with features session and dead-lettering. + System.out.println("Creating first queue " + queue1Name + ", with session, time to live and move to dead-letter queue features..."); + + Queue firstQueue = serviceBusNamespace.queues().define(queue1Name) + .withSession() + .withDefaultMessageTTL(Duration.ofMinutes(10)) + .withExpiredMessageMovedToDeadLetterQueue() + .withMessageMovedToDeadLetterQueueOnMaxDeliveryCount(40) + .create(); + Utils.print(firstQueue); + + //============================================================ + // Create second queue with Deduplication and AutoDeleteOnIdle feature + + System.out.println("Creating second queue " + queue2Name + ", with De-duplication and AutoDeleteOnIdle features..."); + + Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) + .withSizeInMB(2048) + .withDuplicateMessageDetection(Duration.ofMinutes(10)) + .withDeleteOnIdleDurationInMinutes(10) + .create(); + + System.out.println("Created second queue in namespace"); + + Utils.print(secondQueue); + + //============================================================ + // Update second queue to change time for AutoDeleteOnIdle. + + secondQueue = secondQueue.update() + .withDeleteOnIdleDurationInMinutes(5) + .apply(); + + System.out.println("Updated second queue to change its auto deletion time"); + + Utils.print(secondQueue); + + //============================================================= + // Update first queue to disable dead-letter forwarding and with new Send authorization rule + secondQueue = firstQueue.update() + .withoutExpiredMessageMovedToDeadLetterQueue() + .withNewSendRule(sendRuleName) + .apply(); + + System.out.println("Updated first queue to change dead-letter forwarding"); + + Utils.print(secondQueue); + + //============================================================= + // Get connection string for default authorization rule of namespace + + PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); + System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + + + for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + Utils.print(namespaceAuthorizationRule); + } + + System.out.println("Getting keys for authorization rule ..."); + + AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); + Utils.print(keys); + + //============================================================= + // Update first queue to remove Send Authorization rule. + firstQueue.update().withoutAuthorizationRule(sendRuleName).apply(); + + //============================================================= + // Send a message to queue. + ServiceBusSenderClient sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queue1Name) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello").setSessionId("23424")); + sender.close(); + + //============================================================= + // Delete a queue and namespace + System.out.println("Deleting queue " + queue1Name + "in namespace " + namespaceName + "..."); + serviceBusNamespace.queues().deleteByName(queue1Name); + System.out.println("Deleted queue " + queue1Name + "..."); + + System.out.println("Deleting namespace " + namespaceName + "..."); + // This will delete the namespace and queue within it. + azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); + System.out.println("Deleted namespace " + namespaceName + "..."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java index 12733d812d93..1584706ef1ec 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusQueueBasic.java @@ -1,208 +1,208 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.servicebus.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.messaging.servicebus.ServiceBusClientBuilder; -//import com.azure.messaging.servicebus.ServiceBusMessage; -//import com.azure.messaging.servicebus.ServiceBusSenderClient; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; -//import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; -//import com.azure.resourcemanager.servicebus.models.NamespaceSku; -//import com.azure.resourcemanager.servicebus.models.Policykey; -//import com.azure.resourcemanager.servicebus.models.Queue; -//import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; -// -///** -// * Azure Service Bus basic scenario sample. -// * - Create namespace with a queue. -// * - Add another queue in same namespace. -// * - Update Queue. -// * - Update namespace -// * - List namespaces -// * - List queues -// * - Get default authorization rule. -// * - Regenerate the keys in the authorization rule. -// * - Get the keys from authorization rule to connect to queue. -// * - Send a "Hello" message to queue using Data plan sdk for Service Bus. -// * - Delete queue -// * - Delete namespace -// */ -//public final class ServiceBusQueueBasic { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// // New resources -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB01_", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); -// final String queue1Name = Utils.randomResourceName(azureResourceManager, "queue1_", 24); -// final String queue2Name = Utils.randomResourceName(azureResourceManager, "queue2_", 24); -// -// try { -// //============================================================ -// // Create a namespace. -// -// System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); -// -// ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() -// .define(namespaceName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withSku(NamespaceSku.BASIC) -// .withNewQueue(queue1Name, 1024) -// .create(); -// -// System.out.println("Created service bus " + serviceBusNamespace.name()); -// Utils.print(serviceBusNamespace); -// -// Queue firstQueue = serviceBusNamespace.queues().getByName(queue1Name); -// Utils.print(firstQueue); -// -// //============================================================ -// // Create a second queue in same namespace -// -// System.out.println("Creating second queue " + queue2Name + " in namespace " + namespaceName + "..."); -// -// Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) -// .withExpiredMessageMovedToDeadLetterQueue() -// .withSizeInMB(2048) -// .withMessageLockDurationInSeconds(20) -// .create(); -// -// System.out.println("Created second queue in namespace"); -// -// Utils.print(secondQueue); -// -// //============================================================ -// // Get and update second queue. -// -// secondQueue = serviceBusNamespace.queues().getByName(queue2Name); -// secondQueue = secondQueue.update().withSizeInMB(3072).apply(); -// -// System.out.println("Updated second queue to change its size in MB"); -// -// Utils.print(secondQueue); -// -// //============================================================= -// // Update namespace -// System.out.println("Updating sku of namespace " + serviceBusNamespace.name() + "..."); -// -// serviceBusNamespace = serviceBusNamespace -// .update() -// .withSku(NamespaceSku.STANDARD) -// .apply(); -// System.out.println("Updated sku of namespace " + serviceBusNamespace.name()); -// -// //============================================================= -// // List namespaces -// -// System.out.println("List of namespaces in resource group " + rgName + "..."); -// -// for (ServiceBusNamespace serviceBusNamespace1 : azureResourceManager.serviceBusNamespaces().listByResourceGroup(rgName)) { -// Utils.print(serviceBusNamespace1); -// } -// -// //============================================================= -// // List queues in namespaces -// -// PagedIterable queues = serviceBusNamespace.queues().list(); -// System.out.println("Number of queues in namespace :" + Utils.getSize(queues)); -// -// for (Queue queue : queues) { -// Utils.print(queue); -// } -// -// //============================================================= -// // Get connection string for default authorization rule of namespace -// -// PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); -// System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); -// -// for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { -// Utils.print(namespaceAuthorizationRule); -// } -// -// System.out.println("Getting keys for authorization rule ..."); -// -// AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); -// Utils.print(keys); -// System.out.println("Regenerating secondary key for authorization rule ..."); -// keys = namespaceAuthorizationRules.iterator().next().regenerateKey(Policykey.SECONDARY_KEY); -// Utils.print(keys); -// -// //============================================================= -// // Send a message to queue. -// ServiceBusSenderClient sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .queueName(queue1Name) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello World").setSessionId("23424")); -// sender.close(); -// -// //============================================================= -// // Delete a queue and namespace -// System.out.println("Deleting queue " + queue1Name + "in namespace " + namespaceName + "..."); -// serviceBusNamespace.queues().deleteByName(queue1Name); -// System.out.println("Deleted queue " + queue1Name + "..."); -// -// System.out.println("Deleting namespace " + namespaceName + "..."); -// // This will delete the namespace and queue within it. -// azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); -// System.out.println("Deleted namespace " + namespaceName + "..."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.servicebus.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderClient; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.NamespaceSku; +import com.azure.resourcemanager.servicebus.models.Policykey; +import com.azure.resourcemanager.servicebus.models.Queue; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; + +/** + * Azure Service Bus basic scenario sample. + * - Create namespace with a queue. + * - Add another queue in same namespace. + * - Update Queue. + * - Update namespace + * - List namespaces + * - List queues + * - Get default authorization rule. + * - Regenerate the keys in the authorization rule. + * - Get the keys from authorization rule to connect to queue. + * - Send a "Hello" message to queue using Data plan sdk for Service Bus. + * - Delete queue + * - Delete namespace + */ +public final class ServiceBusQueueBasic { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + // New resources + final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB01_", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); + final String queue1Name = Utils.randomResourceName(azureResourceManager, "queue1_", 24); + final String queue2Name = Utils.randomResourceName(azureResourceManager, "queue2_", 24); + + try { + //============================================================ + // Create a namespace. + + System.out.println("Creating name space " + namespaceName + " in resource group " + rgName + "..."); + + ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() + .define(namespaceName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withSku(NamespaceSku.BASIC) + .withNewQueue(queue1Name, 1024) + .create(); + + System.out.println("Created service bus " + serviceBusNamespace.name()); + Utils.print(serviceBusNamespace); + + Queue firstQueue = serviceBusNamespace.queues().getByName(queue1Name); + Utils.print(firstQueue); + + //============================================================ + // Create a second queue in same namespace + + System.out.println("Creating second queue " + queue2Name + " in namespace " + namespaceName + "..."); + + Queue secondQueue = serviceBusNamespace.queues().define(queue2Name) + .withExpiredMessageMovedToDeadLetterQueue() + .withSizeInMB(2048) + .withMessageLockDurationInSeconds(20) + .create(); + + System.out.println("Created second queue in namespace"); + + Utils.print(secondQueue); + + //============================================================ + // Get and update second queue. + + secondQueue = serviceBusNamespace.queues().getByName(queue2Name); + secondQueue = secondQueue.update().withSizeInMB(3072).apply(); + + System.out.println("Updated second queue to change its size in MB"); + + Utils.print(secondQueue); + + //============================================================= + // Update namespace + System.out.println("Updating sku of namespace " + serviceBusNamespace.name() + "..."); + + serviceBusNamespace = serviceBusNamespace + .update() + .withSku(NamespaceSku.STANDARD) + .apply(); + System.out.println("Updated sku of namespace " + serviceBusNamespace.name()); + + //============================================================= + // List namespaces + + System.out.println("List of namespaces in resource group " + rgName + "..."); + + for (ServiceBusNamespace serviceBusNamespace1 : azureResourceManager.serviceBusNamespaces().listByResourceGroup(rgName)) { + Utils.print(serviceBusNamespace1); + } + + //============================================================= + // List queues in namespaces + + PagedIterable queues = serviceBusNamespace.queues().list(); + System.out.println("Number of queues in namespace :" + Utils.getSize(queues)); + + for (Queue queue : queues) { + Utils.print(queue); + } + + //============================================================= + // Get connection string for default authorization rule of namespace + + PagedIterable namespaceAuthorizationRules = serviceBusNamespace.authorizationRules().list(); + System.out.println("Number of authorization rule for namespace :" + Utils.getSize(namespaceAuthorizationRules)); + + for (NamespaceAuthorizationRule namespaceAuthorizationRule: namespaceAuthorizationRules) { + Utils.print(namespaceAuthorizationRule); + } + + System.out.println("Getting keys for authorization rule ..."); + + AuthorizationKeys keys = namespaceAuthorizationRules.iterator().next().getKeys(); + Utils.print(keys); + System.out.println("Regenerating secondary key for authorization rule ..."); + keys = namespaceAuthorizationRules.iterator().next().regenerateKey(Policykey.SECONDARY_KEY); + Utils.print(keys); + + //============================================================= + // Send a message to queue. + ServiceBusSenderClient sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queue1Name) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello World").setSessionId("23424")); + sender.close(); + + //============================================================= + // Delete a queue and namespace + System.out.println("Deleting queue " + queue1Name + "in namespace " + namespaceName + "..."); + serviceBusNamespace.queues().deleteByName(queue1Name); + System.out.println("Deleted queue " + queue1Name + "..."); + + System.out.println("Deleting namespace " + namespaceName + "..."); + // This will delete the namespace and queue within it. + azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); + System.out.println("Deleted namespace " + namespaceName + "..."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java index 4b4bb3cb503d..d6f1f5fa3605 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/servicebus/samples/ServiceBusWithClaimBasedAuthorization.java @@ -1,168 +1,168 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.servicebus.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.messaging.servicebus.ServiceBusClientBuilder; -//import com.azure.messaging.servicebus.ServiceBusMessage; -//import com.azure.messaging.servicebus.ServiceBusSenderClient; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; -//import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; -//import com.azure.resourcemanager.servicebus.models.NamespaceSku; -//import com.azure.resourcemanager.servicebus.models.Queue; -//import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; -//import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; -//import com.azure.resourcemanager.servicebus.models.Topic; -// -///** -// * Azure Service Bus basic scenario sample. -// * - Create namespace with a queue and a topic -// * - Create 2 subscriptions for topic using different methods. -// * - Create send authorization rule for queue. -// * - Create send and listener authorization rule for Topic. -// * - Get the keys from authorization rule to connect to queue. -// * - Send a "Hello" message to queue using Data plan sdk for Service Bus. -// * - Send a "Hello" message to topic using Data plan sdk for Service Bus. -// * - Delete namespace -// */ -//public final class ServiceBusWithClaimBasedAuthorization { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// // New resources -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB03_", 24); -// final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); -// final String queueName = Utils.randomResourceName(azureResourceManager, "queue1_", 24); -// final String topicName = Utils.randomResourceName(azureResourceManager, "topic_", 24); -// final String subscription1Name = Utils.randomResourceName(azureResourceManager, "sub1_", 24); -// final String subscription2Name = Utils.randomResourceName(azureResourceManager, "sub2_", 24); -// -// try { -// //============================================================ -// // Create a namespace. -// -// System.out.println("Creating name space " + namespaceName + " along with a queue " + queueName + " and a topic " + topicName + " in resource group " + rgName + "..."); -// -// ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() -// .define(namespaceName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withSku(NamespaceSku.STANDARD) -// .withNewQueue(queueName, 1024) -// .withNewTopic(topicName, 1024) -// .create(); -// -// System.out.println("Created service bus " + serviceBusNamespace.name() + " (with queue and topic)"); -// Utils.print(serviceBusNamespace); -// -// Queue queue = serviceBusNamespace.queues().getByName(queueName); -// Utils.print(queue); -// -// Topic topic = serviceBusNamespace.topics().getByName(topicName); -// Utils.print(topic); -// -// //============================================================ -// // Create 2 subscriptions in topic using different methods. -// System.out.println("Creating a subscription in the topic using update on topic"); -// topic = topic.update().withNewSubscription(subscription1Name).apply(); -// -// ServiceBusSubscription subscription1 = topic.subscriptions().getByName(subscription1Name); -// -// System.out.println("Creating another subscription in the topic using direct create method for subscription"); -// ServiceBusSubscription subscription2 = topic.subscriptions().define(subscription2Name).create(); -// -// Utils.print(subscription1); -// Utils.print(subscription2); -// -// //============================================================= -// // Create new authorization rule for queue to send message. -// System.out.println("Create authorization rule for queue ..."); -// NamespaceAuthorizationRule sendQueueAuthorizationRule = serviceBusNamespace.authorizationRules().define("SendRule").withSendingEnabled().create(); -// Utils.print(sendQueueAuthorizationRule); -// -// System.out.println("Getting keys for authorization rule ..."); -// AuthorizationKeys keys = sendQueueAuthorizationRule.getKeys(); -// Utils.print(keys); -// -// //============================================================= -// // Send a message to queue. -// ServiceBusSenderClient sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .queueName(queueName) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello").setMessageId("1")); -// sender.close(); -// -// -// //============================================================= -// // Send a message to topic. -// sender = new ServiceBusClientBuilder() -// .connectionString(keys.primaryConnectionString()) -// .sender() -// .topicName(topicName) -// .buildClient(); -// sender.sendMessage(new ServiceBusMessage("Hello").setMessageId("1")); -// sender.close(); -// -// //============================================================= -// // Delete a namespace -// System.out.println("Deleting namespace " + namespaceName + " [topic, queues and subscription will delete along with that]..."); -// // This will delete the namespace and queue within it. -// azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); -// System.out.println("Deleted namespace " + namespaceName + "..."); -// -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// -// /** -// * Main entry point. -// * -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.servicebus.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.messaging.servicebus.ServiceBusClientBuilder; +import com.azure.messaging.servicebus.ServiceBusMessage; +import com.azure.messaging.servicebus.ServiceBusSenderClient; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.servicebus.models.AuthorizationKeys; +import com.azure.resourcemanager.servicebus.models.NamespaceAuthorizationRule; +import com.azure.resourcemanager.servicebus.models.NamespaceSku; +import com.azure.resourcemanager.servicebus.models.Queue; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespace; +import com.azure.resourcemanager.servicebus.models.ServiceBusSubscription; +import com.azure.resourcemanager.servicebus.models.Topic; + +/** + * Azure Service Bus basic scenario sample. + * - Create namespace with a queue and a topic + * - Create 2 subscriptions for topic using different methods. + * - Create send authorization rule for queue. + * - Create send and listener authorization rule for Topic. + * - Get the keys from authorization rule to connect to queue. + * - Send a "Hello" message to queue using Data plan sdk for Service Bus. + * - Send a "Hello" message to topic using Data plan sdk for Service Bus. + * - Delete namespace + */ +public final class ServiceBusWithClaimBasedAuthorization { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + // New resources + final String rgName = Utils.randomResourceName(azureResourceManager, "rgSB03_", 24); + final String namespaceName = Utils.randomResourceName(azureResourceManager, "namespace", 20); + final String queueName = Utils.randomResourceName(azureResourceManager, "queue1_", 24); + final String topicName = Utils.randomResourceName(azureResourceManager, "topic_", 24); + final String subscription1Name = Utils.randomResourceName(azureResourceManager, "sub1_", 24); + final String subscription2Name = Utils.randomResourceName(azureResourceManager, "sub2_", 24); + + try { + //============================================================ + // Create a namespace. + + System.out.println("Creating name space " + namespaceName + " along with a queue " + queueName + " and a topic " + topicName + " in resource group " + rgName + "..."); + + ServiceBusNamespace serviceBusNamespace = azureResourceManager.serviceBusNamespaces() + .define(namespaceName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withSku(NamespaceSku.STANDARD) + .withNewQueue(queueName, 1024) + .withNewTopic(topicName, 1024) + .create(); + + System.out.println("Created service bus " + serviceBusNamespace.name() + " (with queue and topic)"); + Utils.print(serviceBusNamespace); + + Queue queue = serviceBusNamespace.queues().getByName(queueName); + Utils.print(queue); + + Topic topic = serviceBusNamespace.topics().getByName(topicName); + Utils.print(topic); + + //============================================================ + // Create 2 subscriptions in topic using different methods. + System.out.println("Creating a subscription in the topic using update on topic"); + topic = topic.update().withNewSubscription(subscription1Name).apply(); + + ServiceBusSubscription subscription1 = topic.subscriptions().getByName(subscription1Name); + + System.out.println("Creating another subscription in the topic using direct create method for subscription"); + ServiceBusSubscription subscription2 = topic.subscriptions().define(subscription2Name).create(); + + Utils.print(subscription1); + Utils.print(subscription2); + + //============================================================= + // Create new authorization rule for queue to send message. + System.out.println("Create authorization rule for queue ..."); + NamespaceAuthorizationRule sendQueueAuthorizationRule = serviceBusNamespace.authorizationRules().define("SendRule").withSendingEnabled().create(); + Utils.print(sendQueueAuthorizationRule); + + System.out.println("Getting keys for authorization rule ..."); + AuthorizationKeys keys = sendQueueAuthorizationRule.getKeys(); + Utils.print(keys); + + //============================================================= + // Send a message to queue. + ServiceBusSenderClient sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .queueName(queueName) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello").setMessageId("1")); + sender.close(); + + + //============================================================= + // Send a message to topic. + sender = new ServiceBusClientBuilder() + .connectionString(keys.primaryConnectionString()) + .sender() + .topicName(topicName) + .buildClient(); + sender.sendMessage(new ServiceBusMessage("Hello").setMessageId("1")); + sender.close(); + + //============================================================= + // Delete a namespace + System.out.println("Deleting namespace " + namespaceName + " [topic, queues and subscription will delete along with that]..."); + // This will delete the namespace and queue within it. + azureResourceManager.serviceBusNamespaces().deleteById(serviceBusNamespace.id()); + System.out.println("Deleted namespace " + namespaceName + "..."); + + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + + /** + * Main entry point. + * + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/GettingSqlServerMetrics.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/GettingSqlServerMetrics.java index 457403b4dcd0..0e9c7de77bc5 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/GettingSqlServerMetrics.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/GettingSqlServerMetrics.java @@ -1,353 +1,353 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.monitor.fluent.models.MetadataValueInner; -//import com.azure.resourcemanager.monitor.models.Metric; -//import com.azure.resourcemanager.monitor.models.MetricCollection; -//import com.azure.resourcemanager.monitor.models.MetricDefinition; -//import com.azure.resourcemanager.monitor.models.MetricValue; -//import com.azure.resourcemanager.monitor.models.TimeSeriesElement; -//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.resourcemanager.sql.models.SampleName; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlDatabaseMetric; -//import com.azure.resourcemanager.sql.models.SqlDatabaseUsageMetric; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlSubscriptionUsageMetric; -// -//import java.sql.Connection; -//import java.sql.DriverManager; -//import java.sql.PreparedStatement; -//import java.sql.ResultSet; -//import java.sql.SQLException; -//import java.sql.Statement; -//import java.time.Duration; -//import java.time.OffsetDateTime; -//import java.util.List; -// -///** -// * Azure SQL sample for getting SQL Server and Databases metrics -// * - Create a primary SQL Server with a sample database. -// * - Run some queries on the sample database. -// * - Create a new table and insert some values into the database. -// * - List the SQL subscription usage metrics, the database usage metrics and the other database metrics -// * - Use the Monitor Service Fluent APIs to list the SQL Server metrics and the SQL Database metrics -// * - Delete Sql Server -// */ -//public class GettingSqlServerMetrics { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws ClassNotFoundException, SQLException { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqltest", 20); -// final String dbName = "dbSample"; -// final String epName = "epSample"; -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// OffsetDateTime startTime = OffsetDateTime.now().minusDays(1); -// -// try { -// // Check if the expected SQL driver is available -// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); -// -// // ============================================================ -// // Create a SQL Server. -// System.out.println("Creating a SQL server to be used for getting various metrics"); -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineFirewallRule("allowAll") -// .withIpAddressRange("0.0.0.1", "255.255.255.255") -// .attach() -// .defineElasticPool(epName) -// .withStandardPool() -// .attach() -// .defineDatabase(dbName) -// .withExistingElasticPool(epName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .attach() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // Create a connection to the SQL Server. -// System.out.println("Creating a connection to the SQL Server"); -// String connectionToSqlTestUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", -// sqlServer.fullyQualifiedDomainName(), -// dbName, -// administratorLogin, -// administratorPassword); -// -// // Establish the connection. -// try (Connection connection = DriverManager.getConnection(connectionToSqlTestUrl); -// Statement statement = connection.createStatement();) { -// -// // ============================================================ -// // Create and execute a "select" SQL statement on the sample database. -// System.out.println("Creating and executing a \"SELECT\" SQL statement on the sample database"); -// -// String selectSql = "SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"; -// -// System.out.println("SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"); -// try (ResultSet resultSet = statement.executeQuery(selectSql);) { -// -// // Print results from select statement -// while (resultSet.next()) { -// System.out.println(resultSet.getString(2) + " " -// + resultSet.getString(3)); -// } -// } -// -// // ============================================================ -// // Create and execute an "INSERT" SQL statement on the sample database. -// System.out.println("Creating and executing an \"INSERT\" SQL statement on the sample database"); -// // Create and execute an INSERT SQL prepared statement. -// String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES " -// + "('Bike', 'B1', 'Blue', 50, 120, '2016-01-01');"; -// -// try (PreparedStatement prepsInsertProduct = connection.prepareStatement( -// insertSql, -// Statement.RETURN_GENERATED_KEYS);) { -// prepsInsertProduct.execute(); -// -// // Retrieve the generated key from the insert. -// try (ResultSet resultSet2 = prepsInsertProduct.getGeneratedKeys();) { -// // Print the ID of the inserted row. -// while (resultSet2.next()) { -// System.out.println("Generated: " + resultSet2.getString(1)); -// } -// } -// } -// -// // ============================================================ -// // Create a new table into the SQL Server database and insert one value. -// System.out.println("Creating a new table into the SQL Server database and insert one value"); -// -// try (Statement stmt = connection.createStatement();) { -// -// String sqlCommand = "CREATE TABLE [Sample_Test] ([Name] [varchar](30) NOT NULL)"; -// stmt.execute(sqlCommand); -// -// sqlCommand = "INSERT Sample_Test VALUES ('Test')"; -// stmt.execute(sqlCommand); -// -// // ============================================================ -// // Run a "select" query for the new table. -// System.out.println("Running a \"SELECT\" query for the new table"); -// -// sqlCommand = "SELECT * FROM Sample_Test;"; -// try (ResultSet resultSet = stmt.executeQuery(sqlCommand);) { -// // Print results from select statement -// System.out.println("SELECT * FROM Sample_Test"); -// while (resultSet.next()) { -// System.out.format("\t%s%n", resultSet.getString(1)); -// } -// } -// } -// } -// -// ResourceManagerUtils.sleep(Duration.ofMinutes(6)); -// -// -// // ============================================================ -// // List the SQL subscription usage metrics for the current selected region. -// System.out.println("Listing the SQL subscription usage metrics for the current selected region"); -// -// -// List subscriptionUsageMetrics = azureResourceManager.sqlServers().listUsageByRegion(Region.US_EAST); -// for (SqlSubscriptionUsageMetric usageMetric : subscriptionUsageMetrics) { -// Utils.print(usageMetric); -// } -// -// // ============================================================ -// // List the SQL database usage metrics for the sample database. -// System.out.println("Listing the SQL database usage metrics for the sample database"); -// -// SqlDatabase db = sqlServer.databases().get(dbName); -// -// List databaseUsageMetrics = db.listUsageMetrics(); -// for (SqlDatabaseUsageMetric usageMetric : databaseUsageMetrics) { -// Utils.print(usageMetric); -// } -// -// // ============================================================ -// // List the SQL database CPU metrics for the sample database. -// System.out.println("Listing the SQL database CPU metrics for the sample database"); -// -// OffsetDateTime endTime = OffsetDateTime.now(); -// String filter = String.format("name/value eq 'cpu_percent' and startTime eq '%s' and endTime eq '%s'", startTime.toInstant(), endTime.toInstant()); -// -// List dbMetrics = db.listMetrics(filter); -// for (SqlDatabaseMetric metric : dbMetrics) { -// Utils.print(metric); -// } -// -// // ============================================================ -// // List the SQL database metrics for the sample database. -// System.out.println("Listing the SQL database metrics for the sample database"); -// -// endTime = OffsetDateTime.now(); -// filter = String.format("startTime eq '%s' and endTime eq '%s'", startTime.toInstant(), endTime.toInstant()); -// -// dbMetrics = db.listMetrics(filter); -// for (SqlDatabaseMetric metric : dbMetrics) { -// Utils.print(metric); -// } -// -// // ============================================================ -// // Use Monitor Service to list the SQL server metrics. -// -// System.out.println("Using Monitor Service to list the SQL server metrics"); -// PagedIterable metricDefinitions = azureResourceManager.metricDefinitions().listByResource(sqlServer.id()); -// -// for (MetricDefinition metricDefinition : metricDefinitions) { -// // find metric definition for "DTU used" and "Storage used" -// if (metricDefinition.name().localizedValue().equalsIgnoreCase("dtu used") -// || metricDefinition.name().localizedValue().equalsIgnoreCase("storage used")) { -// // get metric records -// MetricCollection metricCollection = metricDefinition.defineQuery() -// .startingFrom(startTime) -// .endsBefore(endTime) -// .withAggregation("Average") -// .withInterval(Duration.ofMinutes(5)) -// .withOdataFilter(String.format("DatabaseResourceId eq '%s'", db.id())) -// .execute(); -// -// System.out.format("SQL server \"%s\" %s metrics%n", sqlServer.name(), metricDefinition.name().localizedValue()); -// System.out.println("\tNamespace: " + metricCollection.namespace()); -// System.out.println("\tQuery time: " + metricCollection.timespan()); -// System.out.println("\tTime Grain: " + metricCollection.interval()); -// System.out.println("\tCost: " + metricCollection.cost()); -// -// for (Metric metric : metricCollection.metrics()) { -// System.out.println("\tMetric: " + metric.name().localizedValue()); -// System.out.println("\tType: " + metric.type()); -// System.out.println("\tUnit: " + metric.unit()); -// System.out.println("\tTime Series: "); -// for (TimeSeriesElement timeElement : metric.timeseries()) { -// System.out.println("\t\tMetadata: "); -// for (MetadataValueInner metadata : timeElement.metadatavalues()) { -// System.out.println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); -// } -// System.out.println("\t\tData: "); -// for (MetricValue data : timeElement.data()) { -// System.out.println("\t\t\t" + data.timestamp() -// + " : (Min) " + data.minimum() -// + " : (Max) " + data.maximum() -// + " : (Avg) " + data.average() -// + " : (Total) " + data.total() -// + " : (Count) " + data.count()); -// } -// } -// } -// break; -// } -// } -// -// // ============================================================ -// // Use Monitor Service to list the SQL Database metrics. -// System.out.println("Using Monitor Service to list the SQL Database metrics"); -// metricDefinitions = azureResourceManager.metricDefinitions().listByResource(db.id()); -// -// for (MetricDefinition metricDefinition : metricDefinitions) { -// // find metric definition for Transactions -// if (metricDefinition.name().localizedValue().equalsIgnoreCase("dtu used") -// || metricDefinition.name().localizedValue().equalsIgnoreCase("cpu used") -// || metricDefinition.name().localizedValue().equalsIgnoreCase("storage used")) { -// // get metric records -// MetricCollection metricCollection = metricDefinition.defineQuery() -// .startingFrom(startTime) -// .endsBefore(endTime) -// .execute(); -// -// System.out.println("Metrics for '" + db.id() + "':"); -// System.out.println("Namespace: " + metricCollection.namespace()); -// System.out.println("Query time: " + metricCollection.timespan()); -// System.out.println("Time Grain: " + metricCollection.interval()); -// System.out.println("Cost: " + metricCollection.cost()); -// -// for (Metric metric : metricCollection.metrics()) { -// System.out.println("\tMetric: " + metric.name().localizedValue()); -// System.out.println("\tType: " + metric.type()); -// System.out.println("\tUnit: " + metric.unit()); -// System.out.println("\tTime Series: "); -// for (TimeSeriesElement timeElement : metric.timeseries()) { -// System.out.println("\t\tMetadata: "); -// for (MetadataValueInner metadata : timeElement.metadatavalues()) { -// System.out.println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); -// } -// System.out.println("\t\tData: "); -// for (MetricValue data : timeElement.data()) { -// System.out.println("\t\t\t" + data.timestamp() -// + " : (Min) " + data.minimum() -// + " : (Max) " + data.maximum() -// + " : (Avg) " + data.average() -// + " : (Total) " + data.total() -// + " : (Count) " + data.count()); -// } -// } -// } -// break; -// } -// } -// -// // Delete the SQL Servers. -// System.out.println("Deleting the Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.monitor.fluent.models.MetadataValueInner; +import com.azure.resourcemanager.monitor.models.Metric; +import com.azure.resourcemanager.monitor.models.MetricCollection; +import com.azure.resourcemanager.monitor.models.MetricDefinition; +import com.azure.resourcemanager.monitor.models.MetricValue; +import com.azure.resourcemanager.monitor.models.TimeSeriesElement; +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.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseMetric; +import com.azure.resourcemanager.sql.models.SqlDatabaseUsageMetric; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlSubscriptionUsageMetric; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; +import java.time.OffsetDateTime; +import java.util.List; + +/** + * Azure SQL sample for getting SQL Server and Databases metrics + * - Create a primary SQL Server with a sample database. + * - Run some queries on the sample database. + * - Create a new table and insert some values into the database. + * - List the SQL subscription usage metrics, the database usage metrics and the other database metrics + * - Use the Monitor Service Fluent APIs to list the SQL Server metrics and the SQL Database metrics + * - Delete Sql Server + */ +public class GettingSqlServerMetrics { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws ClassNotFoundException, SQLException { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqltest", 20); + final String dbName = "dbSample"; + final String epName = "epSample"; + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + OffsetDateTime startTime = OffsetDateTime.now().minusDays(1); + + try { + // Check if the expected SQL driver is available + Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); + + // ============================================================ + // Create a SQL Server. + System.out.println("Creating a SQL server to be used for getting various metrics"); + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("allowAll") + .withIpAddressRange("0.0.0.1", "255.255.255.255") + .attach() + .defineElasticPool(epName) + .withStandardPool() + .attach() + .defineDatabase(dbName) + .withExistingElasticPool(epName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .attach() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // Create a connection to the SQL Server. + System.out.println("Creating a connection to the SQL Server"); + String connectionToSqlTestUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", + sqlServer.fullyQualifiedDomainName(), + dbName, + administratorLogin, + administratorPassword); + + // Establish the connection. + try (Connection connection = DriverManager.getConnection(connectionToSqlTestUrl); + Statement statement = connection.createStatement();) { + + // ============================================================ + // Create and execute a "select" SQL statement on the sample database. + System.out.println("Creating and executing a \"SELECT\" SQL statement on the sample database"); + + String selectSql = "SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"; + + System.out.println("SELECT TOP 10 Title, FirstName, LastName from SalesLT.Customer"); + try (ResultSet resultSet = statement.executeQuery(selectSql);) { + + // Print results from select statement + while (resultSet.next()) { + System.out.println(resultSet.getString(2) + " " + + resultSet.getString(3)); + } + } + + // ============================================================ + // Create and execute an "INSERT" SQL statement on the sample database. + System.out.println("Creating and executing an \"INSERT\" SQL statement on the sample database"); + // Create and execute an INSERT SQL prepared statement. + String insertSql = "INSERT INTO SalesLT.Product (Name, ProductNumber, Color, StandardCost, ListPrice, SellStartDate) VALUES " + + "('Bike', 'B1', 'Blue', 50, 120, '2016-01-01');"; + + try (PreparedStatement prepsInsertProduct = connection.prepareStatement( + insertSql, + Statement.RETURN_GENERATED_KEYS);) { + prepsInsertProduct.execute(); + + // Retrieve the generated key from the insert. + try (ResultSet resultSet2 = prepsInsertProduct.getGeneratedKeys();) { + // Print the ID of the inserted row. + while (resultSet2.next()) { + System.out.println("Generated: " + resultSet2.getString(1)); + } + } + } + + // ============================================================ + // Create a new table into the SQL Server database and insert one value. + System.out.println("Creating a new table into the SQL Server database and insert one value"); + + try (Statement stmt = connection.createStatement();) { + + String sqlCommand = "CREATE TABLE [Sample_Test] ([Name] [varchar](30) NOT NULL)"; + stmt.execute(sqlCommand); + + sqlCommand = "INSERT Sample_Test VALUES ('Test')"; + stmt.execute(sqlCommand); + + // ============================================================ + // Run a "select" query for the new table. + System.out.println("Running a \"SELECT\" query for the new table"); + + sqlCommand = "SELECT * FROM Sample_Test;"; + try (ResultSet resultSet = stmt.executeQuery(sqlCommand);) { + // Print results from select statement + System.out.println("SELECT * FROM Sample_Test"); + while (resultSet.next()) { + System.out.format("\t%s%n", resultSet.getString(1)); + } + } + } + } + + ResourceManagerUtils.sleep(Duration.ofMinutes(6)); + + + // ============================================================ + // List the SQL subscription usage metrics for the current selected region. + System.out.println("Listing the SQL subscription usage metrics for the current selected region"); + + + List subscriptionUsageMetrics = azureResourceManager.sqlServers().listUsageByRegion(Region.US_EAST); + for (SqlSubscriptionUsageMetric usageMetric : subscriptionUsageMetrics) { + Utils.print(usageMetric); + } + + // ============================================================ + // List the SQL database usage metrics for the sample database. + System.out.println("Listing the SQL database usage metrics for the sample database"); + + SqlDatabase db = sqlServer.databases().get(dbName); + + List databaseUsageMetrics = db.listUsageMetrics(); + for (SqlDatabaseUsageMetric usageMetric : databaseUsageMetrics) { + Utils.print(usageMetric); + } + + // ============================================================ + // List the SQL database CPU metrics for the sample database. + System.out.println("Listing the SQL database CPU metrics for the sample database"); + + OffsetDateTime endTime = OffsetDateTime.now(); + String filter = String.format("name/value eq 'cpu_percent' and startTime eq '%s' and endTime eq '%s'", startTime.toInstant(), endTime.toInstant()); + + List dbMetrics = db.listMetrics(filter); + for (SqlDatabaseMetric metric : dbMetrics) { + Utils.print(metric); + } + + // ============================================================ + // List the SQL database metrics for the sample database. + System.out.println("Listing the SQL database metrics for the sample database"); + + endTime = OffsetDateTime.now(); + filter = String.format("startTime eq '%s' and endTime eq '%s'", startTime.toInstant(), endTime.toInstant()); + + dbMetrics = db.listMetrics(filter); + for (SqlDatabaseMetric metric : dbMetrics) { + Utils.print(metric); + } + + // ============================================================ + // Use Monitor Service to list the SQL server metrics. + + System.out.println("Using Monitor Service to list the SQL server metrics"); + PagedIterable metricDefinitions = azureResourceManager.metricDefinitions().listByResource(sqlServer.id()); + + for (MetricDefinition metricDefinition : metricDefinitions) { + // find metric definition for "DTU used" and "Storage used" + if (metricDefinition.name().localizedValue().equalsIgnoreCase("dtu used") + || metricDefinition.name().localizedValue().equalsIgnoreCase("storage used")) { + // get metric records + MetricCollection metricCollection = metricDefinition.defineQuery() + .startingFrom(startTime) + .endsBefore(endTime) + .withAggregation("Average") + .withInterval(Duration.ofMinutes(5)) + .withOdataFilter(String.format("DatabaseResourceId eq '%s'", db.id())) + .execute(); + + System.out.format("SQL server \"%s\" %s metrics%n", sqlServer.name(), metricDefinition.name().localizedValue()); + System.out.println("\tNamespace: " + metricCollection.namespace()); + System.out.println("\tQuery time: " + metricCollection.timespan()); + System.out.println("\tTime Grain: " + metricCollection.interval()); + System.out.println("\tCost: " + metricCollection.cost()); + + for (Metric metric : metricCollection.metrics()) { + System.out.println("\tMetric: " + metric.name().localizedValue()); + System.out.println("\tType: " + metric.type()); + System.out.println("\tUnit: " + metric.unit()); + System.out.println("\tTime Series: "); + for (TimeSeriesElement timeElement : metric.timeseries()) { + System.out.println("\t\tMetadata: "); + for (MetadataValueInner metadata : timeElement.metadatavalues()) { + System.out.println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); + } + System.out.println("\t\tData: "); + for (MetricValue data : timeElement.data()) { + System.out.println("\t\t\t" + data.timestamp() + + " : (Min) " + data.minimum() + + " : (Max) " + data.maximum() + + " : (Avg) " + data.average() + + " : (Total) " + data.total() + + " : (Count) " + data.count()); + } + } + } + break; + } + } + + // ============================================================ + // Use Monitor Service to list the SQL Database metrics. + System.out.println("Using Monitor Service to list the SQL Database metrics"); + metricDefinitions = azureResourceManager.metricDefinitions().listByResource(db.id()); + + for (MetricDefinition metricDefinition : metricDefinitions) { + // find metric definition for Transactions + if (metricDefinition.name().localizedValue().equalsIgnoreCase("dtu used") + || metricDefinition.name().localizedValue().equalsIgnoreCase("cpu used") + || metricDefinition.name().localizedValue().equalsIgnoreCase("storage used")) { + // get metric records + MetricCollection metricCollection = metricDefinition.defineQuery() + .startingFrom(startTime) + .endsBefore(endTime) + .execute(); + + System.out.println("Metrics for '" + db.id() + "':"); + System.out.println("Namespace: " + metricCollection.namespace()); + System.out.println("Query time: " + metricCollection.timespan()); + System.out.println("Time Grain: " + metricCollection.interval()); + System.out.println("Cost: " + metricCollection.cost()); + + for (Metric metric : metricCollection.metrics()) { + System.out.println("\tMetric: " + metric.name().localizedValue()); + System.out.println("\tType: " + metric.type()); + System.out.println("\tUnit: " + metric.unit()); + System.out.println("\tTime Series: "); + for (TimeSeriesElement timeElement : metric.timeseries()) { + System.out.println("\t\tMetadata: "); + for (MetadataValueInner metadata : timeElement.metadatavalues()) { + System.out.println("\t\t\t" + metadata.name().localizedValue() + ": " + metadata.value()); + } + System.out.println("\t\tData: "); + for (MetricValue data : timeElement.data()) { + System.out.println("\t\t\t" + data.timestamp() + + " : (Min) " + data.minimum() + + " : (Max) " + data.maximum() + + " : (Avg) " + data.average() + + " : (Total) " + data.total() + + " : (Count) " + data.count()); + } + } + } + break; + } + } + + // Delete the SQL Servers. + System.out.println("Deleting the Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java index c1954d3f87a2..2028b0e93681 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabase.java @@ -1,158 +1,158 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; -//import com.azure.resourcemanager.sql.models.SqlFirewallRule; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -//import java.util.List; -// -///** -// * Azure SQL sample for managing SQL Database - -// * - Create a SQL Server along with 2 firewalls. -// * - Create a database in SQL server -// * - Change performance level (SKU) of SQL Database -// * - List and delete firewalls. -// * - Create another firewall in the SQlServer -// * - Delete database, firewall and SQL Server -// */ -// -//public final class ManageSqlDatabase { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSDSI", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String firewallRuleIPAddress = "10.0.0.1"; -// final String firewallRuleStartIPAddress = "10.2.0.1"; -// final String firewallRuleEndIPAddress = "10.2.0.10"; -// final String databaseName = "mydatabase"; -// try { -// -// // ============================================================ -// // Create a SQL Server, with 2 firewall rules. -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() -// .defineFirewallRule("filewallRule2") -// .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // Create a Database in SQL server created above. -// System.out.println("Creating a database"); -// -// SqlDatabase database = sqlServer.databases() -// .define(databaseName) -// .create(); -// Utils.print(database); -// -// // ============================================================ -// // Update the edition of database. -// System.out.println("Updating a database"); -// database = database.update() -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) -// .withMaxSizeBytes(1024 * 1024 * 1024 * 20) -// .apply(); -// Utils.print(database); -// -// // ============================================================ -// // List and delete all firewall rules. -// System.out.println("Listing all firewall rules"); -// -// List firewallRules = sqlServer.firewallRules().list(); -// for (SqlFirewallRule firewallRule: firewallRules) { -// // Print information of the firewall rule. -// Utils.print(firewallRule); -// -// // Delete the firewall rule. -// System.out.println("Deleting a firewall rule"); -// firewallRule.delete(); -// } -// -// // ============================================================ -// // Add new firewall rules. -// System.out.println("Creating a firewall rule for SQL Server"); -// SqlFirewallRule firewallRule = sqlServer.firewallRules().define("myFirewallRule") -// .withIpAddress("10.10.10.10") -// .create(); -// -// Utils.print(firewallRule); -// -// database.listUsageMetrics(); -// -// // Delete the database. -// System.out.println("Deleting a database"); -// database.delete(); -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageSqlDatabase() { -// -// } -// -// -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlServer; + +import java.util.List; + +/** + * Azure SQL sample for managing SQL Database - + * - Create a SQL Server along with 2 firewalls. + * - Create a database in SQL server + * - Change performance level (SKU) of SQL Database + * - List and delete firewalls. + * - Create another firewall in the SQlServer + * - Delete database, firewall and SQL Server + */ + +public final class ManageSqlDatabase { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSDSI", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String firewallRuleIPAddress = "10.0.0.1"; + final String firewallRuleStartIPAddress = "10.2.0.1"; + final String firewallRuleEndIPAddress = "10.2.0.10"; + final String databaseName = "mydatabase"; + try { + + // ============================================================ + // Create a SQL Server, with 2 firewall rules. + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() + .defineFirewallRule("filewallRule2") + .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // Create a Database in SQL server created above. + System.out.println("Creating a database"); + + SqlDatabase database = sqlServer.databases() + .define(databaseName) + .create(); + Utils.print(database); + + // ============================================================ + // Update the edition of database. + System.out.println("Updating a database"); + database = database.update() + .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) + .withMaxSizeBytes(1024 * 1024 * 1024 * 20) + .apply(); + Utils.print(database); + + // ============================================================ + // List and delete all firewall rules. + System.out.println("Listing all firewall rules"); + + List firewallRules = sqlServer.firewallRules().list(); + for (SqlFirewallRule firewallRule: firewallRules) { + // Print information of the firewall rule. + Utils.print(firewallRule); + + // Delete the firewall rule. + System.out.println("Deleting a firewall rule"); + firewallRule.delete(); + } + + // ============================================================ + // Add new firewall rules. + System.out.println("Creating a firewall rule for SQL Server"); + SqlFirewallRule firewallRule = sqlServer.firewallRules().define("myFirewallRule") + .withIpAddress("10.10.10.10") + .create(); + + Utils.print(firewallRule); + + database.listUsageMetrics(); + + // Delete the database. + System.out.println("Deleting a database"); + database.delete(); + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageSqlDatabase() { + + } + + +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java index 50933ab1adbe..4e954e90dfc2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabaseInElasticPool.java @@ -1,245 +1,245 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.ElasticPoolActivity; -//import com.azure.resourcemanager.sql.models.ElasticPoolDatabaseActivity; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; -//import com.azure.resourcemanager.sql.models.SqlElasticPool; -//import com.azure.resourcemanager.sql.models.SqlElasticPoolBasicEDTUs; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -///** -// * Azure SQL sample for managing SQL Database - -// * - Create a SQL Server with elastic pool and 2 databases -// * - Create another database and add it to elastic pool through database update -// * - Create one more database and add it to elastic pool through elastic pool update. -// * - List and print databases in the elastic pool -// * - Remove a database from elastic pool. -// * - List and print elastic pool activities -// * - List and print elastic pool database activities -// * - Add another elastic pool in existing SQL Server. -// * - Delete database, elastic pools and SQL Server -// */ -// -//public final class ManageSqlDatabaseInElasticPool { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDEP", 20); -// final String elasticPoolName = "myElasticPool"; -// final String elasticPool2Name = "secondElasticPool"; -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String database1Name = "myDatabase1"; -// final String database2Name = "myDatabase2"; -// final String anotherDatabaseName = "myAnotherDatabase"; -// -// try { -// // ============================================================ -// // Create a SQL Server, with 2 firewall rules. -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineElasticPool(elasticPoolName).withStandardPool().attach() -// .defineDatabase(database1Name).withExistingElasticPool(elasticPoolName).attach() -// .defineDatabase(database2Name).withExistingElasticPool(elasticPoolName).attach() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // List and prints the elastic pools -// for (SqlElasticPool elasticPool: sqlServer.elasticPools().list()) { -// Utils.print(elasticPool); -// } -// -// // ============================================================ -// // Get and prints the elastic pool -// SqlElasticPool elasticPool = sqlServer.elasticPools().get(elasticPoolName); -// Utils.print(elasticPool); -// -// // ============================================================ -// // Change DTUs in the elastic pools. -// elasticPool = elasticPool.update() -// .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_200) -// .withStorageCapacity(204800 * 1024 * 1024L) -// .withDatabaseMinCapacity(10) -// .withDatabaseMaxCapacity(50) -// .apply(); -// -// Utils.print(elasticPool); -// -// System.out.println("Start ------- Current databases in the elastic pool"); -// for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { -// Utils.print(databaseInElasticPool); -// } -// System.out.println("End --------- Current databases in the elastic pool"); -// -// // ============================================================ -// // Create a Database in SQL server created above. -// System.out.println("Creating a database"); -// -// SqlDatabase database = sqlServer.databases() -// .define("myNewDatabase") -// .create(); -// Utils.print(database); -// -// System.out.println("Start ------- Current databases in the elastic pool"); -// for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { -// Utils.print(databaseInElasticPool); -// } -// System.out.println("End --------- Current databases in the elastic pool"); -// -// // ============================================================ -// // Move newly created database to the pool. -// System.out.println("Updating a database"); -// database = database.update() -// .withExistingElasticPool(elasticPoolName) -// .apply(); -// Utils.print(database); -// -// // ============================================================ -// // Create another database and move it in elastic pool as update to the elastic pool. -// SqlDatabase anotherDatabase = sqlServer.databases().define(anotherDatabaseName) -// .create(); -// -// // ============================================================ -// // Update the elastic pool to have newly created database. -// elasticPool.update() -// .withExistingDatabase(anotherDatabase) -// .apply(); -// -// System.out.println("Start ------- Current databases in the elastic pool"); -// for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { -// Utils.print(databaseInElasticPool); -// } -// System.out.println("End --------- Current databases in the elastic pool"); -// -// // ============================================================ -// // Remove the database from the elastic pool. -// System.out.println("Remove the database from the pool."); -// anotherDatabase = anotherDatabase.update() -// .withoutElasticPool() -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) -// .withMaxSizeBytes(1024 * 1024 * 1024 * 20) -// .apply(); -// Utils.print(anotherDatabase); -// -// System.out.println("Start ------- Current databases in the elastic pool"); -// for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { -// Utils.print(databaseInElasticPool); -// } -// System.out.println("End --------- Current databases in the elastic pool"); -// -// -// // ============================================================ -// // Get list of elastic pool's activities and print the same. -// System.out.println("Start ------- Activities in a elastic pool"); -// for (ElasticPoolActivity activity: elasticPool.listActivities()) { -// Utils.print(activity); -// } -// System.out.println("End ------- Activities in a elastic pool"); -// -// // ============================================================ -// // Get list of elastic pool's database activities and print the same. -// -// System.out.println("Start ------- Activities in a elastic pool"); -// for (ElasticPoolDatabaseActivity databaseActivity: elasticPool.listDatabaseActivities()) { -// Utils.print(databaseActivity); -// } -// System.out.println("End ------- Activities in a elastic pool"); -// -// // ============================================================ -// // List databases in the sql server and delete the same. -// System.out.println("List and delete all databases from SQL Server"); -// for (SqlDatabase databaseInServer: sqlServer.databases().list()) { -// Utils.print(databaseInServer); -// // Can not delete reserved database "master" -// if (!databaseInServer.name().equals("master")) { -// databaseInServer.delete(); -// } -// } -// -// // ============================================================ -// // Create another elastic pool in SQL Server -// System.out.println("Create ElasticPool in existing SQL Server"); -// SqlElasticPool elasticPool2 = sqlServer.elasticPools().define(elasticPool2Name) -// .withStandardPool() -// .create(); -// -// Utils.print(elasticPool2); -// -// // ============================================================ -// // Deletes the elastic pool. -// System.out.println("Delete the elastic pool from the SQL Server"); -// sqlServer.elasticPools().delete(elasticPoolName); -// sqlServer.elasticPools().delete(elasticPool2Name); -// -// // ============================================================ -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageSqlDatabaseInElasticPool() { -// -// } -// -// -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.ElasticPoolActivity; +import com.azure.resourcemanager.sql.models.ElasticPoolDatabaseActivity; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlElasticPool; +import com.azure.resourcemanager.sql.models.SqlElasticPoolBasicEDTUs; +import com.azure.resourcemanager.sql.models.SqlServer; + +/** + * Azure SQL sample for managing SQL Database - + * - Create a SQL Server with elastic pool and 2 databases + * - Create another database and add it to elastic pool through database update + * - Create one more database and add it to elastic pool through elastic pool update. + * - List and print databases in the elastic pool + * - Remove a database from elastic pool. + * - List and print elastic pool activities + * - List and print elastic pool database activities + * - Add another elastic pool in existing SQL Server. + * - Delete database, elastic pools and SQL Server + */ + +public final class ManageSqlDatabaseInElasticPool { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDEP", 20); + final String elasticPoolName = "myElasticPool"; + final String elasticPool2Name = "secondElasticPool"; + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String database1Name = "myDatabase1"; + final String database2Name = "myDatabase2"; + final String anotherDatabaseName = "myAnotherDatabase"; + + try { + // ============================================================ + // Create a SQL Server, with 2 firewall rules. + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineElasticPool(elasticPoolName).withStandardPool().attach() + .defineDatabase(database1Name).withExistingElasticPool(elasticPoolName).attach() + .defineDatabase(database2Name).withExistingElasticPool(elasticPoolName).attach() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // List and prints the elastic pools + for (SqlElasticPool elasticPool: sqlServer.elasticPools().list()) { + Utils.print(elasticPool); + } + + // ============================================================ + // Get and prints the elastic pool + SqlElasticPool elasticPool = sqlServer.elasticPools().get(elasticPoolName); + Utils.print(elasticPool); + + // ============================================================ + // Change DTUs in the elastic pools. + elasticPool = elasticPool.update() + .withReservedDtu(SqlElasticPoolBasicEDTUs.eDTU_200) + .withStorageCapacity(204800 * 1024 * 1024L) + .withDatabaseMinCapacity(10) + .withDatabaseMaxCapacity(50) + .apply(); + + Utils.print(elasticPool); + + System.out.println("Start ------- Current databases in the elastic pool"); + for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + Utils.print(databaseInElasticPool); + } + System.out.println("End --------- Current databases in the elastic pool"); + + // ============================================================ + // Create a Database in SQL server created above. + System.out.println("Creating a database"); + + SqlDatabase database = sqlServer.databases() + .define("myNewDatabase") + .create(); + Utils.print(database); + + System.out.println("Start ------- Current databases in the elastic pool"); + for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + Utils.print(databaseInElasticPool); + } + System.out.println("End --------- Current databases in the elastic pool"); + + // ============================================================ + // Move newly created database to the pool. + System.out.println("Updating a database"); + database = database.update() + .withExistingElasticPool(elasticPoolName) + .apply(); + Utils.print(database); + + // ============================================================ + // Create another database and move it in elastic pool as update to the elastic pool. + SqlDatabase anotherDatabase = sqlServer.databases().define(anotherDatabaseName) + .create(); + + // ============================================================ + // Update the elastic pool to have newly created database. + elasticPool.update() + .withExistingDatabase(anotherDatabase) + .apply(); + + System.out.println("Start ------- Current databases in the elastic pool"); + for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + Utils.print(databaseInElasticPool); + } + System.out.println("End --------- Current databases in the elastic pool"); + + // ============================================================ + // Remove the database from the elastic pool. + System.out.println("Remove the database from the pool."); + anotherDatabase = anotherDatabase.update() + .withoutElasticPool() + .withStandardEdition(SqlDatabaseStandardServiceObjective.S3) + .withMaxSizeBytes(1024 * 1024 * 1024 * 20) + .apply(); + Utils.print(anotherDatabase); + + System.out.println("Start ------- Current databases in the elastic pool"); + for (SqlDatabase databaseInElasticPool: elasticPool.listDatabases()) { + Utils.print(databaseInElasticPool); + } + System.out.println("End --------- Current databases in the elastic pool"); + + + // ============================================================ + // Get list of elastic pool's activities and print the same. + System.out.println("Start ------- Activities in a elastic pool"); + for (ElasticPoolActivity activity: elasticPool.listActivities()) { + Utils.print(activity); + } + System.out.println("End ------- Activities in a elastic pool"); + + // ============================================================ + // Get list of elastic pool's database activities and print the same. + + System.out.println("Start ------- Activities in a elastic pool"); + for (ElasticPoolDatabaseActivity databaseActivity: elasticPool.listDatabaseActivities()) { + Utils.print(databaseActivity); + } + System.out.println("End ------- Activities in a elastic pool"); + + // ============================================================ + // List databases in the sql server and delete the same. + System.out.println("List and delete all databases from SQL Server"); + for (SqlDatabase databaseInServer: sqlServer.databases().list()) { + Utils.print(databaseInServer); + // Can not delete reserved database "master" + if (!databaseInServer.name().equals("master")) { + databaseInServer.delete(); + } + } + + // ============================================================ + // Create another elastic pool in SQL Server + System.out.println("Create ElasticPool in existing SQL Server"); + SqlElasticPool elasticPool2 = sqlServer.elasticPools().define(elasticPool2Name) + .withStandardPool() + .create(); + + Utils.print(elasticPool2); + + // ============================================================ + // Deletes the elastic pool. + System.out.println("Delete the elastic pool from the SQL Server"); + sqlServer.elasticPools().delete(elasticPoolName); + sqlServer.elasticPools().delete(elasticPool2Name); + + // ============================================================ + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageSqlDatabaseInElasticPool() { + + } + + +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java index b7d93a8b7090..52bfd71f410c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlDatabasesAcrossDifferentDataCenters.java @@ -1,240 +1,240 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; -//import com.azure.resourcemanager.compute.models.VirtualMachine; -//import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; -//import com.azure.resourcemanager.network.models.Network; -//import com.azure.resourcemanager.network.models.PublicIpAddress; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.CreateMode; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlFirewallRule; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -//import java.util.ArrayList; -//import java.util.Collection; -//import java.util.HashMap; -//import java.util.List; -//import java.util.Map; -// -///** -// * Azure SQL sample for managing SQL Database - -// * - Create 3 SQL Servers in different region. -// * - Create a master database in master SQL Server. -// * - Create 2 more SQL Servers in different azure regions -// * - Create secondary read only databases in these server with source as database in server created in step 1. -// * - Create 5 virtual networks in different regions. -// * - Create one VM in each of the virtual network. -// * - Update all three databases to have firewall rules with range of each of the virtual network. -// */ -// -//public final class ManageSqlDatabasesAcrossDifferentDataCenters { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDRE", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String slaveSqlServer1Name = Utils.randomResourceName(azureResourceManager, "slave1sql", 20); -// final String slaveSqlServer2Name = Utils.randomResourceName(azureResourceManager, "slave2sql", 20); -// final String databaseName = "mydatabase"; -// final String networkPrefix = "network"; -// final String virtualMachinePrefix = "samplevm"; -// try { -// -// // ============================================================ -// // Create a SQL Server, with 2 firewall rules. -// SqlServer masterSqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .create(); -// -// Utils.print(masterSqlServer); -// -// // ============================================================ -// // Create a Database in master SQL server created above. -// System.out.println("Creating a database"); -// -// SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName) -// .withBasicEdition() -// .create(); -// Utils.print(masterDatabase); -// -// // ============================================================ -// // Create secondary SQLServer/Database for the master database -// System.out.println("Creating server in secondary location for master SQL Server"); -// -// SqlServer sqlServerInSecondaryLocation = azureResourceManager.sqlServers() -// .define(slaveSqlServer1Name) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .create(); -// Utils.print(sqlServerInSecondaryLocation); -// -// System.out.println("Creating database in slave SQL Server."); -// SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases().define(databaseName) -// .withSourceDatabase(masterDatabase) -// .withMode(CreateMode.ONLINE_SECONDARY) -// .create(); -// Utils.print(secondaryDatabase); -// -// // ============================================================ -// // Create another slave SQLServer/Database for the master database -// System.out.println("Creating server in another location for master SQL Server"); -// SqlServer sqlServerInEurope = azureResourceManager.sqlServers() -// .define(slaveSqlServer2Name) -// .withRegion(Region.US_SOUTH_CENTRAL) -// .withExistingResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .create(); -// Utils.print(sqlServerInEurope); -// -// System.out.println("Creating database in second slave SQL Server."); -// SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases().define(databaseName) -// .withSourceDatabase(masterDatabase) -// .withMode(CreateMode.ONLINE_SECONDARY) -// .create(); -// Utils.print(secondaryDatabaseInEurope); -// -// // ============================================================ -// // Create Virtual Networks in different regions -// List regions = new ArrayList<>(); -// -// regions.add(Region.US_EAST); -// regions.add(Region.US_SOUTH_CENTRAL); -// regions.add(Region.EUROPE_NORTH); -// regions.add(Region.ASIA_SOUTHEAST); -// regions.add(Region.JAPAN_EAST); -// -// List> creatableNetworks = new ArrayList<>(); -// -// System.out.println("Creating virtual networks in different regions."); -// -// for (Region region: regions) { -// creatableNetworks.add(azureResourceManager.networks().define(Utils.randomResourceName(azureResourceManager, networkPrefix, 20)) -// .withRegion(region) -// .withExistingResourceGroup(rgName)); -// } -// Collection networks = azureResourceManager.networks().create(creatableNetworks).values(); -// -// // ============================================================ -// // Create virtual machines attached to different virtual networks created above. -// List> creatableVirtualMachines = new ArrayList<>(); -// System.out.println("Creating virtual machines in different regions."); -// -// for (Network network: networks) { -// String virtualMachineName = Utils.randomResourceName(azureResourceManager, virtualMachinePrefix, 20); -// Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses().define(virtualMachineName) -// .withRegion(network.region()) -// .withExistingResourceGroup(rgName) -// .withLeafDomainLabel(virtualMachineName); -// creatableVirtualMachines.add(azureResourceManager.virtualMachines().define(virtualMachineName) -// .withRegion(network.region()) -// .withExistingResourceGroup(rgName) -// .withExistingPrimaryNetwork(network) -// .withSubnet(network.subnets().values().iterator().next().name()) -// .withPrimaryPrivateIPAddressDynamic() -// .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) -// .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) -// .withAdminUsername(administratorLogin) -// .withAdminPassword(administratorPassword) -// .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))); -// } -// -// HashMap ipAddresses = new HashMap<>(); -// for (VirtualMachine virtualMachine: azureResourceManager.virtualMachines().create(creatableVirtualMachines).values()) { -// ipAddresses.put(virtualMachine.name(), virtualMachine.getPrimaryPublicIPAddress().ipAddress()); -// } -// -// System.out.println("Adding firewall rule for each of virtual network network"); -// -// List sqlServers = new ArrayList<>(); -// sqlServers.add(sqlServerInSecondaryLocation); -// sqlServers.add(sqlServerInEurope); -// sqlServers.add(masterSqlServer); -// -// for (SqlServer sqlServer: sqlServers) { -// for (Map.Entry ipAddress: ipAddresses.entrySet()) { -// sqlServer.firewallRules().define(ipAddress.getKey()).withIpAddress(ipAddress.getValue()).create(); -// } -// } -// -// for (SqlServer sqlServer: sqlServers) { -// System.out.println("Print firewall rules in Sql Server in " + sqlServer.regionName()); -// -// List firewallRules = sqlServer.firewallRules().list(); -// for (SqlFirewallRule firewallRule: firewallRules) { -// Utils.print(firewallRule); -// } -// } -// -// // Delete the SQL Server. -// System.out.println("Deleting all Sql Servers"); -// for (SqlServer sqlServer: sqlServers) { -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// } -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageSqlDatabasesAcrossDifferentDataCenters() { -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.KnownWindowsVirtualMachineImage; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.PublicIpAddress; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.CreateMode; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlServer; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Azure SQL sample for managing SQL Database - + * - Create 3 SQL Servers in different region. + * - Create a master database in master SQL Server. + * - Create 2 more SQL Servers in different azure regions + * - Create secondary read only databases in these server with source as database in server created in step 1. + * - Create 5 virtual networks in different regions. + * - Create one VM in each of the virtual network. + * - Update all three databases to have firewall rules with range of each of the virtual network. + */ + +public final class ManageSqlDatabasesAcrossDifferentDataCenters { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDRE", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String slaveSqlServer1Name = Utils.randomResourceName(azureResourceManager, "slave1sql", 20); + final String slaveSqlServer2Name = Utils.randomResourceName(azureResourceManager, "slave2sql", 20); + final String databaseName = "mydatabase"; + final String networkPrefix = "network"; + final String virtualMachinePrefix = "samplevm"; + try { + + // ============================================================ + // Create a SQL Server, with 2 firewall rules. + SqlServer masterSqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + + Utils.print(masterSqlServer); + + // ============================================================ + // Create a Database in master SQL server created above. + System.out.println("Creating a database"); + + SqlDatabase masterDatabase = masterSqlServer.databases().define(databaseName) + .withBasicEdition() + .create(); + Utils.print(masterDatabase); + + // ============================================================ + // Create secondary SQLServer/Database for the master database + System.out.println("Creating server in secondary location for master SQL Server"); + + SqlServer sqlServerInSecondaryLocation = azureResourceManager.sqlServers() + .define(slaveSqlServer1Name) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + Utils.print(sqlServerInSecondaryLocation); + + System.out.println("Creating database in slave SQL Server."); + SqlDatabase secondaryDatabase = sqlServerInSecondaryLocation.databases().define(databaseName) + .withSourceDatabase(masterDatabase) + .withMode(CreateMode.ONLINE_SECONDARY) + .create(); + Utils.print(secondaryDatabase); + + // ============================================================ + // Create another slave SQLServer/Database for the master database + System.out.println("Creating server in another location for master SQL Server"); + SqlServer sqlServerInEurope = azureResourceManager.sqlServers() + .define(slaveSqlServer2Name) + .withRegion(Region.US_SOUTH_CENTRAL) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + Utils.print(sqlServerInEurope); + + System.out.println("Creating database in second slave SQL Server."); + SqlDatabase secondaryDatabaseInEurope = sqlServerInEurope.databases().define(databaseName) + .withSourceDatabase(masterDatabase) + .withMode(CreateMode.ONLINE_SECONDARY) + .create(); + Utils.print(secondaryDatabaseInEurope); + + // ============================================================ + // Create Virtual Networks in different regions + List regions = new ArrayList<>(); + + regions.add(Region.US_EAST); + regions.add(Region.US_SOUTH_CENTRAL); + regions.add(Region.EUROPE_NORTH); + regions.add(Region.ASIA_SOUTHEAST); + regions.add(Region.JAPAN_EAST); + + List> creatableNetworks = new ArrayList<>(); + + System.out.println("Creating virtual networks in different regions."); + + for (Region region: regions) { + creatableNetworks.add(azureResourceManager.networks().define(Utils.randomResourceName(azureResourceManager, networkPrefix, 20)) + .withRegion(region) + .withExistingResourceGroup(rgName)); + } + Collection networks = azureResourceManager.networks().create(creatableNetworks).values(); + + // ============================================================ + // Create virtual machines attached to different virtual networks created above. + List> creatableVirtualMachines = new ArrayList<>(); + System.out.println("Creating virtual machines in different regions."); + + for (Network network: networks) { + String virtualMachineName = Utils.randomResourceName(azureResourceManager, virtualMachinePrefix, 20); + Creatable publicIPAddressCreatable = azureResourceManager.publicIpAddresses().define(virtualMachineName) + .withRegion(network.region()) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(virtualMachineName); + creatableVirtualMachines.add(azureResourceManager.virtualMachines().define(virtualMachineName) + .withRegion(network.region()) + .withExistingResourceGroup(rgName) + .withExistingPrimaryNetwork(network) + .withSubnet(network.subnets().values().iterator().next().name()) + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(publicIPAddressCreatable) + .withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER) + .withAdminUsername(administratorLogin) + .withAdminPassword(administratorPassword) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4"))); + } + + HashMap ipAddresses = new HashMap<>(); + for (VirtualMachine virtualMachine: azureResourceManager.virtualMachines().create(creatableVirtualMachines).values()) { + ipAddresses.put(virtualMachine.name(), virtualMachine.getPrimaryPublicIPAddress().ipAddress()); + } + + System.out.println("Adding firewall rule for each of virtual network network"); + + List sqlServers = new ArrayList<>(); + sqlServers.add(sqlServerInSecondaryLocation); + sqlServers.add(sqlServerInEurope); + sqlServers.add(masterSqlServer); + + for (SqlServer sqlServer: sqlServers) { + for (Map.Entry ipAddress: ipAddresses.entrySet()) { + sqlServer.firewallRules().define(ipAddress.getKey()).withIpAddress(ipAddress.getValue()).create(); + } + } + + for (SqlServer sqlServer: sqlServers) { + System.out.println("Print firewall rules in Sql Server in " + sqlServer.regionName()); + + List firewallRules = sqlServer.firewallRules().list(); + for (SqlFirewallRule firewallRule: firewallRules) { + Utils.print(firewallRule); + } + } + + // Delete the SQL Server. + System.out.println("Deleting all Sql Servers"); + for (SqlServer sqlServer: sqlServers) { + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + } + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageSqlDatabasesAcrossDifferentDataCenters() { + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java index 3a05b860f9cc..6e3be306b965 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFailoverGroups.java @@ -1,197 +1,197 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//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.resourcemanager.sql.models.SampleName; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; -//import com.azure.resourcemanager.sql.models.SqlFailoverGroup; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -//import java.time.Duration; -// -///** -// * Azure SQL sample for managing SQL Failover Groups -// * - Create a primary SQL Server with a sample database and a secondary SQL Server. -// * - Get a failover group from the primary SQL server to the secondary SQL server. -// * - Update a failover group. -// * - List all failover groups. -// * - Delete a failover group. -// * - Delete Sql Server -// */ -//public class ManageSqlFailoverGroups { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlPrimaryServerName = Utils.randomResourceName(azureResourceManager, "sqlpri", 20); -// final String sqlSecondaryServerName = Utils.randomResourceName(azureResourceManager, "sqlsec", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// final String failoverGroupName = Utils.randomResourceName(azureResourceManager, "fog", 20); -// final String dbName = "dbSample"; -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// -// try { -// -// // ============================================================ -// // Create a primary SQL Server with a sample database. -// System.out.println("Creating a primary SQL Server with a sample database"); -// -// SqlServer sqlPrimaryServer = azureResourceManager.sqlServers().define(sqlPrimaryServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineDatabase(dbName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) -// .attach() -// .create(); -// -// Utils.print(sqlPrimaryServer); -// -// // ============================================================ -// // Create a secondary SQL Server with a sample database. -// System.out.println("Creating a secondary SQL Server with a sample database"); -// -// SqlServer sqlSecondaryServer = azureResourceManager.sqlServers().define(sqlSecondaryServerName) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .create(); -// -// Utils.print(sqlSecondaryServer); -// -// -// // ============================================================ -// // Create a Failover Group from the primary SQL server to the secondary SQL server. -// System.out.println("Creating a Failover Group from the primary SQL server to the secondary SQL server"); -// -// SqlFailoverGroup failoverGroup = sqlPrimaryServer.failoverGroups().define(failoverGroupName) -// .withManualReadWriteEndpointPolicy() -// .withPartnerServerId(sqlSecondaryServer.id()) -// .withReadOnlyEndpointPolicyDisabled() -// .create(); -// -// Utils.print(failoverGroup); -// -// // ============================================================ -// // Get the Failover Group from the secondary SQL server. -// System.out.println("Getting the Failover Group from the secondary SQL server"); -// -// sqlSecondaryServer.failoverGroups().get(failoverGroup.name()); -// -// Utils.print(failoverGroup); -// -// -// // ============================================================ -// // Update the Failover Group Endpoint policies and tags. -// System.out.println("Updating the Failover Group Endpoint policies and tags"); -// -// failoverGroup.update() -// .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) -// .withReadOnlyEndpointPolicyEnabled() -// .withTag("tag1", "value1") -// .apply(); -// -// Utils.print(failoverGroup); -// -// -// // ============================================================ -// // Update the Failover Group to add database and change read-write endpoint's failover policy. -// System.out.println("Updating the Failover Group to add database and change read-write endpoint's failover policy"); -// -// SqlDatabase db = sqlPrimaryServer.databases().get(dbName); -// -// Utils.print(db); -// -// failoverGroup.update() -// .withManualReadWriteEndpointPolicy() -// .withReadOnlyEndpointPolicyDisabled() -// .withNewDatabaseId(db.id()) -// .apply(); -// -// Utils.print(failoverGroup); -// -// -// // ============================================================ -// // List the Failover Group on the secondary server. -// System.out.println("Listing the Failover Group on the secondary server"); -// -// for (SqlFailoverGroup item : sqlSecondaryServer.failoverGroups().list()) { -// Utils.print(item); -// } -// -// // ============================================================ -// // Get the database from the secondary SQL server. -// System.out.println("Getting the database from the secondary server"); -// ResourceManagerUtils.sleep(Duration.ofMinutes(3)); -// -// db = sqlSecondaryServer.databases().get(dbName); -// -// Utils.print(db); -// -// // ============================================================ -// // Delete the Failover Group. -// System.out.println("Deleting the Failover Group"); -// -// sqlPrimaryServer.failoverGroups().delete(failoverGroup.name()); -// -// -// -// // Delete the SQL Servers. -// System.out.println("Deleting the Sql Servers"); -// azureResourceManager.sqlServers().deleteById(sqlPrimaryServer.id()); -// azureResourceManager.sqlServers().deleteById(sqlSecondaryServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +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.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlFailoverGroup; +import com.azure.resourcemanager.sql.models.SqlServer; + +import java.time.Duration; + +/** + * Azure SQL sample for managing SQL Failover Groups + * - Create a primary SQL Server with a sample database and a secondary SQL Server. + * - Get a failover group from the primary SQL server to the secondary SQL server. + * - Update a failover group. + * - List all failover groups. + * - Delete a failover group. + * - Delete Sql Server + */ +public class ManageSqlFailoverGroups { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlPrimaryServerName = Utils.randomResourceName(azureResourceManager, "sqlpri", 20); + final String sqlSecondaryServerName = Utils.randomResourceName(azureResourceManager, "sqlsec", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + final String failoverGroupName = Utils.randomResourceName(azureResourceManager, "fog", 20); + final String dbName = "dbSample"; + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + + try { + + // ============================================================ + // Create a primary SQL Server with a sample database. + System.out.println("Creating a primary SQL Server with a sample database"); + + SqlServer sqlPrimaryServer = azureResourceManager.sqlServers().define(sqlPrimaryServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); + + Utils.print(sqlPrimaryServer); + + // ============================================================ + // Create a secondary SQL Server with a sample database. + System.out.println("Creating a secondary SQL Server with a sample database"); + + SqlServer sqlSecondaryServer = azureResourceManager.sqlServers().define(sqlSecondaryServerName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .create(); + + Utils.print(sqlSecondaryServer); + + + // ============================================================ + // Create a Failover Group from the primary SQL server to the secondary SQL server. + System.out.println("Creating a Failover Group from the primary SQL server to the secondary SQL server"); + + SqlFailoverGroup failoverGroup = sqlPrimaryServer.failoverGroups().define(failoverGroupName) + .withManualReadWriteEndpointPolicy() + .withPartnerServerId(sqlSecondaryServer.id()) + .withReadOnlyEndpointPolicyDisabled() + .create(); + + Utils.print(failoverGroup); + + // ============================================================ + // Get the Failover Group from the secondary SQL server. + System.out.println("Getting the Failover Group from the secondary SQL server"); + + sqlSecondaryServer.failoverGroups().get(failoverGroup.name()); + + Utils.print(failoverGroup); + + + // ============================================================ + // Update the Failover Group Endpoint policies and tags. + System.out.println("Updating the Failover Group Endpoint policies and tags"); + + failoverGroup.update() + .withAutomaticReadWriteEndpointPolicyAndDataLossGracePeriod(120) + .withReadOnlyEndpointPolicyEnabled() + .withTag("tag1", "value1") + .apply(); + + Utils.print(failoverGroup); + + + // ============================================================ + // Update the Failover Group to add database and change read-write endpoint's failover policy. + System.out.println("Updating the Failover Group to add database and change read-write endpoint's failover policy"); + + SqlDatabase db = sqlPrimaryServer.databases().get(dbName); + + Utils.print(db); + + failoverGroup.update() + .withManualReadWriteEndpointPolicy() + .withReadOnlyEndpointPolicyDisabled() + .withNewDatabaseId(db.id()) + .apply(); + + Utils.print(failoverGroup); + + + // ============================================================ + // List the Failover Group on the secondary server. + System.out.println("Listing the Failover Group on the secondary server"); + + for (SqlFailoverGroup item : sqlSecondaryServer.failoverGroups().list()) { + Utils.print(item); + } + + // ============================================================ + // Get the database from the secondary SQL server. + System.out.println("Getting the database from the secondary server"); + ResourceManagerUtils.sleep(Duration.ofMinutes(3)); + + db = sqlSecondaryServer.databases().get(dbName); + + Utils.print(db); + + // ============================================================ + // Delete the Failover Group. + System.out.println("Deleting the Failover Group"); + + sqlPrimaryServer.failoverGroups().delete(failoverGroup.name()); + + + + // Delete the SQL Servers. + System.out.println("Deleting the Sql Servers"); + azureResourceManager.sqlServers().deleteById(sqlPrimaryServer.id()); + azureResourceManager.sqlServers().deleteById(sqlSecondaryServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java index 54285cf7fd43..64a97ce58288 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlFirewallRules.java @@ -1,155 +1,155 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SqlFirewallRule; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -//import java.util.List; -// -///** -// * Azure SQL sample for managing SQL Database - -// * - Create a SQL Server along with 2 firewalls. -// * - Add another firewall in the SQL Server -// * - List all firewalls. -// * - Get a firewall. -// * - Update a firewall. -// * - Delete a firewall. -// * - Add and delete a firewall as part of update of SQL Server -// * - Delete Sql Server -// */ -// -//public final class ManageSqlFirewallRules { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String firewallRuleIPAddress = "10.0.0.1"; -// final String firewallRuleStartIPAddress = "10.2.0.1"; -// final String firewallRuleEndIPAddress = "10.2.0.10"; -// final String myFirewallName = "myFirewallRule"; -// final String myFirewallRuleIPAddress = "10.10.10.10"; -// final String otherFirewallRuleStartIPAddress = "121.12.12.1"; -// final String otherFirewallRuleEndIPAddress = "121.12.12.10"; -// try { -// -// // ============================================================ -// // Create a SQL Server, with 2 firewall rules. -// System.out.println("Create a SQL server with 2 firewall rules adding a single IP Address and a range of IP Addresses"); -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() -// .defineFirewallRule("filewallRule2") -// .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // List and delete all firewall rules. -// System.out.println("Listing all firewall rules in SQL Server."); -// -// List firewallRules = sqlServer.firewallRules().list(); -// for (SqlFirewallRule firewallRule: firewallRules) { -// // Print information of the firewall rule. -// Utils.print(firewallRule); -// -// // Delete the firewall rule. -// System.out.println("Deleting a firewall rule"); -// firewallRule.delete(); -// } -// -// // ============================================================ -// // Add new firewall rules. -// System.out.println("Creating a firewall rule in existing SQL Server"); -// SqlFirewallRule firewallRule = sqlServer.firewallRules().define(myFirewallName) -// .withIpAddress(myFirewallRuleIPAddress) -// .create(); -// -// Utils.print(firewallRule); -// -// System.out.println("Get a particular firewall rule in SQL Server"); -// -// firewallRule = sqlServer.firewallRules().get(myFirewallName); -// Utils.print(firewallRule); -// -// System.out.println("Deleting and adding new firewall rules as part of SQL Server update."); -// sqlServer.update() -// .withoutFirewallRule(myFirewallName) -// .defineFirewallRule("filewallRule2") -// .withIpAddressRange(otherFirewallRuleStartIPAddress, otherFirewallRuleEndIPAddress) -// .attach() -// .apply(); -// -// for (SqlFirewallRule sqlFirewallRule: sqlServer.firewallRules().list()) { -// // Print information of the firewall rule. -// Utils.print(sqlFirewallRule); -// } -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageSqlFirewallRules() { -// -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SqlFirewallRule; +import com.azure.resourcemanager.sql.models.SqlServer; + +import java.util.List; + +/** + * Azure SQL sample for managing SQL Database - + * - Create a SQL Server along with 2 firewalls. + * - Add another firewall in the SQL Server + * - List all firewalls. + * - Get a firewall. + * - Update a firewall. + * - Delete a firewall. + * - Add and delete a firewall as part of update of SQL Server + * - Delete Sql Server + */ + +public final class ManageSqlFirewallRules { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String firewallRuleIPAddress = "10.0.0.1"; + final String firewallRuleStartIPAddress = "10.2.0.1"; + final String firewallRuleEndIPAddress = "10.2.0.10"; + final String myFirewallName = "myFirewallRule"; + final String myFirewallRuleIPAddress = "10.10.10.10"; + final String otherFirewallRuleStartIPAddress = "121.12.12.1"; + final String otherFirewallRuleEndIPAddress = "121.12.12.10"; + try { + + // ============================================================ + // Create a SQL Server, with 2 firewall rules. + System.out.println("Create a SQL server with 2 firewall rules adding a single IP Address and a range of IP Addresses"); + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("filewallRule1").withIpAddress(firewallRuleIPAddress).attach() + .defineFirewallRule("filewallRule2") + .withIpAddressRange(firewallRuleStartIPAddress, firewallRuleEndIPAddress).attach() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // List and delete all firewall rules. + System.out.println("Listing all firewall rules in SQL Server."); + + List firewallRules = sqlServer.firewallRules().list(); + for (SqlFirewallRule firewallRule: firewallRules) { + // Print information of the firewall rule. + Utils.print(firewallRule); + + // Delete the firewall rule. + System.out.println("Deleting a firewall rule"); + firewallRule.delete(); + } + + // ============================================================ + // Add new firewall rules. + System.out.println("Creating a firewall rule in existing SQL Server"); + SqlFirewallRule firewallRule = sqlServer.firewallRules().define(myFirewallName) + .withIpAddress(myFirewallRuleIPAddress) + .create(); + + Utils.print(firewallRule); + + System.out.println("Get a particular firewall rule in SQL Server"); + + firewallRule = sqlServer.firewallRules().get(myFirewallName); + Utils.print(firewallRule); + + System.out.println("Deleting and adding new firewall rules as part of SQL Server update."); + sqlServer.update() + .withoutFirewallRule(myFirewallName) + .defineFirewallRule("filewallRule2") + .withIpAddressRange(otherFirewallRuleStartIPAddress, otherFirewallRuleEndIPAddress) + .attach() + .apply(); + + for (SqlFirewallRule sqlFirewallRule: sqlServer.firewallRules().list()) { + // Print information of the firewall rule. + Utils.print(sqlFirewallRule); + } + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageSqlFirewallRules() { + + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java index 4939a4f19cb8..e784b4bca024 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlImportExportDatabase.java @@ -1,167 +1,167 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SampleName; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.storage.models.StorageAccount; -// -///** -// * Azure SQL sample for managing import/export SQL Database - -// * - Create a SQL Server with one database from a pre-existing sample. -// * - Create a storage account and export a database -// * - Create a new database from a backup using the import functionality -// * - Update an empty database with a backup database using the import functionality -// * - Delete storage account, databases and SQL Server -// */ -//public final class ManageSqlImportExportDatabase { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// String storageName = Utils.randomResourceName(azureResourceManager, sqlServerName, 23); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String dbFromSampleName = "db-from-sample"; -// try { -// -// // ============================================================ -// // Create a SQL Server with one database from a sample. -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineDatabase(dbFromSampleName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .withBasicEdition() -// .attach() -// .create(); -// Utils.print(sqlServer); -// -// SqlDatabase dbFromSample = sqlServer.databases() -// .get(dbFromSampleName); -// Utils.print(dbFromSample); -// -// // ============================================================ -// // Export a database from a SQL server created above to a new storage account within the same resource group. -// System.out.println("Exporting a database from a SQL server created above to a new storage account within the same resource group."); -// -// Creatable storageAccountCreatable = azureResourceManager.storageAccounts() -// .define(storageName) -// .withRegion(sqlServer.regionName()) -// .withExistingResourceGroup(sqlServer.resourceGroupName()); -// -// dbFromSample.exportTo(storageAccountCreatable, "container-name", "dbfromsample.bacpac") -// .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) -// .execute(); -// StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); -// -// // ============================================================ -// // Import a database within a new elastic pool from a storage account container created above. -// System.out.println("Importing a database within a new elastic pool from a storage account container created above."); -// -// SqlDatabase dbFromImport = sqlServer.databases() -// .define("db-from-import1") -// .defineElasticPool("epi") -// .withStandardPool() -// .attach() -// .importFrom(storageAccount, "container-name", "dbfromsample.bacpac") -// .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) -// .create(); -// Utils.print(dbFromImport); -// -// // Delete the database. -// System.out.println("Deleting a database"); -// dbFromImport.delete(); -// -// // ============================================================ -// // Create an empty database within an elastic pool. -// SqlDatabase dbEmpty = sqlServer.databases() -// .define("db-from-import2") -// .withExistingElasticPool("epi") -// .create(); -// -// // ============================================================ -// // Import data from a BACPAC to an empty database within an elastic pool. -// System.out.println("Importing data from a BACPAC to an empty database within an elastic pool."); -// -// dbEmpty -// .importBacpac(storageAccount, "container-name", "dbfromsample.bacpac") -// .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) -// .execute(); -// Utils.print(dbFromImport); -// -// // Delete the storage account. -// System.out.println("Deleting the storage account"); -// azureResourceManager.storageAccounts().deleteById(storageAccount.id()); -// -// // Delete the databases. -// System.out.println("Deleting the databases"); -// dbEmpty.delete(); -// dbFromSample.delete(); -// -// // Delete the elastic pool. -// System.out.println("Deleting the elastic pool"); -// sqlServer.elasticPools().delete("epi"); -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.storage.models.StorageAccount; + +/** + * Azure SQL sample for managing import/export SQL Database - + * - Create a SQL Server with one database from a pre-existing sample. + * - Create a storage account and export a database + * - Create a new database from a backup using the import functionality + * - Update an empty database with a backup database using the import functionality + * - Delete storage account, databases and SQL Server + */ +public final class ManageSqlImportExportDatabase { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + String storageName = Utils.randomResourceName(azureResourceManager, sqlServerName, 23); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String dbFromSampleName = "db-from-sample"; + try { + + // ============================================================ + // Create a SQL Server with one database from a sample. + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbFromSampleName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withBasicEdition() + .attach() + .create(); + Utils.print(sqlServer); + + SqlDatabase dbFromSample = sqlServer.databases() + .get(dbFromSampleName); + Utils.print(dbFromSample); + + // ============================================================ + // Export a database from a SQL server created above to a new storage account within the same resource group. + System.out.println("Exporting a database from a SQL server created above to a new storage account within the same resource group."); + + Creatable storageAccountCreatable = azureResourceManager.storageAccounts() + .define(storageName) + .withRegion(sqlServer.regionName()) + .withExistingResourceGroup(sqlServer.resourceGroupName()); + + dbFromSample.exportTo(storageAccountCreatable, "container-name", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) + .execute(); + StorageAccount storageAccount = azureResourceManager.storageAccounts().getByResourceGroup(sqlServer.resourceGroupName(), storageName); + + // ============================================================ + // Import a database within a new elastic pool from a storage account container created above. + System.out.println("Importing a database within a new elastic pool from a storage account container created above."); + + SqlDatabase dbFromImport = sqlServer.databases() + .define("db-from-import1") + .defineElasticPool("epi") + .withStandardPool() + .attach() + .importFrom(storageAccount, "container-name", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) + .create(); + Utils.print(dbFromImport); + + // Delete the database. + System.out.println("Deleting a database"); + dbFromImport.delete(); + + // ============================================================ + // Create an empty database within an elastic pool. + SqlDatabase dbEmpty = sqlServer.databases() + .define("db-from-import2") + .withExistingElasticPool("epi") + .create(); + + // ============================================================ + // Import data from a BACPAC to an empty database within an elastic pool. + System.out.println("Importing data from a BACPAC to an empty database within an elastic pool."); + + dbEmpty + .importBacpac(storageAccount, "container-name", "dbfromsample.bacpac") + .withSqlAdministratorLoginAndPassword(administratorLogin, administratorPassword) + .execute(); + Utils.print(dbFromImport); + + // Delete the storage account. + System.out.println("Deleting the storage account"); + azureResourceManager.storageAccounts().deleteById(storageAccount.id()); + + // Delete the databases. + System.out.println("Deleting the databases"); + dbEmpty.delete(); + dbFromSample.delete(); + + // Delete the elastic pool. + System.out.println("Deleting the elastic pool"); + sqlServer.elasticPools().delete("epi"); + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java index 54e27e46b893..86873a4a71d6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerDnsAliases.java @@ -1,241 +1,241 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//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.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlServerDnsAlias; -// -//import java.sql.Connection; -//import java.sql.DriverManager; -//import java.sql.ResultSet; -//import java.sql.SQLException; -//import java.sql.Statement; -//import java.time.Duration; -// -///** -// * Azure SQL sample for managing SQL Server DNS Aliases. -// * - Create two SQL Servers "test" and "production", each with an empty database. -// * - Create a new table and insert some expected values into each database. -// * - Create a SQL Server DNS Alias to the "test" SQL database. -// * - Query the "test" SQL database via the DNS alias and print the result. -// * - Use the SQL Server DNS alias to acquire the "production" SQL database. -// * - Query the "production" SQL database via the DNS alias and print the result. -// * - Delete the SQL Servers -// */ -// -//public class ManageSqlServerDnsAliases { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws ClassNotFoundException, SQLException { -// final String sqlServerForTestName = Utils.randomResourceName(azureResourceManager, "sqltest", 20); -// final String sqlServerForProdName = Utils.randomResourceName(azureResourceManager, "sqlprod", 20); -// final String sqlServerDnsAlias = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String dbName = "dbSample"; -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// try { -// // Check if the expected SQL driver is available -// Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); -// -// // ============================================================ -// // Create a "test" SQL Server. -// System.out.println("Creating a SQL server for test related activities"); -// -// SqlServer sqlServerForTest = azureResourceManager.sqlServers().define(sqlServerForTestName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineFirewallRule("allowAll") -// .withIpAddressRange("0.0.0.1", "255.255.255.255") -// .attach() -// .defineDatabase(dbName) -// .withBasicEdition() -// .attach() -// .create(); -// -// Utils.print(sqlServerForTest); -// -// // ============================================================ -// // Create a connection to the "test" SQL Server. -// System.out.println("Creating a connection to the \"test\" SQL Server"); -// String connectionToSqlTestUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", -// sqlServerForTest.fullyQualifiedDomainName(), -// dbName, -// administratorLogin, -// administratorPassword); -// -// // Establish the connection. -// try (Connection conTest = DriverManager.getConnection(connectionToSqlTestUrl); -// Statement stmt = conTest.createStatement();) { -// -// -// // ============================================================ -// // Create a new table into the "test" SQL Server database and insert one value. -// System.out.println("Creating a new table into the \"test\" SQL Server database and insert one value"); -// -// String sqlCommand = "CREATE TABLE [Dns_Alias_Sample_Test] ([Name] [varchar](30) NOT NULL)"; -// stmt.execute(sqlCommand); -// -// sqlCommand = "INSERT Dns_Alias_Sample_Test VALUES ('Test')"; -// stmt.execute(sqlCommand); -// } -// -// -// // ============================================================ -// // Create a "production" SQL Server. -// System.out.println("Creating a SQL server for production related activities"); -// -// SqlServer sqlServerForProd = azureResourceManager.sqlServers().define(sqlServerForProdName) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineFirewallRule("allowAll") -// .withIpAddressRange("0.0.0.1", "255.255.255.255") -// .attach() -// .defineDatabase(dbName) -// .withBasicEdition() -// .attach() -// .create(); -// -// Utils.print(sqlServerForProd); -// -// // ============================================================ -// // Create a connection to the "production" SQL Server. -// System.out.println("Creating a connection to the \"production\" SQL Server"); -// -// String connectionToSqlProdUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", -// sqlServerForProd.fullyQualifiedDomainName(), -// dbName, -// administratorLogin, -// administratorPassword); -// -// // Establish the connection. -// try (Connection conProd = DriverManager.getConnection(connectionToSqlProdUrl); -// Statement stmt1 = conProd.createStatement();) { -// -// -// // ============================================================ -// // Create a new table into the "production" SQL Server database and insert one value. -// System.out.println("Creating a new table into the \"production\" SQL Server database and insert one value"); -// -// -// String sqlCommand = "CREATE TABLE [Dns_Alias_Sample_Prod] ([Name] [varchar](30) NOT NULL)"; -// stmt1.execute(sqlCommand); -// -// sqlCommand = "INSERT Dns_Alias_Sample_Prod VALUES ('Production')"; -// stmt1.execute(sqlCommand); -// } -// -// -// // ============================================================ -// // Create a SQL Server DNS alias and use it to query the "test" database. -// System.out.println("Creating a SQL Server DNS alias and use it to query the \"test\" database"); -// -// SqlServerDnsAlias dnsAlias = sqlServerForTest.dnsAliases() -// .define(sqlServerDnsAlias) -// .create(); -// ResourceManagerUtils.sleep(Duration.ofMinutes(5)); -// -// String connectionUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", -// dnsAlias.azureDnsRecord(), -// dbName, -// administratorLogin, -// administratorPassword); -// -// // Establish the connection. -// try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); -// Statement stmt2 = conDnsAlias.createStatement();) { -// -// String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Test;"; -// try (ResultSet resultSet = stmt2.executeQuery(sqlCommand);) { -// // Print results from select statement -// System.out.println("SELECT * FROM Dns_Alias_Sample_Test"); -// while (resultSet.next()) { -// System.out.format("\t%s%n", resultSet.getString(1)); -// } -// } -// } -// -// -// // ============================================================ -// // Use the "production" SQL Server to acquire the SQL Server DNS Alias and use it to query the "production" database. -// System.out.println("Using the \"production\" SQL Server to acquire the SQL Server DNS Alias and use it to query the \"production\" database"); -// -// sqlServerForProd.dnsAliases().acquire(sqlServerDnsAlias, sqlServerForTest.id()); -// -// // It takes some time for the DNS alias to reflect the new Server connection -// ResourceManagerUtils.sleep(Duration.ofMinutes(10)); -// -// // Re-establish the connection. -// try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); -// Statement stmt = conDnsAlias.createStatement();) { -// -// String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Prod;"; -// try (ResultSet resultSet = stmt.executeQuery(sqlCommand);) { -// // Print results from select statement -// System.out.println("SELECT * FROM Dns_Alias_Sample_Prod"); -// while (resultSet.next()) { -// System.out.format("\t%s%n", resultSet.getString(1)); -// } -// } -// } -// -// // Delete the SQL Servers. -// System.out.println("Deleting the Sql Servers"); -// azureResourceManager.sqlServers().deleteById(sqlServerForTest.id()); -// azureResourceManager.sqlServers().deleteById(sqlServerForProd.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +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.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlServerDnsAlias; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import java.time.Duration; + +/** + * Azure SQL sample for managing SQL Server DNS Aliases. + * - Create two SQL Servers "test" and "production", each with an empty database. + * - Create a new table and insert some expected values into each database. + * - Create a SQL Server DNS Alias to the "test" SQL database. + * - Query the "test" SQL database via the DNS alias and print the result. + * - Use the SQL Server DNS alias to acquire the "production" SQL database. + * - Query the "production" SQL database via the DNS alias and print the result. + * - Delete the SQL Servers + */ + +public class ManageSqlServerDnsAliases { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws ClassNotFoundException, SQLException { + final String sqlServerForTestName = Utils.randomResourceName(azureResourceManager, "sqltest", 20); + final String sqlServerForProdName = Utils.randomResourceName(azureResourceManager, "sqlprod", 20); + final String sqlServerDnsAlias = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String dbName = "dbSample"; + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + try { + // Check if the expected SQL driver is available + Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); + + // ============================================================ + // Create a "test" SQL Server. + System.out.println("Creating a SQL server for test related activities"); + + SqlServer sqlServerForTest = azureResourceManager.sqlServers().define(sqlServerForTestName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("allowAll") + .withIpAddressRange("0.0.0.1", "255.255.255.255") + .attach() + .defineDatabase(dbName) + .withBasicEdition() + .attach() + .create(); + + Utils.print(sqlServerForTest); + + // ============================================================ + // Create a connection to the "test" SQL Server. + System.out.println("Creating a connection to the \"test\" SQL Server"); + String connectionToSqlTestUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", + sqlServerForTest.fullyQualifiedDomainName(), + dbName, + administratorLogin, + administratorPassword); + + // Establish the connection. + try (Connection conTest = DriverManager.getConnection(connectionToSqlTestUrl); + Statement stmt = conTest.createStatement();) { + + + // ============================================================ + // Create a new table into the "test" SQL Server database and insert one value. + System.out.println("Creating a new table into the \"test\" SQL Server database and insert one value"); + + String sqlCommand = "CREATE TABLE [Dns_Alias_Sample_Test] ([Name] [varchar](30) NOT NULL)"; + stmt.execute(sqlCommand); + + sqlCommand = "INSERT Dns_Alias_Sample_Test VALUES ('Test')"; + stmt.execute(sqlCommand); + } + + + // ============================================================ + // Create a "production" SQL Server. + System.out.println("Creating a SQL server for production related activities"); + + SqlServer sqlServerForProd = azureResourceManager.sqlServers().define(sqlServerForProdName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineFirewallRule("allowAll") + .withIpAddressRange("0.0.0.1", "255.255.255.255") + .attach() + .defineDatabase(dbName) + .withBasicEdition() + .attach() + .create(); + + Utils.print(sqlServerForProd); + + // ============================================================ + // Create a connection to the "production" SQL Server. + System.out.println("Creating a connection to the \"production\" SQL Server"); + + String connectionToSqlProdUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", + sqlServerForProd.fullyQualifiedDomainName(), + dbName, + administratorLogin, + administratorPassword); + + // Establish the connection. + try (Connection conProd = DriverManager.getConnection(connectionToSqlProdUrl); + Statement stmt1 = conProd.createStatement();) { + + + // ============================================================ + // Create a new table into the "production" SQL Server database and insert one value. + System.out.println("Creating a new table into the \"production\" SQL Server database and insert one value"); + + + String sqlCommand = "CREATE TABLE [Dns_Alias_Sample_Prod] ([Name] [varchar](30) NOT NULL)"; + stmt1.execute(sqlCommand); + + sqlCommand = "INSERT Dns_Alias_Sample_Prod VALUES ('Production')"; + stmt1.execute(sqlCommand); + } + + + // ============================================================ + // Create a SQL Server DNS alias and use it to query the "test" database. + System.out.println("Creating a SQL Server DNS alias and use it to query the \"test\" database"); + + SqlServerDnsAlias dnsAlias = sqlServerForTest.dnsAliases() + .define(sqlServerDnsAlias) + .create(); + ResourceManagerUtils.sleep(Duration.ofMinutes(5)); + + String connectionUrl = String.format("jdbc:sqlserver://%s:1433;database=%s;user=%s;password=%s;", + dnsAlias.azureDnsRecord(), + dbName, + administratorLogin, + administratorPassword); + + // Establish the connection. + try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); + Statement stmt2 = conDnsAlias.createStatement();) { + + String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Test;"; + try (ResultSet resultSet = stmt2.executeQuery(sqlCommand);) { + // Print results from select statement + System.out.println("SELECT * FROM Dns_Alias_Sample_Test"); + while (resultSet.next()) { + System.out.format("\t%s%n", resultSet.getString(1)); + } + } + } + + + // ============================================================ + // Use the "production" SQL Server to acquire the SQL Server DNS Alias and use it to query the "production" database. + System.out.println("Using the \"production\" SQL Server to acquire the SQL Server DNS Alias and use it to query the \"production\" database"); + + sqlServerForProd.dnsAliases().acquire(sqlServerDnsAlias, sqlServerForTest.id()); + + // It takes some time for the DNS alias to reflect the new Server connection + ResourceManagerUtils.sleep(Duration.ofMinutes(10)); + + // Re-establish the connection. + try (Connection conDnsAlias = DriverManager.getConnection(connectionUrl); + Statement stmt = conDnsAlias.createStatement();) { + + String sqlCommand = "SELECT * FROM Dns_Alias_Sample_Prod;"; + try (ResultSet resultSet = stmt.executeQuery(sqlCommand);) { + // Print results from select statement + System.out.println("SELECT * FROM Dns_Alias_Sample_Prod"); + while (resultSet.next()) { + System.out.format("\t%s%n", resultSet.getString(1)); + } + } + } + + // Delete the SQL Servers. + System.out.println("Deleting the Sql Servers"); + azureResourceManager.sqlServers().deleteById(sqlServerForTest.id()); + azureResourceManager.sqlServers().deleteById(sqlServerForProd.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java index 9aa55ab08ec9..7adeb2c39ad2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerKeysWithAzureKeyVaultKey.java @@ -1,184 +1,184 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.util.Configuration; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.keyvault.models.Key; -//import com.azure.resourcemanager.keyvault.models.KeyPermissions; -//import com.azure.resourcemanager.keyvault.models.SkuName; -//import com.azure.resourcemanager.keyvault.models.Vault; -//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.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlServerKey; -//import com.azure.security.keyvault.keys.models.KeyOperation; -//import com.azure.security.keyvault.keys.models.KeyType; -// -//import java.time.Duration; -//import java.util.ArrayList; -//import java.util.List; -// -///** -// * Azure SQL sample for managing SQL secrets (Server Keys) using Azure Key Vault - -// * - Create a SQL Server with "system assigned" managed service identity. -// * - Create an Azure Key Vault with giving access to the SQL Server -// * - Create, get, list and delete SQL Server Keys -// * - Delete SQL Server -// */ -// -//public class ManageSqlServerKeysWithAzureKeyVaultKey { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @param objectId the object ID of the service principal/user used to authenticate to Azure -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager, String objectId) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlsrv", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// final String vaultName = Utils.randomResourceName(azureResourceManager, "sqlkv", 20); -// final String keyName = Utils.randomResourceName(azureResourceManager, "sqlkey", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// -// try { -// -// // ============================================================ -// // Create a SQL Server with system assigned managed service identity. -// System.out.println("Creating a SQL Server with system assigned managed service identity"); -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .withSystemAssignedManagedServiceIdentity() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // Create an Azure Key Vault and set the access policies. -// System.out.println("Creating an Azure Key Vault and set the access policies"); -// -// Vault vault = azureResourceManager.vaults().define(vaultName) -// .withRegion(Region.US_EAST) -// .withExistingResourceGroup(rgName) -// .defineAccessPolicy() -// .forObjectId(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()) -// .allowKeyPermissions(KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY, KeyPermissions.GET, KeyPermissions.LIST) -// .attach() -// .defineAccessPolicy() -// .forServicePrincipal(objectId) -// .allowKeyAllPermissions() -// .attach() -// .withSku(SkuName.PREMIUM) -// .withSoftDeleteEnabled() -// .create(); -// -// ResourceManagerUtils.sleep(Duration.ofMinutes(3)); -// -// List keyOperations = new ArrayList<>(); -// for (KeyOperation operation : KeyOperation.values()) { -// if (operation != KeyOperation.IMPORT) { -// keyOperations.add(operation); -// } -// } -// -// Key keyBundle = vault.keys().define(keyName) -// .withKeyTypeToCreate(KeyType.RSA_HSM) -// .withKeyOperations(keyOperations) -// .create(); -// -// // ============================================================ -// // Create a SQL server key with Azure Key Vault key. -// System.out.println("Creating a SQL server key with Azure Key Vault key"); -// -// String keyUri = keyBundle.getJsonWebKey().getId(); -// -// // Work around for SQL server key name must be formatted as "vault_key_version" -// String serverKeyName = String.format("%s_%s_%s", vaultName, keyName, -// keyUri.substring(keyUri.lastIndexOf("/") + 1)); -// -// SqlServerKey sqlServerKey = sqlServer.serverKeys().define() -// .withAzureKeyVaultKey(keyUri) -// .create(); -// -// Utils.print(sqlServerKey); -// -// -// // Validate key exists by getting key -// System.out.println("Validating key exists by getting the key"); -// -// sqlServerKey = sqlServer.serverKeys().get(serverKeyName); -// -// Utils.print(sqlServerKey); -// -// -// // Validate key exists by listing keys -// System.out.println("Validating key exists by listing keys"); -// -// List serverKeys = sqlServer.serverKeys().list(); -// for (SqlServerKey item : serverKeys) { -// Utils.print(item); -// } -// -// -// // Delete key -// System.out.println("Deleting the key"); -// -// azureResourceManager.sqlServers().serverKeys().deleteBySqlServer(rgName, sqlServerName, serverKeyName); -// -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// final Configuration configuration = Configuration.getGlobalConfiguration(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager, configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID)); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.util.Configuration; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.keyvault.models.Key; +import com.azure.resourcemanager.keyvault.models.KeyPermissions; +import com.azure.resourcemanager.keyvault.models.SkuName; +import com.azure.resourcemanager.keyvault.models.Vault; +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.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlServerKey; +import com.azure.security.keyvault.keys.models.KeyOperation; +import com.azure.security.keyvault.keys.models.KeyType; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; + +/** + * Azure SQL sample for managing SQL secrets (Server Keys) using Azure Key Vault - + * - Create a SQL Server with "system assigned" managed service identity. + * - Create an Azure Key Vault with giving access to the SQL Server + * - Create, get, list and delete SQL Server Keys + * - Delete SQL Server + */ + +public class ManageSqlServerKeysWithAzureKeyVaultKey { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @param objectId the object ID of the service principal/user used to authenticate to Azure + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager, String objectId) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlsrv", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + final String vaultName = Utils.randomResourceName(azureResourceManager, "sqlkv", 20); + final String keyName = Utils.randomResourceName(azureResourceManager, "sqlkey", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + + try { + + // ============================================================ + // Create a SQL Server with system assigned managed service identity. + System.out.println("Creating a SQL Server with system assigned managed service identity"); + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .withSystemAssignedManagedServiceIdentity() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // Create an Azure Key Vault and set the access policies. + System.out.println("Creating an Azure Key Vault and set the access policies"); + + Vault vault = azureResourceManager.vaults().define(vaultName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .defineAccessPolicy() + .forObjectId(sqlServer.systemAssignedManagedServiceIdentityPrincipalId()) + .allowKeyPermissions(KeyPermissions.WRAP_KEY, KeyPermissions.UNWRAP_KEY, KeyPermissions.GET, KeyPermissions.LIST) + .attach() + .defineAccessPolicy() + .forServicePrincipal(objectId) + .allowKeyAllPermissions() + .attach() + .withSku(SkuName.PREMIUM) + .withSoftDeleteEnabled() + .create(); + + ResourceManagerUtils.sleep(Duration.ofMinutes(3)); + + List keyOperations = new ArrayList<>(); + for (KeyOperation operation : KeyOperation.values()) { + if (operation != KeyOperation.IMPORT) { + keyOperations.add(operation); + } + } + + Key keyBundle = vault.keys().define(keyName) + .withKeyTypeToCreate(KeyType.RSA_HSM) + .withKeyOperations(keyOperations) + .create(); + + // ============================================================ + // Create a SQL server key with Azure Key Vault key. + System.out.println("Creating a SQL server key with Azure Key Vault key"); + + String keyUri = keyBundle.getJsonWebKey().getId(); + + // Work around for SQL server key name must be formatted as "vault_key_version" + String serverKeyName = String.format("%s_%s_%s", vaultName, keyName, + keyUri.substring(keyUri.lastIndexOf("/") + 1)); + + SqlServerKey sqlServerKey = sqlServer.serverKeys().define() + .withAzureKeyVaultKey(keyUri) + .create(); + + Utils.print(sqlServerKey); + + + // Validate key exists by getting key + System.out.println("Validating key exists by getting the key"); + + sqlServerKey = sqlServer.serverKeys().get(serverKeyName); + + Utils.print(sqlServerKey); + + + // Validate key exists by listing keys + System.out.println("Validating key exists by listing keys"); + + List serverKeys = sqlServer.serverKeys().list(); + for (SqlServerKey item : serverKeys) { + Utils.print(item); + } + + + // Delete key + System.out.println("Deleting the key"); + + azureResourceManager.sqlServers().serverKeys().deleteBySqlServer(rgName, sqlServerName, serverKeyName); + + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + final Configuration configuration = Configuration.getGlobalConfiguration(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager, configuration.get(Configuration.PROPERTY_AZURE_CLIENT_ID)); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java index 1bacd29f8e3e..5e20ea526e6c 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlServerSecurityAlertPolicy.java @@ -1,142 +1,142 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SampleName; -//import com.azure.resourcemanager.sql.models.SecurityAlertPolicyState; -//import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlServerSecurityAlertPolicy; -//import com.azure.resourcemanager.storage.models.StorageAccount; -// -///** -// * Azure SQL sample for managing SQL Server Security Alert Policy -// * - Create a SQL Server. -// * - Create an Azure Storage Account and get the storage account blob entry point -// * - Create a Server Security Alert Policy -// * - Get the Server Security Alert Policy. -// * - Update the Server Security Alert Policy. -// * - Delete the Sql Server -// */ -//public class ManageSqlServerSecurityAlertPolicy { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sql", 20); -// final String storageAccountName = Utils.randomResourceName(azureResourceManager, "sqlsa", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// final Region region = Region.US_EAST; -// final String dbName = "dbSample"; -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// -// try { -// -// // ============================================================ -// // Create a primary SQL Server with a sample database. -// System.out.println("Creating a primary SQL Server with a sample database"); -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(region) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineDatabase(dbName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) -// .attach() -// .create(); -// -// Utils.print(sqlServer); -// -// // ============================================================ -// // Create an Azure Storage Account and get the storage account blob entry point. -// System.out.println("Creating an Azure Storage Account and a storage account blob"); -// StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .create(); -// String accountKey = storageAccount.getKeys().get(0).value(); -// String blobEntrypoint = storageAccount.endPoints().primary().blob(); -// -// // ============================================================ -// // Create a Server Security Alert Policy. -// System.out.println("Creating a Server Security Alert Policy"); -// sqlServer.serverSecurityAlertPolicies().define() -// .withState(SecurityAlertPolicyState.ENABLED) -// .withEmailAccountAdmins() -// .withStorageEndpoint(blobEntrypoint, accountKey) -// .withDisabledAlerts("Access_Anomaly", "Sql_Injection") -// .withRetentionDays(5) -// .create(); -// -// -// // ============================================================ -// // Get the Server Security Alert Policy. -// System.out.println("Getting the Server Security Alert Policy"); -// SqlServerSecurityAlertPolicy sqlSecurityAlertPolicy = sqlServer.serverSecurityAlertPolicies().get(); -// -// -// // ============================================================ -// // Update the Server Security Alert Policy. -// System.out.println("Updating the Server Security Alert Policy"); -// sqlSecurityAlertPolicy.update() -// .withoutEmailAccountAdmins() -// .withEmailAddresses("testSecurityAlert@contoso.com") -// .withRetentionDays(1) -// .apply(); -// -// -// // Delete the SQL Servers. -// System.out.println("Deleting the Sql Servers"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SecurityAlertPolicyState; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlServerSecurityAlertPolicy; +import com.azure.resourcemanager.storage.models.StorageAccount; + +/** + * Azure SQL sample for managing SQL Server Security Alert Policy + * - Create a SQL Server. + * - Create an Azure Storage Account and get the storage account blob entry point + * - Create a Server Security Alert Policy + * - Get the Server Security Alert Policy. + * - Update the Server Security Alert Policy. + * - Delete the Sql Server + */ +public class ManageSqlServerSecurityAlertPolicy { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sql", 20); + final String storageAccountName = Utils.randomResourceName(azureResourceManager, "sqlsa", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + final Region region = Region.US_EAST; + final String dbName = "dbSample"; + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + + try { + + // ============================================================ + // Create a primary SQL Server with a sample database. + System.out.println("Creating a primary SQL Server with a sample database"); + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(region) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); + + Utils.print(sqlServer); + + // ============================================================ + // Create an Azure Storage Account and get the storage account blob entry point. + System.out.println("Creating an Azure Storage Account and a storage account blob"); + StorageAccount storageAccount = azureResourceManager.storageAccounts().define(storageAccountName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .create(); + String accountKey = storageAccount.getKeys().get(0).value(); + String blobEntrypoint = storageAccount.endPoints().primary().blob(); + + // ============================================================ + // Create a Server Security Alert Policy. + System.out.println("Creating a Server Security Alert Policy"); + sqlServer.serverSecurityAlertPolicies().define() + .withState(SecurityAlertPolicyState.ENABLED) + .withEmailAccountAdmins() + .withStorageEndpoint(blobEntrypoint, accountKey) + .withDisabledAlerts("Access_Anomaly", "Sql_Injection") + .withRetentionDays(5) + .create(); + + + // ============================================================ + // Get the Server Security Alert Policy. + System.out.println("Getting the Server Security Alert Policy"); + SqlServerSecurityAlertPolicy sqlSecurityAlertPolicy = sqlServer.serverSecurityAlertPolicies().get(); + + + // ============================================================ + // Update the Server Security Alert Policy. + System.out.println("Updating the Server Security Alert Policy"); + sqlSecurityAlertPolicy.update() + .withoutEmailAccountAdmins() + .withEmailAddresses("testSecurityAlert@contoso.com") + .withRetentionDays(1) + .apply(); + + + // Delete the SQL Servers. + System.out.println("Deleting the Sql Servers"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java index 3a1416fe7f36..fe86584c9ebc 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlVirtualNetworkRules.java @@ -1,168 +1,168 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.network.models.Network; -//import com.azure.resourcemanager.network.models.ServiceEndpointType; -//import com.azure.core.management.Region; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; -// -//import java.util.List; -// -///** -// * Azure SQL sample for managing SQL Virtual Network Rules -// * - Create a Virtual Network with two subnets. -// * - Create a SQL Server along with one virtual network rule. -// * - Add another virtual network rule in the SQL Server -// * - Get a virtual network rule. -// * - Update a virtual network rule. -// * - List all virtual network rules. -// * - Delete a virtual network. -// * - Delete Sql Server -// */ -// -//public class ManageSqlVirtualNetworkRules { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String vnetName = Utils.randomResourceName(azureResourceManager, "vnetsql", 20); -// -// try { -// -// // ============================================================ -// // Create a virtual network with two subnets. -// System.out.println("Create a virtual network with two subnets: subnet1 and subnet2"); -// -// Network virtualNetwork = azureResourceManager.networks().define(vnetName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAddressSpace("192.168.0.0/16") -// .defineSubnet("subnet1") -// .withAddressPrefix("192.168.1.0/24") -// .withAccessFromService(ServiceEndpointType.MICROSOFT_SQL) -// .attach() -// .withSubnet("subnet2", "192.168.2.0/24") -// .create(); -// -// System.out.println("Created a virtual network"); -// // Print the virtual network details -// Utils.print(virtualNetwork); -// -// // ============================================================ -// // Create a SQL Server, with one virtual network rule. -// System.out.println("Create a SQL server with one virtual network rule"); -// -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withExistingResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .withoutAccessFromAzureServices() -// .defineVirtualNetworkRule("virtualNetworkRule1") -// .withSubnet(virtualNetwork.id(), "subnet1") -// .attach() -// .create(); -// -// Utils.print(sqlServer); -// -// -// // ============================================================ -// // Get the virtual network rule created above. -// SqlVirtualNetworkRule virtualNetworkRule = azureResourceManager.sqlServers().virtualNetworkRules() -// .getBySqlServer(rgName, sqlServerName, "virtualNetworkRule1"); -// -// Utils.print(virtualNetworkRule); -// -// -// // ============================================================ -// // Add new virtual network rules. -// System.out.println("adding another virtual network rule in existing SQL Server"); -// virtualNetworkRule = sqlServer.virtualNetworkRules() -// .define("virtualNetworkRule2") -// .withSubnet(virtualNetwork.id(), "subnet2") -// .ignoreMissingSqlServiceEndpoint() -// .create(); -// -// Utils.print(virtualNetworkRule); -// -// -// // ============================================================ -// // Update a virtual network rules. -// System.out.println("Updating an existing virtual network rules in SQL Server."); -// virtualNetworkRule.update() -// .withSubnet(virtualNetwork.id(), "subnet1") -// .apply(); -// -// Utils.print(virtualNetworkRule); -// -// -// // ============================================================ -// // List and delete all virtual network rules. -// System.out.println("Listing all virtual network rules in SQL Server."); -// -// List virtualNetworkRules = sqlServer.virtualNetworkRules().list(); -// for (SqlVirtualNetworkRule vnetRule : virtualNetworkRules) { -// // Delete the virtual network rule. -// System.out.println("Deleting a virtual network rule"); -// vnetRule.delete(); -// } -// -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.network.models.Network; +import com.azure.resourcemanager.network.models.ServiceEndpointType; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlVirtualNetworkRule; + +import java.util.List; + +/** + * Azure SQL sample for managing SQL Virtual Network Rules + * - Create a Virtual Network with two subnets. + * - Create a SQL Server along with one virtual network rule. + * - Add another virtual network rule in the SQL Server + * - Get a virtual network rule. + * - Update a virtual network rule. + * - List all virtual network rules. + * - Delete a virtual network. + * - Delete Sql Server + */ + +public class ManageSqlVirtualNetworkRules { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgRSSDFW", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String vnetName = Utils.randomResourceName(azureResourceManager, "vnetsql", 20); + + try { + + // ============================================================ + // Create a virtual network with two subnets. + System.out.println("Create a virtual network with two subnets: subnet1 and subnet2"); + + Network virtualNetwork = azureResourceManager.networks().define(vnetName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAddressSpace("192.168.0.0/16") + .defineSubnet("subnet1") + .withAddressPrefix("192.168.1.0/24") + .withAccessFromService(ServiceEndpointType.MICROSOFT_SQL) + .attach() + .withSubnet("subnet2", "192.168.2.0/24") + .create(); + + System.out.println("Created a virtual network"); + // Print the virtual network details + Utils.print(virtualNetwork); + + // ============================================================ + // Create a SQL Server, with one virtual network rule. + System.out.println("Create a SQL server with one virtual network rule"); + + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withExistingResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .withoutAccessFromAzureServices() + .defineVirtualNetworkRule("virtualNetworkRule1") + .withSubnet(virtualNetwork.id(), "subnet1") + .attach() + .create(); + + Utils.print(sqlServer); + + + // ============================================================ + // Get the virtual network rule created above. + SqlVirtualNetworkRule virtualNetworkRule = azureResourceManager.sqlServers().virtualNetworkRules() + .getBySqlServer(rgName, sqlServerName, "virtualNetworkRule1"); + + Utils.print(virtualNetworkRule); + + + // ============================================================ + // Add new virtual network rules. + System.out.println("adding another virtual network rule in existing SQL Server"); + virtualNetworkRule = sqlServer.virtualNetworkRules() + .define("virtualNetworkRule2") + .withSubnet(virtualNetwork.id(), "subnet2") + .ignoreMissingSqlServiceEndpoint() + .create(); + + Utils.print(virtualNetworkRule); + + + // ============================================================ + // Update a virtual network rules. + System.out.println("Updating an existing virtual network rules in SQL Server."); + virtualNetworkRule.update() + .withSubnet(virtualNetwork.id(), "subnet1") + .apply(); + + Utils.print(virtualNetworkRule); + + + // ============================================================ + // List and delete all virtual network rules. + System.out.println("Listing all virtual network rules in SQL Server."); + + List virtualNetworkRules = sqlServer.virtualNetworkRules().list(); + for (SqlVirtualNetworkRule vnetRule : virtualNetworkRules) { + // Delete the virtual network rule. + System.out.println("Deleting a virtual network rule"); + vnetRule.delete(); + } + + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java index 04e5d5d62fb7..a290c6aa2c90 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/sql/samples/ManageSqlWithRecoveredOrRestoredDatabase.java @@ -1,181 +1,181 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.sql.samples; -// -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//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.resourcemanager.sql.models.RestorePoint; -//import com.azure.resourcemanager.sql.models.SampleName; -//import com.azure.resourcemanager.sql.models.SqlDatabase; -//import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; -//import com.azure.resourcemanager.sql.models.SqlRestorableDroppedDatabase; -//import com.azure.resourcemanager.sql.models.SqlServer; -// -//import java.time.Duration; -//import java.time.OffsetDateTime; -//import java.time.temporal.ChronoUnit; -// -///** -// * Azure SQL sample for managing point in time restore and recover a deleted SQL Database - -// * - Create a SQL Server with two database from a pre-existing sample. -// * - Create a new database from a point in time restore -// * - Delete a database then restore it from a recoverable dropped database automatic backup -// * - Delete databases and SQL Server -// */ -//public final class ManageSqlWithRecoveredOrRestoredDatabase { -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); -// final String administratorLogin = "sqladmin3423"; -// final String administratorPassword = Utils.password(); -// final String dbToDeleteName = "db-to-delete"; -// final String dbToRestoreName = "db-to-restore"; -// try { -// -// // ============================================================ -// // Create a SQL Server with two databases from a sample. -// System.out.println("Creating a SQL Server with two databases from a sample."); -// SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withAdministratorLogin(administratorLogin) -// .withAdministratorPassword(administratorPassword) -// .defineDatabase(dbToDeleteName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) -// .attach() -// .defineDatabase(dbToRestoreName) -// .fromSample(SampleName.ADVENTURE_WORKS_LT) -// .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) -// .attach() -// .create(); -// Utils.print(sqlServer); -// -// // Sleep for 5 minutes to allow for the service to be aware of the new server and databases -// ResourceManagerUtils.sleep(Duration.ofMinutes(5)); -// -// SqlDatabase dbToBeDeleted = sqlServer.databases() -// .get(dbToDeleteName); -// Utils.print(dbToBeDeleted); -// SqlDatabase dbToRestore = sqlServer.databases() -// .get(dbToRestoreName); -// Utils.print(dbToRestore); -// -// // ============================================================ -// // Loop until a point in time restore is available. -// System.out.println("Loop until a point in time restore is available."); -// -// int retries = 50; -// while (retries > 0 && dbToRestore.listRestorePoints().size() == 0) { -// retries--; -// // Sleep for about 3 minutes -// ResourceManagerUtils.sleep(Duration.ofMinutes(3)); -// } -// if (retries == 0) { -// return false; -// } -// -// RestorePoint restorePointInTime = dbToRestore.listRestorePoints().get(0); -// // Restore point might not be ready right away and we will have to wait for it. -// OffsetDateTime currentTime = OffsetDateTime.now(); -// long waitForRestoreToBeReady = ChronoUnit.MILLIS.between(currentTime, restorePointInTime.earliestRestoreDate()) -// + 5 * 60 * 1000; -// System.out.printf("waitForRestoreToBeReady %d%n", waitForRestoreToBeReady); -// if (waitForRestoreToBeReady > 0) { -// ResourceManagerUtils.sleep(Duration.ofMillis(waitForRestoreToBeReady)); -// } -// -// SqlDatabase dbRestorePointInTime = sqlServer.databases() -// .define("db-restore-pit") -// .fromRestorePoint(restorePointInTime) -// .create(); -// Utils.print(dbRestorePointInTime); -// dbRestorePointInTime.delete(); -// -// // ============================================================ -// // Restore the database form a point in time restore which is 5 minutes ago. -// dbRestorePointInTime = sqlServer.databases() -// .define("db-restore-pit-2") -// .fromRestorePoint(restorePointInTime, OffsetDateTime.now().minusMinutes(5)) -// .create(); -// Utils.print(dbRestorePointInTime); -// dbRestorePointInTime.delete(); -// -// // ============================================================ -// // Delete the database than loop until the restorable dropped database backup is available. -// System.out.println("Deleting the database than loop until the restorable dropped database backup is available."); -// -// dbToBeDeleted.delete(); -// retries = 24; -// while (retries > 0 && sqlServer.listRestorableDroppedDatabases().size() == 0) { -// retries--; -// // Sleep for about 5 minutes -// ResourceManagerUtils.sleep(Duration.ofMinutes(5)); -// } -// SqlRestorableDroppedDatabase restorableDroppedDatabase = sqlServer.listRestorableDroppedDatabases().get(0); -// SqlDatabase dbRestoreDeleted = sqlServer.databases() -// .define("db-restore-deleted") -// .fromRestorableDroppedDatabase(restorableDroppedDatabase) -// .create(); -// Utils.print(dbRestoreDeleted); -// -// // Delete databases -// dbToRestore.delete(); -// dbRestoreDeleted.delete(); -// -// // Delete the SQL Server. -// System.out.println("Deleting a Sql Server"); -// azureResourceManager.sqlServers().deleteById(sqlServer.id()); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().beginDeleteByName(rgName); -// System.out.println("Deleted Resource Group: " + rgName); -// } catch (Exception e) { -// System.out.println("Did not create any resources in Azure. No clean up is necessary"); -// } -// } -// } -// -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.sql.samples; + + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +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.resourcemanager.sql.models.RestorePoint; +import com.azure.resourcemanager.sql.models.SampleName; +import com.azure.resourcemanager.sql.models.SqlDatabase; +import com.azure.resourcemanager.sql.models.SqlDatabaseStandardServiceObjective; +import com.azure.resourcemanager.sql.models.SqlRestorableDroppedDatabase; +import com.azure.resourcemanager.sql.models.SqlServer; + +import java.time.Duration; +import java.time.OffsetDateTime; +import java.time.temporal.ChronoUnit; + +/** + * Azure SQL sample for managing point in time restore and recover a deleted SQL Database - + * - Create a SQL Server with two database from a pre-existing sample. + * - Create a new database from a point in time restore + * - Delete a database then restore it from a recoverable dropped database automatic backup + * - Delete databases and SQL Server + */ +public final class ManageSqlWithRecoveredOrRestoredDatabase { + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String sqlServerName = Utils.randomResourceName(azureResourceManager, "sqlserver", 20); + final String rgName = Utils.randomResourceName(azureResourceManager, "rgsql", 20); + final String administratorLogin = "sqladmin3423"; + final String administratorPassword = Utils.password(); + final String dbToDeleteName = "db-to-delete"; + final String dbToRestoreName = "db-to-restore"; + try { + + // ============================================================ + // Create a SQL Server with two databases from a sample. + System.out.println("Creating a SQL Server with two databases from a sample."); + SqlServer sqlServer = azureResourceManager.sqlServers().define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withAdministratorLogin(administratorLogin) + .withAdministratorPassword(administratorPassword) + .defineDatabase(dbToDeleteName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .defineDatabase(dbToRestoreName) + .fromSample(SampleName.ADVENTURE_WORKS_LT) + .withStandardEdition(SqlDatabaseStandardServiceObjective.S0) + .attach() + .create(); + Utils.print(sqlServer); + + // Sleep for 5 minutes to allow for the service to be aware of the new server and databases + ResourceManagerUtils.sleep(Duration.ofMinutes(5)); + + SqlDatabase dbToBeDeleted = sqlServer.databases() + .get(dbToDeleteName); + Utils.print(dbToBeDeleted); + SqlDatabase dbToRestore = sqlServer.databases() + .get(dbToRestoreName); + Utils.print(dbToRestore); + + // ============================================================ + // Loop until a point in time restore is available. + System.out.println("Loop until a point in time restore is available."); + + int retries = 50; + while (retries > 0 && dbToRestore.listRestorePoints().size() == 0) { + retries--; + // Sleep for about 3 minutes + ResourceManagerUtils.sleep(Duration.ofMinutes(3)); + } + if (retries == 0) { + return false; + } + + RestorePoint restorePointInTime = dbToRestore.listRestorePoints().get(0); + // Restore point might not be ready right away and we will have to wait for it. + OffsetDateTime currentTime = OffsetDateTime.now(); + long waitForRestoreToBeReady = ChronoUnit.MILLIS.between(currentTime, restorePointInTime.earliestRestoreDate()) + + 5 * 60 * 1000; + System.out.printf("waitForRestoreToBeReady %d%n", waitForRestoreToBeReady); + if (waitForRestoreToBeReady > 0) { + ResourceManagerUtils.sleep(Duration.ofMillis(waitForRestoreToBeReady)); + } + + SqlDatabase dbRestorePointInTime = sqlServer.databases() + .define("db-restore-pit") + .fromRestorePoint(restorePointInTime) + .create(); + Utils.print(dbRestorePointInTime); + dbRestorePointInTime.delete(); + + // ============================================================ + // Restore the database form a point in time restore which is 5 minutes ago. + dbRestorePointInTime = sqlServer.databases() + .define("db-restore-pit-2") + .fromRestorePoint(restorePointInTime, OffsetDateTime.now().minusMinutes(5)) + .create(); + Utils.print(dbRestorePointInTime); + dbRestorePointInTime.delete(); + + // ============================================================ + // Delete the database than loop until the restorable dropped database backup is available. + System.out.println("Deleting the database than loop until the restorable dropped database backup is available."); + + dbToBeDeleted.delete(); + retries = 24; + while (retries > 0 && sqlServer.listRestorableDroppedDatabases().size() == 0) { + retries--; + // Sleep for about 5 minutes + ResourceManagerUtils.sleep(Duration.ofMinutes(5)); + } + SqlRestorableDroppedDatabase restorableDroppedDatabase = sqlServer.listRestorableDroppedDatabases().get(0); + SqlDatabase dbRestoreDeleted = sqlServer.databases() + .define("db-restore-deleted") + .fromRestorableDroppedDatabase(restorableDroppedDatabase) + .create(); + Utils.print(dbRestoreDeleted); + + // Delete databases + dbToRestore.delete(); + dbRestoreDeleted.delete(); + + // Delete the SQL Server. + System.out.println("Deleting a Sql Server"); + azureResourceManager.sqlServers().deleteById(sqlServer.id()); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().beginDeleteByName(rgName); + System.out.println("Deleted Resource Group: " + rgName); + } catch (Exception e) { + System.out.println("Did not create any resources in Azure. No clean up is necessary"); + } + } + } + + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java index 65c99e8d52cf..fabc1d6d40d2 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageSimpleTrafficManager.java @@ -1,183 +1,183 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.trafficmanager.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; -//import com.azure.resourcemanager.compute.models.VirtualMachine; -//import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.resourcemanager.resources.models.ResourceGroup; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; -//import org.apache.commons.lang.time.StopWatch; -// -//import java.util.ArrayList; -//import java.util.Arrays; -//import java.util.Collection; -//import java.util.HashSet; -//import java.util.List; -//import java.util.Set; -// -///** -// * Simple Azure traffic manager sample. -// * - Create 4 VMs spread across 2 regions -// * - Create a traffic manager in front of the VMs -// * - Change/configure traffic manager routing method -// */ -//public final class ManageSimpleTrafficManager { -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOPD", 24); -// final String userName = "tirekicker"; -// final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; -// final int vmCountPerRegion = 2; -// Set regions = new HashSet<>(Arrays.asList( -// Region.US_EAST2, -// Region.ASIA_SOUTHEAST -// )); -// -// try { -// //============================================================= -// // Create a shared resource group for all the resources so they can all be deleted together -// // -// ResourceGroup resourceGroup = azureResourceManager.resourceGroups() -// .define(rgName) -// .withRegion(Region.US_EAST2) -// .create(); -// -// System.out.println("Created a new resource group - " + resourceGroup.id()); -// -// // Prepare a batch of creatable VM definitions to put behind the traffic manager -// // -// List> creatableVirtualMachines = new ArrayList<>(); -// -// for (Region region : regions) { -// String linuxVMNamePrefix = Utils.randomResourceName(azureResourceManager, "vm", 15); -// for (int i = 0; i < vmCountPerRegion; i++) { -// //============================================================= -// // Create a virtual machine in its own virtual network -// String vmName = String.format("%s-%d", linuxVMNamePrefix, i); -// Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) -// .withRegion(region) -// .withExistingResourceGroup(resourceGroup) -// .withNewPrimaryNetwork("10.0.0.0/29") -// .withPrimaryPrivateIPAddressDynamic() -// .withNewPrimaryPublicIPAddress(vmName) -// .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) -// .withRootUsername(userName) -// .withSsh(sshKey) -// .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); -// creatableVirtualMachines.add(vmDefinition); -// } -// } -// -// -// //============================================================= -// // Create the VMs !! -// -// StopWatch stopwatch = new StopWatch(); -// System.out.println("Creating the virtual machines..."); -// stopwatch.start(); -// -// Collection virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); -// -// stopwatch.stop(); -// System.out.println(String.format("Created virtual machines in %d seconds.", stopwatch.getTime() / 1000)); -// -// //============================================================= -// // Create 1 traffic manager profile -// // -// String trafficManagerName = Utils.randomResourceName(azureResourceManager, "tra", 15); -// TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azureResourceManager.trafficManagerProfiles() -// .define(trafficManagerName) -// .withExistingResourceGroup(resourceGroup) -// .withLeafDomainLabel(trafficManagerName) -// .withPerformanceBasedRouting(); -// -// TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null; -// int routingPriority = 1; -// for (VirtualMachine vm : virtualMachines) { -// String endpointName = Utils.randomResourceName(azureResourceManager, "ep", 15); -// profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName) -// .toResourceId(vm.getPrimaryPublicIPAddressId()) -// .withRoutingPriority(routingPriority++) -// .attach(); -// } -// -// stopwatch.reset(); -// stopwatch.start(); -// -// TrafficManagerProfile trafficManagerProfile = profileWithCreate.create(); -// -// stopwatch.stop(); -// System.out.printf("Created a traffic manager profile %s in %d seconds.%n", trafficManagerProfile.id(), stopwatch.getTime() / 1000); -// -// //============================================================= -// // Modify the traffic manager to use priority based routing -// // -// -// trafficManagerProfile.update() -// .withPriorityBasedRouting() -// .apply(); -// -// System.out.println("Modified the traffic manager to use priority-based routing."); -// return true; -// } finally { -// -// try { -// System.out.println("Deleting Resource Group: " + rgName); -// azureResourceManager.resourceGroups().deleteByName(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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// // -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -// -// private ManageSimpleTrafficManager() { -// } -//} +package com.azure.resourcemanager.trafficmanager.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; +import com.azure.resourcemanager.compute.models.VirtualMachine; +import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.resourcemanager.resources.models.ResourceGroup; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; +import org.apache.commons.lang.time.StopWatch; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Simple Azure traffic manager sample. + * - Create 4 VMs spread across 2 regions + * - Create a traffic manager in front of the VMs + * - Change/configure traffic manager routing method + */ +public final class ManageSimpleTrafficManager { + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgCOPD", 24); + final String userName = "tirekicker"; + final String sshKey = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCfSPC2K7LZcFKEO+/t3dzmQYtrJFZNxOsbVgOVKietqHyvmYGHEC0J2wPdAqQ/63g/hhAEFRoyehM+rbeDri4txB3YFfnOK58jqdkyXzupWqXzOrlKY4Wz9SKjjN765+dqUITjKRIaAip1Ri137szRg71WnrmdP3SphTRlCx1Bk2nXqWPsclbRDCiZeF8QOTi4JqbmJyK5+0UqhqYRduun8ylAwKKQJ1NJt85sYIHn9f1Rfr6Tq2zS0wZ7DHbZL+zB5rSlAr8QyUdg/GQD+cmSs6LvPJKL78d6hMGk84ARtFo4A79ovwX/Fj01znDQkU6nJildfkaolH2rWFG/qttD azjava@javalib.com"; + final int vmCountPerRegion = 2; + Set regions = new HashSet<>(Arrays.asList( + Region.US_EAST2, + Region.ASIA_SOUTHEAST + )); + + try { + //============================================================= + // Create a shared resource group for all the resources so they can all be deleted together + // + ResourceGroup resourceGroup = azureResourceManager.resourceGroups() + .define(rgName) + .withRegion(Region.US_EAST2) + .create(); + + System.out.println("Created a new resource group - " + resourceGroup.id()); + + // Prepare a batch of creatable VM definitions to put behind the traffic manager + // + List> creatableVirtualMachines = new ArrayList<>(); + + for (Region region : regions) { + String linuxVMNamePrefix = Utils.randomResourceName(azureResourceManager, "vm", 15); + for (int i = 0; i < vmCountPerRegion; i++) { + //============================================================= + // Create a virtual machine in its own virtual network + String vmName = String.format("%s-%d", linuxVMNamePrefix, i); + Creatable vmDefinition = azureResourceManager.virtualMachines().define(vmName) + .withRegion(region) + .withExistingResourceGroup(resourceGroup) + .withNewPrimaryNetwork("10.0.0.0/29") + .withPrimaryPrivateIPAddressDynamic() + .withNewPrimaryPublicIPAddress(vmName) + .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) + .withRootUsername(userName) + .withSsh(sshKey) + .withSize(VirtualMachineSizeTypes.fromString("Standard_D2a_v4")); + creatableVirtualMachines.add(vmDefinition); + } + } + + + //============================================================= + // Create the VMs !! + + StopWatch stopwatch = new StopWatch(); + System.out.println("Creating the virtual machines..."); + stopwatch.start(); + + Collection virtualMachines = azureResourceManager.virtualMachines().create(creatableVirtualMachines).values(); + + stopwatch.stop(); + System.out.println(String.format("Created virtual machines in %d seconds.", stopwatch.getTime() / 1000)); + + //============================================================= + // Create 1 traffic manager profile + // + String trafficManagerName = Utils.randomResourceName(azureResourceManager, "tra", 15); + TrafficManagerProfile.DefinitionStages.WithEndpoint profileWithEndpoint = azureResourceManager.trafficManagerProfiles() + .define(trafficManagerName) + .withExistingResourceGroup(resourceGroup) + .withLeafDomainLabel(trafficManagerName) + .withPerformanceBasedRouting(); + + TrafficManagerProfile.DefinitionStages.WithCreate profileWithCreate = null; + int routingPriority = 1; + for (VirtualMachine vm : virtualMachines) { + String endpointName = Utils.randomResourceName(azureResourceManager, "ep", 15); + profileWithCreate = profileWithEndpoint.defineAzureTargetEndpoint(endpointName) + .toResourceId(vm.getPrimaryPublicIPAddressId()) + .withRoutingPriority(routingPriority++) + .attach(); + } + + stopwatch.reset(); + stopwatch.start(); + + TrafficManagerProfile trafficManagerProfile = profileWithCreate.create(); + + stopwatch.stop(); + System.out.printf("Created a traffic manager profile %s in %d seconds.%n", trafficManagerProfile.id(), stopwatch.getTime() / 1000); + + //============================================================= + // Modify the traffic manager to use priority based routing + // + + trafficManagerProfile.update() + .withPriorityBasedRouting() + .apply(); + + System.out.println("Modified the traffic manager to use priority-based routing."); + return true; + } finally { + + try { + System.out.println("Deleting Resource Group: " + rgName); + azureResourceManager.resourceGroups().deleteByName(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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + // + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } + + private ManageSimpleTrafficManager() { + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java index 7ef555aaea4d..77dfaa7d7eff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java @@ -1,274 +1,274 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager.trafficmanager.samples; -// -//import com.azure.core.credential.TokenCredential; -//import com.azure.core.http.policy.HttpLogDetailLevel; -//import com.azure.core.management.AzureEnvironment; -//import com.azure.core.management.profile.AzureProfile; -//import com.azure.identity.DefaultAzureCredentialBuilder; -//import com.azure.resourcemanager.AzureResourceManager; -//import com.azure.resourcemanager.appservice.models.AppServiceDomain; -//import com.azure.resourcemanager.appservice.models.AppServicePlan; -//import com.azure.resourcemanager.appservice.models.OperatingSystem; -//import com.azure.resourcemanager.appservice.models.PricingTier; -//import com.azure.resourcemanager.appservice.models.WebApp; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; -//import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.fluentcore.model.Creatable; -//import com.azure.resourcemanager.samples.Utils; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; -// -//import java.io.File; -//import java.io.IOException; -//import java.util.ArrayList; -//import java.util.List; -// -///** -// * Azure traffic manager sample for managing profiles. -// * - Create a domain -// * - Create a self-signed certificate for the domain -// * - Create 5 app service plans in 5 different regions -// * - Create 5 web apps under the each plan, bound to the domain and the certificate -// * - Create a traffic manager in front of the web apps -// * - Disable an endpoint -// * - Delete an endpoint -// * - Enable an endpoint -// * - Change/configure traffic manager routing method -// * - Disable traffic manager profile -// * - Enable traffic manager profile -// */ -//public final class ManageTrafficManager { -// -// -// /** -// * Main function which runs the actual sample. -// * @param azureResourceManager instance of the azure client -// * @return true if sample runs successfully -// */ -// public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { -// final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); -// final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; -// // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")] -// final String certPassword = "StrongPass!12"; -// final String appServicePlanNamePrefix = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); -// final String webAppNamePrefix = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); -// final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); -// final List regions = new ArrayList<>(); -// // The regions in which web app needs to be created -// // -// regions.add(Region.US_WEST2); -// regions.add(Region.US_EAST2); -// regions.add(Region.ASIA_EAST); -// regions.add(Region.US_CENTRAL); -// -// try { -// azureResourceManager.resourceGroups().define(rgName) -// .withRegion(Region.US_WEST) -// .create(); -// -// //============================================================ -// // Purchase a domain (will be canceled for a full refund) -// -// System.out.println("Purchasing a domain " + domainName + "..."); -// AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) -// .withExistingResourceGroup(rgName) -// .defineRegistrantContact() -// .withFirstName("Jon") -// .withLastName("Doe") -// .withEmail("jondoe@contoso.com") -// .withAddressLine1("123 4th Ave") -// .withCity("Redmond") -// .withStateOrProvince("WA") -// .withCountry(CountryIsoCode.UNITED_STATES) -// .withPostalCode("98052") -// .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) -// .withPhoneNumber("4258828080") -// .attach() -// .withDomainPrivacyEnabled(true) -// .withAutoRenewEnabled(false) -// .create(); -// System.out.println("Purchased domain " + domain.name()); -// Utils.print(domain); -// -// //============================================================ -// // Create a self-singed SSL certificate -// -// String pfxPath = ManageTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; -// String cerPath = ManageTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; -// -// System.out.println("Creating a self-signed certificate " + pfxPath + "..."); -// -// Utils.createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName); -// -// //============================================================ -// // Creates app service in 5 different region -// -// List appServicePlans = new ArrayList<>(); -// int id = 0; -// for (Region region : regions) { -// String planName = appServicePlanNamePrefix + id; -// System.out.println("Creating an app service plan " + planName + " in region " + region + "..."); -// AppServicePlan appServicePlan = azureResourceManager.appServicePlans().define(planName) -// .withRegion(region) -// .withExistingResourceGroup(rgName) -// .withPricingTier(PricingTier.BASIC_B1) -// .withOperatingSystem(OperatingSystem.WINDOWS) -// .create(); -// System.out.println("Created app service plan " + planName); -// Utils.print(appServicePlan); -// appServicePlans.add(appServicePlan); -// id++; -// } -// -// //============================================================ -// // Creates websites using previously created plan -// List webApps = new ArrayList<>(); -// id = 0; -// for (AppServicePlan appServicePlan : appServicePlans) { -// String webAppName = webAppNamePrefix + id; -// System.out.println("Creating a web app " + webAppName + " using the plan " + appServicePlan.name() + "..."); -// WebApp webApp = azureResourceManager.webApps().define(webAppName) -// .withExistingWindowsPlan(appServicePlan) -// .withExistingResourceGroup(rgName) -// .withManagedHostnameBindings(domain, webAppName) -// .defineSslBinding() -// .forHostname(webAppName + "." + domain.name()) -// .withPfxCertificateToUpload(new File(pfxPath), certPassword) -// .withSniBasedSsl() -// .attach() -// .defineSourceControl() -// .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") -// .withBranch("master") -// .attach() -// .create(); -// System.out.println("Created web app " + webAppName); -// Utils.print(webApp); -// webApps.add(webApp); -// id++; -// } -// -// //============================================================ -// // Creates a traffic manager profile -// -// System.out.println("Creating a traffic manager profile " + tmName + " for the web apps..."); -// TrafficManagerProfile.DefinitionStages.WithEndpoint tmDefinition = azureResourceManager.trafficManagerProfiles() -// .define(tmName) -// .withExistingResourceGroup(rgName) -// .withLeafDomainLabel(tmName) -// .withPriorityBasedRouting(); -// Creatable tmCreatable = null; -// int priority = 1; -// for (WebApp webApp : webApps) { -// tmCreatable = tmDefinition.defineAzureTargetEndpoint("endpoint-" + priority) -// .toResourceId(webApp.id()) -// .withRoutingPriority(priority) -// .attach(); -// priority++; -// } -// TrafficManagerProfile trafficManagerProfile = tmCreatable.create(); -// System.out.println("Created traffic manager " + trafficManagerProfile.name()); -// Utils.print(trafficManagerProfile); -// -// //============================================================ -// // Disables one endpoint and removes another endpoint -// -// System.out.println("Disabling and removing endpoint..."); -// trafficManagerProfile = trafficManagerProfile.update() -// .updateAzureTargetEndpoint("endpoint-1") -// .withTrafficDisabled() -// .parent() -// .withoutEndpoint("endpoint-2") -// .apply(); -// System.out.println("Endpoints updated"); -// -// //============================================================ -// // Enables an endpoint -// -// System.out.println("Enabling endpoint..."); -// trafficManagerProfile = trafficManagerProfile.update() -// .updateAzureTargetEndpoint("endpoint-1") -// .withTrafficEnabled() -// .parent() -// .apply(); -// System.out.println("Endpoint updated"); -// Utils.print(trafficManagerProfile); -// -// //============================================================ -// // Change/configure traffic manager routing method -// -// System.out.println("Changing traffic manager profile routing method..."); -// trafficManagerProfile = trafficManagerProfile.update() -// .withPerformanceBasedRouting() -// .apply(); -// System.out.println("Changed traffic manager profile routing method"); -// -// //============================================================ -// // Disables the traffic manager profile -// -// System.out.println("Disabling traffic manager profile..."); -// trafficManagerProfile.update() -// .withProfileStatusDisabled() -// .apply(); -// System.out.println("Traffic manager profile disabled"); -// -// //============================================================ -// // Enables the traffic manager profile -// -// System.out.println("Enabling traffic manager profile..."); -// trafficManagerProfile.update() -// .withProfileStatusDisabled() -// .apply(); -// System.out.println("Traffic manager profile enabled"); -// -// //============================================================ -// // Deletes the traffic manager profile -// -// System.out.println("Deleting the traffic manger profile..."); -// azureResourceManager.trafficManagerProfiles().deleteById(trafficManagerProfile.id()); -// System.out.println("Traffic manager profile deleted"); -// return true; -// } finally { -// try { -// System.out.println("Deleting Resource Group: " + 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"); -// } catch (Exception g) { -// g.printStackTrace(); -// } -// } -// } -// /** -// * Main entry point. -// * @param args the parameters -// */ -// public static void main(String[] args) { -// try { -// //============================================================= -// // Authenticate -// // -// final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); -// final TokenCredential credential = new DefaultAzureCredentialBuilder() -// .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) -// .build(); -// -// AzureResourceManager azureResourceManager = AzureResourceManager -// .configure() -// .withLogLevel(HttpLogDetailLevel.BASIC) -// .authenticate(credential, profile) -// .withDefaultSubscription(); -// -// // Print selected subscription -// System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); -// -// runSample(azureResourceManager); -// } catch (Exception e) { -// System.out.println(e.getMessage()); -// e.printStackTrace(); -// } -// } -//} +package com.azure.resourcemanager.trafficmanager.samples; + +import com.azure.core.credential.TokenCredential; +import com.azure.core.http.policy.HttpLogDetailLevel; +import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.profile.AzureProfile; +import com.azure.identity.DefaultAzureCredentialBuilder; +import com.azure.resourcemanager.AzureResourceManager; +import com.azure.resourcemanager.appservice.models.AppServiceDomain; +import com.azure.resourcemanager.appservice.models.AppServicePlan; +import com.azure.resourcemanager.appservice.models.OperatingSystem; +import com.azure.resourcemanager.appservice.models.PricingTier; +import com.azure.resourcemanager.appservice.models.WebApp; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.resourcemanager.samples.Utils; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +/** + * Azure traffic manager sample for managing profiles. + * - Create a domain + * - Create a self-signed certificate for the domain + * - Create 5 app service plans in 5 different regions + * - Create 5 web apps under the each plan, bound to the domain and the certificate + * - Create a traffic manager in front of the web apps + * - Disable an endpoint + * - Delete an endpoint + * - Enable an endpoint + * - Change/configure traffic manager routing method + * - Disable traffic manager profile + * - Enable traffic manager profile + */ +public final class ManageTrafficManager { + + + /** + * Main function which runs the actual sample. + * @param azureResourceManager instance of the azure client + * @return true if sample runs successfully + */ + public static boolean runSample(AzureResourceManager azureResourceManager) throws IOException { + final String rgName = Utils.randomResourceName(azureResourceManager, "rgNEMV_", 24); + final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; + // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")] + final String certPassword = "StrongPass!12"; + final String appServicePlanNamePrefix = Utils.randomResourceName(azureResourceManager, "jplan1_", 15); + final String webAppNamePrefix = Utils.randomResourceName(azureResourceManager, "webapp1-", 20); + final String tmName = Utils.randomResourceName(azureResourceManager, "jsdktm-", 20); + final List regions = new ArrayList<>(); + // The regions in which web app needs to be created + // + regions.add(Region.US_WEST2); + regions.add(Region.US_EAST2); + regions.add(Region.ASIA_EAST); + regions.add(Region.US_CENTRAL); + + try { + azureResourceManager.resourceGroups().define(rgName) + .withRegion(Region.US_WEST) + .create(); + + //============================================================ + // Purchase a domain (will be canceled for a full refund) + + System.out.println("Purchasing a domain " + domainName + "..."); + AppServiceDomain domain = azureResourceManager.appServiceDomains().define(domainName) + .withExistingResourceGroup(rgName) + .defineRegistrantContact() + .withFirstName("Jon") + .withLastName("Doe") + .withEmail("jondoe@contoso.com") + .withAddressLine1("123 4th Ave") + .withCity("Redmond") + .withStateOrProvince("WA") + .withCountry(CountryIsoCode.UNITED_STATES) + .withPostalCode("98052") + .withPhoneCountryCode(CountryPhoneCode.UNITED_STATES) + .withPhoneNumber("4258828080") + .attach() + .withDomainPrivacyEnabled(true) + .withAutoRenewEnabled(false) + .create(); + System.out.println("Purchased domain " + domain.name()); + Utils.print(domain); + + //============================================================ + // Create a self-singed SSL certificate + + String pfxPath = ManageTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".pfx"; + String cerPath = ManageTrafficManager.class.getResource("/").getPath() + "webapp_" + domainName + ".cer"; + + System.out.println("Creating a self-signed certificate " + pfxPath + "..."); + + Utils.createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName); + + //============================================================ + // Creates app service in 5 different region + + List appServicePlans = new ArrayList<>(); + int id = 0; + for (Region region : regions) { + String planName = appServicePlanNamePrefix + id; + System.out.println("Creating an app service plan " + planName + " in region " + region + "..."); + AppServicePlan appServicePlan = azureResourceManager.appServicePlans().define(planName) + .withRegion(region) + .withExistingResourceGroup(rgName) + .withPricingTier(PricingTier.BASIC_B1) + .withOperatingSystem(OperatingSystem.WINDOWS) + .create(); + System.out.println("Created app service plan " + planName); + Utils.print(appServicePlan); + appServicePlans.add(appServicePlan); + id++; + } + + //============================================================ + // Creates websites using previously created plan + List webApps = new ArrayList<>(); + id = 0; + for (AppServicePlan appServicePlan : appServicePlans) { + String webAppName = webAppNamePrefix + id; + System.out.println("Creating a web app " + webAppName + " using the plan " + appServicePlan.name() + "..."); + WebApp webApp = azureResourceManager.webApps().define(webAppName) + .withExistingWindowsPlan(appServicePlan) + .withExistingResourceGroup(rgName) + .withManagedHostnameBindings(domain, webAppName) + .defineSslBinding() + .forHostname(webAppName + "." + domain.name()) + .withPfxCertificateToUpload(new File(pfxPath), certPassword) + .withSniBasedSsl() + .attach() + .defineSourceControl() + .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test") + .withBranch("master") + .attach() + .create(); + System.out.println("Created web app " + webAppName); + Utils.print(webApp); + webApps.add(webApp); + id++; + } + + //============================================================ + // Creates a traffic manager profile + + System.out.println("Creating a traffic manager profile " + tmName + " for the web apps..."); + TrafficManagerProfile.DefinitionStages.WithEndpoint tmDefinition = azureResourceManager.trafficManagerProfiles() + .define(tmName) + .withExistingResourceGroup(rgName) + .withLeafDomainLabel(tmName) + .withPriorityBasedRouting(); + Creatable tmCreatable = null; + int priority = 1; + for (WebApp webApp : webApps) { + tmCreatable = tmDefinition.defineAzureTargetEndpoint("endpoint-" + priority) + .toResourceId(webApp.id()) + .withRoutingPriority(priority) + .attach(); + priority++; + } + TrafficManagerProfile trafficManagerProfile = tmCreatable.create(); + System.out.println("Created traffic manager " + trafficManagerProfile.name()); + Utils.print(trafficManagerProfile); + + //============================================================ + // Disables one endpoint and removes another endpoint + + System.out.println("Disabling and removing endpoint..."); + trafficManagerProfile = trafficManagerProfile.update() + .updateAzureTargetEndpoint("endpoint-1") + .withTrafficDisabled() + .parent() + .withoutEndpoint("endpoint-2") + .apply(); + System.out.println("Endpoints updated"); + + //============================================================ + // Enables an endpoint + + System.out.println("Enabling endpoint..."); + trafficManagerProfile = trafficManagerProfile.update() + .updateAzureTargetEndpoint("endpoint-1") + .withTrafficEnabled() + .parent() + .apply(); + System.out.println("Endpoint updated"); + Utils.print(trafficManagerProfile); + + //============================================================ + // Change/configure traffic manager routing method + + System.out.println("Changing traffic manager profile routing method..."); + trafficManagerProfile = trafficManagerProfile.update() + .withPerformanceBasedRouting() + .apply(); + System.out.println("Changed traffic manager profile routing method"); + + //============================================================ + // Disables the traffic manager profile + + System.out.println("Disabling traffic manager profile..."); + trafficManagerProfile.update() + .withProfileStatusDisabled() + .apply(); + System.out.println("Traffic manager profile disabled"); + + //============================================================ + // Enables the traffic manager profile + + System.out.println("Enabling traffic manager profile..."); + trafficManagerProfile.update() + .withProfileStatusDisabled() + .apply(); + System.out.println("Traffic manager profile enabled"); + + //============================================================ + // Deletes the traffic manager profile + + System.out.println("Deleting the traffic manger profile..."); + azureResourceManager.trafficManagerProfiles().deleteById(trafficManagerProfile.id()); + System.out.println("Traffic manager profile deleted"); + return true; + } finally { + try { + System.out.println("Deleting Resource Group: " + 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"); + } catch (Exception g) { + g.printStackTrace(); + } + } + } + /** + * Main entry point. + * @param args the parameters + */ + public static void main(String[] args) { + try { + //============================================================= + // Authenticate + // + final AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE); + final TokenCredential credential = new DefaultAzureCredentialBuilder() + .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint()) + .build(); + + AzureResourceManager azureResourceManager = AzureResourceManager + .configure() + .withLogLevel(HttpLogDetailLevel.BASIC) + .authenticate(credential, profile) + .withDefaultSubscription(); + + // Print selected subscription + System.out.println("Selected subscription: " + azureResourceManager.subscriptionId()); + + runSample(azureResourceManager); + } catch (Exception e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java index a9610b11b2bc..6ffb40772f97 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java @@ -3,15 +3,25 @@ package com.azure.resourcemanager.samples; +import com.azure.core.test.annotation.DoNotRecord; +import com.azure.resourcemanager.appplatform.samples.ManageSpringCloud; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; + public class AppPlatformLiveOnlyTests extends SamplesTestBase { -// @Test -// @DoNotRecord -// public void testSpringCloud() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageSpringCloud.runSample(azureResourceManager, clientIdFromFile())); -// } + @Test + @DoNotRecord + public void testSpringCloud() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageSpringCloud.runSample(azureResourceManager, clientIdFromFile())); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java index e652a35bbb32..3932cac0f16e 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleLiveOnlyTests.java @@ -15,15 +15,19 @@ import com.azure.resourcemanager.appservice.samples.ManageFunctionAppWithAuthentication; import com.azure.resourcemanager.appservice.samples.ManageFunctionAppWithDomainSsl; import com.azure.resourcemanager.appservice.samples.ManageLinuxFunctionAppSourceControl; +import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppCosmosDbByMsi; import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppSourceControl; import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppStorageAccountConnection; +import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppWithContainerRegistry; import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppWithDomainSsl; +import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppWithTrafficManager; import com.azure.resourcemanager.appservice.samples.ManageWebAppCosmosDbByMsi; import com.azure.resourcemanager.appservice.samples.ManageWebAppCosmosDbThroughKeyVault; import com.azure.resourcemanager.appservice.samples.ManageWebAppLogs; import com.azure.resourcemanager.appservice.samples.ManageWebAppSourceControl; import com.azure.resourcemanager.appservice.samples.ManageWebAppStorageAccountConnection; import com.azure.resourcemanager.appservice.samples.ManageWebAppWithDomainSsl; +import com.azure.resourcemanager.appservice.samples.ManageWebAppWithTrafficManager; import org.eclipse.jgit.api.errors.GitAPIException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -72,15 +76,15 @@ public void testManageLinuxWebAppStorageAccountConnection() { Assertions.assertTrue(ManageLinuxWebAppStorageAccountConnection.runSample(azureResourceManager)); } -// @Test -// @DoNotRecord -// public void testManageLinuxWebAppWithContainerRegistry() throws IOException, InterruptedException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageLinuxWebAppWithContainerRegistry.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testManageLinuxWebAppWithContainerRegistry() throws IOException, InterruptedException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageLinuxWebAppWithContainerRegistry.runSample(azureResourceManager)); + } @Test @DoNotRecord @@ -102,15 +106,15 @@ public void testManageFunctionAppSourceControl() throws GitAPIException { Assertions.assertTrue(ManageFunctionAppSourceControl.runSample(azureResourceManager)); } -// @Test -// @DoNotRecord -// public void testManageLinuxWebAppCosmosDbByMsi() throws IOException, InterruptedException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageLinuxWebAppCosmosDbByMsi.runSample(azureResourceManager, "")); -// } + @Test + @DoNotRecord + public void testManageLinuxWebAppCosmosDbByMsi() throws IOException, InterruptedException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageLinuxWebAppCosmosDbByMsi.runSample(azureResourceManager, "")); + } @Test @DoNotRecord @@ -195,15 +199,15 @@ public void testManageWebAppWithDomainSsl() throws IOException { Assertions.assertTrue(ManageWebAppWithDomainSsl.runSample(azureResourceManager)); } -// @Test -// @DoNotRecord -// public void testManageWebAppWithTrafficManager() throws IOException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageWebAppWithTrafficManager.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testManageWebAppWithTrafficManager() throws IOException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageWebAppWithTrafficManager.runSample(azureResourceManager)); + } @Test @DoNotRecord @@ -215,15 +219,15 @@ public void testManageLinuxWebAppWithDomainSsl() throws IOException { Assertions.assertTrue(ManageLinuxWebAppWithDomainSsl.runSample(azureResourceManager)); } -// @Test -// @DoNotRecord -// public void testManageLinuxWebAppWithTrafficManager() throws IOException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageLinuxWebAppWithTrafficManager.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testManageLinuxWebAppWithTrafficManager() throws IOException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageLinuxWebAppWithTrafficManager.runSample(azureResourceManager)); + } @Test @DoNotRecord diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleTests.java index 54f4d23b54e9..8af2255cf8ff 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppServiceSampleTests.java @@ -5,13 +5,18 @@ import com.azure.resourcemanager.appservice.samples.ManageFunctionAppBasic; import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppBasic; +import com.azure.resourcemanager.appservice.samples.ManageLinuxWebAppSqlConnection; import com.azure.resourcemanager.appservice.samples.ManageWebAppBasic; import com.azure.resourcemanager.appservice.samples.ManageWebAppSlots; import com.azure.resourcemanager.appservice.samples.ManageWebAppSourceControlAsync; +import com.azure.resourcemanager.appservice.samples.ManageWebAppSqlConnection; + import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import java.io.IOException; + public class AppServiceSampleTests extends SamplesTestBase { @Test public void testManageWebAppBasic() { @@ -30,22 +35,22 @@ public void testManageWebAppSourceControlAsync() { Assertions.assertTrue(ManageWebAppSourceControlAsync.runSample(azureResourceManager)); } -// @Test -// @Disabled("Stops in between for user input") -// public void testManageWebAppSqlConnection() throws IOException { -// Assertions.assertTrue(ManageWebAppSqlConnection.runSample(azureResourceManager)); -// } + @Test + @Disabled("Stops in between for user input") + public void testManageWebAppSqlConnection() throws IOException { + Assertions.assertTrue(ManageWebAppSqlConnection.runSample(azureResourceManager)); + } @Test public void testManageLinuxWebAppBasic() { Assertions.assertTrue(ManageLinuxWebAppBasic.runSample(azureResourceManager)); } -// @Test -// @Disabled("Stops in between for user input") -// public void testManageLinuxWebAppSqlConnection() throws IOException { -// Assertions.assertTrue(ManageLinuxWebAppSqlConnection.runSample(azureResourceManager)); -// } + @Test + @Disabled("Stops in between for user input") + public void testManageLinuxWebAppSqlConnection() throws IOException { + Assertions.assertTrue(ManageLinuxWebAppSqlConnection.runSample(azureResourceManager)); + } @Test public void testManageFunctionAppBasic() { diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleLiveOnlyTests.java index 48f054d30618..5de7dfdc627a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleLiveOnlyTests.java @@ -3,15 +3,20 @@ package com.azure.resourcemanager.samples; +import com.azure.core.test.annotation.DoNotRecord; +import com.azure.resourcemanager.cdn.samples.ManageCdn; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class CdnSampleLiveOnlyTests extends SamplesTestBase { -// @Test -// @DoNotRecord -// public void testManageCdnProfileWithWebApp() { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageCdn.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testManageCdnProfileWithWebApp() { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageCdn.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleTests.java index 7403afdfbf79..56c74adc50ed 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/CdnSampleTests.java @@ -3,10 +3,14 @@ package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.cdn.samples.ManageCdnWithCustomDomain; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class CdnSampleTests extends SamplesTestBase { -// @Test -// public void testManageCdnProfileWithCustomDomain() { -// Assertions.assertTrue(ManageCdnWithCustomDomain.runSample(azureResourceManager)); -// } + @Test + public void testManageCdnProfileWithCustomDomain() { + Assertions.assertTrue(ManageCdnWithCustomDomain.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java index 73eea39cdde8..dc68ba20b202 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerInstanceTests.java @@ -3,38 +3,48 @@ package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.containerinstance.samples.ManageContainerInstanceWithAzureFileShareMount; +import com.azure.resourcemanager.containerinstance.samples.ManageContainerInstanceWithManualAzureFileShareMountCreation; +import com.azure.resourcemanager.containerinstance.samples.ManageContainerInstanceWithMultipleContainerImages; +import com.azure.resourcemanager.containerinstance.samples.ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator; +import com.jcraft.jsch.JSchException; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + public class ContainerInstanceTests extends SamplesTestBase { -// @Test -// public void testManageContainerInstanceWithAzureFileShareMount() { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageContainerInstanceWithAzureFileShareMount.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageContainerInstanceWithManualAzureFileShareMountCreation() { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageContainerInstanceWithManualAzureFileShareMountCreation.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageContainerInstanceWithMultipleContainerImages() { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageContainerInstanceWithMultipleContainerImages.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator() throws InterruptedException, JSchException, IOException { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.runSample(azureResourceManager, "", "")); -// } -// } + @Test + public void testManageContainerInstanceWithAzureFileShareMount() { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageContainerInstanceWithAzureFileShareMount.runSample(azureResourceManager)); + } + } + + @Test + public void testManageContainerInstanceWithManualAzureFileShareMountCreation() { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageContainerInstanceWithManualAzureFileShareMountCreation.runSample(azureResourceManager)); + } + } + + @Test + public void testManageContainerInstanceWithMultipleContainerImages() { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageContainerInstanceWithMultipleContainerImages.runSample(azureResourceManager)); + } + } + + @Test + public void testManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator() throws InterruptedException, JSchException, IOException { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageContainerInstanceZeroToOneAndOneToManyUsingContainerServiceOrchestrator.runSample(azureResourceManager, "", "")); + } + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerRegistryTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerRegistryTests.java index dd18eeef4ee3..41e704a21646 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerRegistryTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ContainerRegistryTests.java @@ -3,25 +3,33 @@ package com.azure.resourcemanager.samples; +import com.azure.core.test.annotation.DoNotRecord; +import com.azure.resourcemanager.containerregistry.samples.ManageContainerRegistry; +import com.azure.resourcemanager.containerregistry.samples.ManageContainerRegistryWithWebhooks; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + public class ContainerRegistryTests extends SamplesTestBase { -// @Test -// @DoNotRecord -// public void testManageContainerRegistry() throws IOException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageContainerRegistry.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testManageContainerRegistryWithWebhooks() throws IOException, InterruptedException { -// if (skipInPlayback()) { -// return; -// } -// -// Assertions.assertTrue(ManageContainerRegistryWithWebhooks.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testManageContainerRegistry() throws IOException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageContainerRegistry.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testManageContainerRegistryWithWebhooks() throws IOException, InterruptedException { + if (skipInPlayback()) { + return; + } + + Assertions.assertTrue(ManageContainerRegistryWithWebhooks.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/EventHubsSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/EventHubsSampleTests.java index 3501e5614f3e..16a0ae07982f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/EventHubsSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/EventHubsSampleTests.java @@ -2,19 +2,25 @@ // Licensed under the MIT License. package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.eventhubs.samples.ManageEventHub; +import com.azure.resourcemanager.eventhubs.samples.ManageEventHubEvents; +import com.azure.resourcemanager.eventhubs.samples.ManageEventHubGeoDisasterRecovery; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class EventHubsSampleTests extends SamplesTestBase { -// @Test -// public void testManageEventHub() { -// Assertions.assertTrue(ManageEventHub.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageEventHubEvents() { -// Assertions.assertTrue(ManageEventHubEvents.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageEventHubGeoDisasterRecovery() { -// Assertions.assertTrue(ManageEventHubGeoDisasterRecovery.runSample(azureResourceManager)); -// } + @Test + public void testManageEventHub() { + Assertions.assertTrue(ManageEventHub.runSample(azureResourceManager)); + } + + @Test + public void testManageEventHubEvents() { + Assertions.assertTrue(ManageEventHubEvents.runSample(azureResourceManager)); + } + + @Test + public void testManageEventHubGeoDisasterRecovery() { + Assertions.assertTrue(ManageEventHubGeoDisasterRecovery.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java index 588634cfe5b0..940cc55005e7 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/KubernetesClusterTests.java @@ -3,6 +3,7 @@ package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.kubernetescluster.samples.DeployImageFromContainerRegistryToKubernetes; import com.azure.resourcemanager.kubernetescluster.samples.ManageKubernetesCluster; import com.azure.resourcemanager.kubernetescluster.samples.ManagedKubernetesClusterWithAdvancedNetworking; import com.jcraft.jsch.JSchException; @@ -37,10 +38,10 @@ public void testManageKubernetesClusterWithAdvancedNetworking() throws IOExcepti } } -// @Test -// public void testDeployImageFromContainerRegistryToKubernetes() throws InterruptedException, JSchException, IOException { -// if (!isPlaybackMode()) { -// Assertions.assertTrue(DeployImageFromContainerRegistryToKubernetes.runSample(azureResourceManager, "", "")); -// } -// } + @Test + public void testDeployImageFromContainerRegistryToKubernetes() throws InterruptedException, JSchException, IOException { + if (!isPlaybackMode()) { + Assertions.assertTrue(DeployImageFromContainerRegistryToKubernetes.runSample(azureResourceManager, "", "")); + } + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/PrivateDnsSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/PrivateDnsSampleTests.java index a712e86cfab0..56ac9790a264 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/PrivateDnsSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/PrivateDnsSampleTests.java @@ -2,9 +2,13 @@ // Licensed under the MIT License. package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.privatedns.samples.ManagePrivateDns; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class PrivateDnsSampleTests extends SamplesTestBase { -// @Test -// public void testManagePrivateDns() { -// Assertions.assertTrue(ManagePrivateDns.runSample(azureResourceManager)); -// } + @Test + public void testManagePrivateDns() { + Assertions.assertTrue(ManagePrivateDns.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/RedisCacheSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/RedisCacheSampleTests.java index 946715763146..8bbe21fd0805 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/RedisCacheSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/RedisCacheSampleTests.java @@ -3,9 +3,13 @@ package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.rediscache.samples.ManageRedisCache; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class RedisCacheSampleTests extends SamplesTestBase { -// @Test -// public void testManageRedisCache() { -// Assertions.assertTrue(ManageRedisCache.runSample(azureResourceManager)); -// } + @Test + public void testManageRedisCache() { + Assertions.assertTrue(ManageRedisCache.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ServiceBusSampleLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ServiceBusSampleLiveOnlyTests.java index cf6c671c147d..acd2b60611e6 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ServiceBusSampleLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/ServiceBusSampleLiveOnlyTests.java @@ -3,49 +3,58 @@ package com.azure.resourcemanager.samples; +import com.azure.core.test.annotation.DoNotRecord; +import com.azure.resourcemanager.servicebus.samples.ServiceBusPublishSubscribeAdvanceFeatures; +import com.azure.resourcemanager.servicebus.samples.ServiceBusPublishSubscribeBasic; +import com.azure.resourcemanager.servicebus.samples.ServiceBusQueueAdvanceFeatures; +import com.azure.resourcemanager.servicebus.samples.ServiceBusQueueBasic; +import com.azure.resourcemanager.servicebus.samples.ServiceBusWithClaimBasedAuthorization; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + public class ServiceBusSampleLiveOnlyTests extends SamplesTestBase { -// @Test -// @DoNotRecord -// public void testServiceBusQueueBasic() { -// if (skipInPlayback()) { -// return; -// } -// Assertions.assertTrue(ServiceBusQueueBasic.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testServiceBusPublishSubscribeBasic() { -// if (skipInPlayback()) { -// return; -// } -// Assertions.assertTrue(ServiceBusPublishSubscribeBasic.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testServiceBusWithClaimBasedAuthorization() { -// if (skipInPlayback()) { -// return; -// } -// Assertions.assertTrue(ServiceBusWithClaimBasedAuthorization.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testServiceBusQueueAdvanceFeatures() { -// if (skipInPlayback()) { -// return; -// } -// Assertions.assertTrue(ServiceBusQueueAdvanceFeatures.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testServiceBusPublishSubscribeAdvanceFeatures() { -// if (skipInPlayback()) { -// return; -// } -// Assertions.assertTrue(ServiceBusPublishSubscribeAdvanceFeatures.runSample(azureResourceManager)); -// } + @Test + @DoNotRecord + public void testServiceBusQueueBasic() { + if (skipInPlayback()) { + return; + } + Assertions.assertTrue(ServiceBusQueueBasic.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testServiceBusPublishSubscribeBasic() { + if (skipInPlayback()) { + return; + } + Assertions.assertTrue(ServiceBusPublishSubscribeBasic.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testServiceBusWithClaimBasedAuthorization() { + if (skipInPlayback()) { + return; + } + Assertions.assertTrue(ServiceBusWithClaimBasedAuthorization.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testServiceBusQueueAdvanceFeatures() { + if (skipInPlayback()) { + return; + } + Assertions.assertTrue(ServiceBusQueueAdvanceFeatures.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testServiceBusPublishSubscribeAdvanceFeatures() { + if (skipInPlayback()) { + return; + } + Assertions.assertTrue(ServiceBusPublishSubscribeAdvanceFeatures.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java index fe924e8dfc14..7e740d4a0609 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/SqlSampleTests.java @@ -3,98 +3,117 @@ package com.azure.resourcemanager.samples; +import com.azure.resourcemanager.sql.samples.GettingSqlServerMetrics; +import com.azure.resourcemanager.sql.samples.ManageSqlDatabase; +import com.azure.resourcemanager.sql.samples.ManageSqlDatabaseInElasticPool; +import com.azure.resourcemanager.sql.samples.ManageSqlDatabasesAcrossDifferentDataCenters; +import com.azure.resourcemanager.sql.samples.ManageSqlFailoverGroups; +import com.azure.resourcemanager.sql.samples.ManageSqlFirewallRules; +import com.azure.resourcemanager.sql.samples.ManageSqlImportExportDatabase; +import com.azure.resourcemanager.sql.samples.ManageSqlServerDnsAliases; +import com.azure.resourcemanager.sql.samples.ManageSqlServerKeysWithAzureKeyVaultKey; +import com.azure.resourcemanager.sql.samples.ManageSqlServerSecurityAlertPolicy; +import com.azure.resourcemanager.sql.samples.ManageSqlVirtualNetworkRules; +import com.azure.resourcemanager.sql.samples.ManageSqlWithRecoveredOrRestoredDatabase; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.nio.file.Files; +import java.nio.file.Paths; +import java.sql.SQLException; + public class SqlSampleTests extends SamplesTestBase { -// @Test -// public void testManageSqlDatabase() { -// Assertions.assertTrue(ManageSqlDatabase.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlDatabaseInElasticPool() { -// Assertions.assertTrue(ManageSqlDatabaseInElasticPool.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlDatabasesAcrossDifferentDataCenters() { -// Assertions.assertTrue(ManageSqlDatabasesAcrossDifferentDataCenters.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlFirewallRules() { -// Assertions.assertTrue(ManageSqlFirewallRules.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlServerSecurityAlertPolicy() { -// Assertions.assertTrue(ManageSqlServerSecurityAlertPolicy.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlVirtualNetworkRules() { -// Assertions.assertTrue(ManageSqlVirtualNetworkRules.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlImportExportDatabase() { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageSqlImportExportDatabase.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageSqlWithRecoveredOrRestoredDatabase() { -// // This test can take significant time to run since it depends on the availability of certain resources on the service side. -// Assertions.assertTrue(ManageSqlWithRecoveredOrRestoredDatabase.runSample(azureResourceManager)); -// } -// -// @Test -// public void testManageSqlFailoverGroups() { -// Assertions.assertTrue(ManageSqlFailoverGroups.runSample(azureResourceManager)); -// } -// -// @Test -// public void testGettingSqlServerMetrics() throws SQLException, ClassNotFoundException { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(GettingSqlServerMetrics.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageSqlServerDnsAliases() throws SQLException, ClassNotFoundException { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// Assertions.assertTrue(ManageSqlServerDnsAliases.runSample(azureResourceManager)); -// } -// } -// -// @Test -// public void testManageSqlServerKeysWithAzureKeyVaultKey() { -// // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time -// if (!isPlaybackMode()) { -// //============================================================= -// // If service principal client id is not set via the local variables, attempt to read the service -// // principal client id from a secondary ".azureauth" file set through an environment variable. -// // -// // If the environment variable was not set then reuse the main service principal set for running this sample. -// -// String servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); -// if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { -// String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); -// -// if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { -// envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); -// } -// try { -// servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); -// } catch (Exception e) { -// Assertions.assertFalse(true, "Unexpected exception trying to retrieve the client ID"); -// } -// } -// -// Assertions.assertTrue(ManageSqlServerKeysWithAzureKeyVaultKey.runSample(azureResourceManager, servicePrincipalClientId)); -// } -// } + @Test + public void testManageSqlDatabase() { + Assertions.assertTrue(ManageSqlDatabase.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlDatabaseInElasticPool() { + Assertions.assertTrue(ManageSqlDatabaseInElasticPool.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlDatabasesAcrossDifferentDataCenters() { + Assertions.assertTrue(ManageSqlDatabasesAcrossDifferentDataCenters.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlFirewallRules() { + Assertions.assertTrue(ManageSqlFirewallRules.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlServerSecurityAlertPolicy() { + Assertions.assertTrue(ManageSqlServerSecurityAlertPolicy.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlVirtualNetworkRules() { + Assertions.assertTrue(ManageSqlVirtualNetworkRules.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlImportExportDatabase() { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageSqlImportExportDatabase.runSample(azureResourceManager)); + } + } + + @Test + public void testManageSqlWithRecoveredOrRestoredDatabase() { + // This test can take significant time to run since it depends on the availability of certain resources on the service side. + Assertions.assertTrue(ManageSqlWithRecoveredOrRestoredDatabase.runSample(azureResourceManager)); + } + + @Test + public void testManageSqlFailoverGroups() { + Assertions.assertTrue(ManageSqlFailoverGroups.runSample(azureResourceManager)); + } + + @Test + public void testGettingSqlServerMetrics() throws SQLException, ClassNotFoundException { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(GettingSqlServerMetrics.runSample(azureResourceManager)); + } + } + + @Test + public void testManageSqlServerDnsAliases() throws SQLException, ClassNotFoundException { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + Assertions.assertTrue(ManageSqlServerDnsAliases.runSample(azureResourceManager)); + } + } + + @Test + public void testManageSqlServerKeysWithAzureKeyVaultKey() { + // Skip test in "playback" mode due to HTTP calls made outside of the management plane which can not be recorded at this time + if (!isPlaybackMode()) { + //============================================================= + // If service principal client id is not set via the local variables, attempt to read the service + // principal client id from a secondary ".azureauth" file set through an environment variable. + // + // If the environment variable was not set then reuse the main service principal set for running this sample. + + String servicePrincipalClientId = System.getenv("AZURE_CLIENT_ID"); + if (servicePrincipalClientId == null || servicePrincipalClientId.isEmpty()) { + String envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION_2"); + + if (envSecondaryServicePrincipal == null || !envSecondaryServicePrincipal.isEmpty() || !Files.exists(Paths.get(envSecondaryServicePrincipal))) { + envSecondaryServicePrincipal = System.getenv("AZURE_AUTH_LOCATION"); + } + try { + servicePrincipalClientId = Utils.getSecondaryServicePrincipalClientID(envSecondaryServicePrincipal); + } catch (Exception e) { + Assertions.assertFalse(true, "Unexpected exception trying to retrieve the client ID"); + } + } + + Assertions.assertTrue(ManageSqlServerKeysWithAzureKeyVaultKey.runSample(azureResourceManager, servicePrincipalClientId)); + } + } } diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/TrafficManagerSampleTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/TrafficManagerSampleTests.java index 4cee8c0642b2..ef52aa6ab02f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/TrafficManagerSampleTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/TrafficManagerSampleTests.java @@ -3,19 +3,27 @@ package com.azure.resourcemanager.samples; +import com.azure.core.test.annotation.DoNotRecord; +import com.azure.resourcemanager.trafficmanager.samples.ManageSimpleTrafficManager; +import com.azure.resourcemanager.trafficmanager.samples.ManageTrafficManager; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import java.io.IOException; + public class TrafficManagerSampleTests extends SamplesTestBase { -// @Test -// public void testManageSimpleTrafficManager() { -// Assertions.assertTrue(ManageSimpleTrafficManager.runSample(azureResourceManager)); -// } -// -// @Test -// @DoNotRecord -// public void testManageTrafficManager() throws IOException { -// if (this.skipInPlayback()) { -// // sample creates certificate -// return; -// } -// Assertions.assertTrue(ManageTrafficManager.runSample(azureResourceManager)); -// } + @Test + public void testManageSimpleTrafficManager() { + Assertions.assertTrue(ManageSimpleTrafficManager.runSample(azureResourceManager)); + } + + @Test + @DoNotRecord + public void testManageTrafficManager() throws IOException { + if (this.skipInPlayback()) { + // sample creates certificate + return; + } + Assertions.assertTrue(ManageTrafficManager.runSample(azureResourceManager)); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager/README.md b/sdk/resourcemanager/azure-resourcemanager/README.md index 3ad41daeaa46..0c76eb4461c6 100644 --- a/sdk/resourcemanager/azure-resourcemanager/README.md +++ b/sdk/resourcemanager/azure-resourcemanager/README.md @@ -18,7 +18,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager - 2.0.0 + 2.0.0-beta.5 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index a002f4edfb21..7a6fd5e1b7fb 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -80,6 +80,11 @@ azure-resourcemanager-msi 2.1.0-beta.1 + + com.azure.resourcemanager + azure-resourcemanager-sql + 2.0.0-beta.5 + com.azure.resourcemanager azure-resourcemanager-authorization @@ -105,11 +110,56 @@ azure-resourcemanager-monitor 2.1.0-beta.1 + + com.azure.resourcemanager + azure-resourcemanager-containerregistry + 2.0.0-beta.5 + com.azure.resourcemanager azure-resourcemanager-dns 2.1.0-beta.1 + + com.azure.resourcemanager + azure-resourcemanager-appplatform + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-containerinstance + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-privatedns + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-redis + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-eventhubs + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-trafficmanager + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-servicebus + 2.0.0-beta.5 + + + com.azure.resourcemanager + azure-resourcemanager-cdn + 2.0.0-beta.5 + org.junit.jupiter junit-jupiter-engine diff --git a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java index ec5e29f5419e..d005c7a15894 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/main/java/com/azure/resourcemanager/AzureResourceManager.java @@ -6,7 +6,8 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.management.AzureEnvironment; -import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.appplatform.AppPlatformManager; +import com.azure.resourcemanager.appplatform.models.SpringServices; import com.azure.resourcemanager.appservice.AppServiceManager; import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrders; import com.azure.resourcemanager.appservice.models.AppServiceCertificates; @@ -21,6 +22,8 @@ import com.azure.resourcemanager.authorization.models.RoleAssignments; import com.azure.resourcemanager.authorization.models.RoleDefinitions; import com.azure.resourcemanager.authorization.models.ServicePrincipals; +import com.azure.resourcemanager.cdn.CdnManager; +import com.azure.resourcemanager.cdn.models.CdnProfiles; import com.azure.resourcemanager.compute.ComputeManager; import com.azure.resourcemanager.compute.models.AvailabilitySets; import com.azure.resourcemanager.compute.models.ComputeSkus; @@ -34,12 +37,22 @@ import com.azure.resourcemanager.compute.models.VirtualMachineImages; import com.azure.resourcemanager.compute.models.VirtualMachineScaleSets; import com.azure.resourcemanager.compute.models.VirtualMachines; +import com.azure.resourcemanager.containerinstance.ContainerInstanceManager; +import com.azure.resourcemanager.containerinstance.models.ContainerGroups; +import com.azure.resourcemanager.containerregistry.ContainerRegistryManager; +import com.azure.resourcemanager.containerregistry.models.Registries; +import com.azure.resourcemanager.containerregistry.models.RegistryTaskRuns; +import com.azure.resourcemanager.containerregistry.models.RegistryTasks; import com.azure.resourcemanager.containerservice.ContainerServiceManager; import com.azure.resourcemanager.containerservice.models.KubernetesClusters; import com.azure.resourcemanager.cosmos.CosmosManager; import com.azure.resourcemanager.cosmos.models.CosmosDBAccounts; import com.azure.resourcemanager.dns.DnsZoneManager; import com.azure.resourcemanager.dns.models.DnsZones; +import com.azure.resourcemanager.eventhubs.EventHubsManager; +import com.azure.resourcemanager.eventhubs.models.EventHubDisasterRecoveryPairings; +import com.azure.resourcemanager.eventhubs.models.EventHubNamespaces; +import com.azure.resourcemanager.eventhubs.models.EventHubs; import com.azure.resourcemanager.keyvault.KeyVaultManager; import com.azure.resourcemanager.keyvault.models.Vaults; import com.azure.resourcemanager.monitor.MonitorManager; @@ -69,9 +82,14 @@ import com.azure.resourcemanager.network.models.RouteFilters; import com.azure.resourcemanager.network.models.RouteTables; import com.azure.resourcemanager.network.models.VirtualNetworkGateways; +import com.azure.resourcemanager.privatedns.PrivateDnsZoneManager; +import com.azure.resourcemanager.privatedns.models.PrivateDnsZones; +import com.azure.resourcemanager.redis.RedisManager; +import com.azure.resourcemanager.redis.models.RedisCaches; import com.azure.resourcemanager.resources.ResourceManager; import com.azure.resourcemanager.resources.fluentcore.arm.AzureConfigurable; import com.azure.resourcemanager.resources.fluentcore.arm.implementation.AzureConfigurableImpl; +import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.resources.fluentcore.utils.HttpPipelineProvider; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.resources.models.Deployments; @@ -84,6 +102,10 @@ import com.azure.resourcemanager.resources.models.Subscription; import com.azure.resourcemanager.resources.models.Subscriptions; import com.azure.resourcemanager.resources.models.Tenants; +import com.azure.resourcemanager.servicebus.ServiceBusManager; +import com.azure.resourcemanager.servicebus.models.ServiceBusNamespaces; +import com.azure.resourcemanager.sql.SqlServerManager; +import com.azure.resourcemanager.sql.models.SqlServers; import com.azure.resourcemanager.storage.StorageManager; import com.azure.resourcemanager.storage.models.BlobContainers; import com.azure.resourcemanager.storage.models.BlobServices; @@ -91,6 +113,8 @@ import com.azure.resourcemanager.storage.models.StorageAccounts; import com.azure.resourcemanager.storage.models.StorageSkus; import com.azure.resourcemanager.storage.models.Usages; +import com.azure.resourcemanager.trafficmanager.TrafficManager; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfiles; import java.util.Objects; @@ -102,24 +126,24 @@ public final class AzureResourceManager { private final NetworkManager networkManager; private final KeyVaultManager keyVaultManager; // private final BatchManager batchManager; -// private final TrafficManager trafficManager; -// private final RedisManager redisManager; -// private final CdnManager cdnManager; + private final TrafficManager trafficManager; + private final RedisManager redisManager; + private final CdnManager cdnManager; private final DnsZoneManager dnsZoneManager; private final AppServiceManager appServiceManager; -// private final SqlServerManager sqlServerManager; -// private final ServiceBusManager serviceBusManager; -// private final ContainerInstanceManager containerInstanceManager; -// private final ContainerRegistryManager containerRegistryManager; + private final SqlServerManager sqlServerManager; + private final ServiceBusManager serviceBusManager; + private final ContainerInstanceManager containerInstanceManager; + private final ContainerRegistryManager containerRegistryManager; private final ContainerServiceManager containerServiceManager; // private final SearchServiceManager searchServiceManager; private final CosmosManager cosmosManager; // private final AuthorizationManager authorizationManager; private final MsiManager msiManager; private final MonitorManager monitorManager; -// private final EventHubsManager eventHubsManager; -// private final AppPlatformManager appPlatformManager; -// private final PrivateDnsZoneManager privateDnsZoneManager; + private final EventHubsManager eventHubsManager; + private final AppPlatformManager appPlatformManager; + private final PrivateDnsZoneManager privateDnsZoneManager; private final Authenticated authenticated; private final String subscriptionId; private final String tenantId; @@ -336,24 +360,24 @@ private AzureResourceManager(HttpPipeline httpPipeline, AzureProfile profile, Au this.keyVaultManager = withHttpPipeline(httpPipeline, KeyVaultManager.configure()) .authenticate(null, profile); // this.batchManager = BatchManager.authenticate(restClient, subscriptionId, internalContext); -// this.trafficManager = withHttpPipeline(httpPipeline, TrafficManager.configure()) -// .authenticate(null, profile); -// this.redisManager = withHttpPipeline(httpPipeline, RedisManager.configure()) -// .authenticate(null, profile); -// this.cdnManager = withHttpPipeline(httpPipeline, CdnManager.configure()) -// .authenticate(null, profile); + this.trafficManager = withHttpPipeline(httpPipeline, TrafficManager.configure()) + .authenticate(null, profile); + this.redisManager = withHttpPipeline(httpPipeline, RedisManager.configure()) + .authenticate(null, profile); + this.cdnManager = withHttpPipeline(httpPipeline, CdnManager.configure()) + .authenticate(null, profile); this.dnsZoneManager = withHttpPipeline(httpPipeline, DnsZoneManager.configure()) .authenticate(null, profile); this.appServiceManager = withHttpPipeline(httpPipeline, AppServiceManager.configure()) .authenticate(null, profile); -// this.sqlServerManager = withHttpPipeline(httpPipeline, SqlServerManager.configure()) -// .authenticate(null, profile); -// this.serviceBusManager = withHttpPipeline(httpPipeline, ServiceBusManager.configure()) -// .authenticate(null, profile); -// this.containerInstanceManager = withHttpPipeline(httpPipeline, ContainerInstanceManager.configure()) -// .authenticate(null, profile); -// this.containerRegistryManager = withHttpPipeline(httpPipeline, ContainerRegistryManager.configure()) -// .authenticate(null, profile); + this.sqlServerManager = withHttpPipeline(httpPipeline, SqlServerManager.configure()) + .authenticate(null, profile); + this.serviceBusManager = withHttpPipeline(httpPipeline, ServiceBusManager.configure()) + .authenticate(null, profile); + this.containerInstanceManager = withHttpPipeline(httpPipeline, ContainerInstanceManager.configure()) + .authenticate(null, profile); + this.containerRegistryManager = withHttpPipeline(httpPipeline, ContainerRegistryManager.configure()) + .authenticate(null, profile); this.containerServiceManager = withHttpPipeline(httpPipeline, ContainerServiceManager.configure()) .authenticate(null, profile); this.cosmosManager = withHttpPipeline(httpPipeline, CosmosManager.configure()) @@ -366,12 +390,12 @@ private AzureResourceManager(HttpPipeline httpPipeline, AzureProfile profile, Au .authenticate(null, profile); this.monitorManager = withHttpPipeline(httpPipeline, MonitorManager.configure()) .authenticate(null, profile); -// this.eventHubsManager = withHttpPipeline(httpPipeline, EventHubsManager.configure()) -// .authenticate(null, profile); -// this.appPlatformManager = withHttpPipeline(httpPipeline, AppPlatformManager.configure()) -// .authenticate(null, profile); -// this.privateDnsZoneManager = withHttpPipeline(httpPipeline, PrivateDnsZoneManager.configure()) -// .authenticate(null, profile); + this.eventHubsManager = withHttpPipeline(httpPipeline, EventHubsManager.configure()) + .authenticate(null, profile); + this.appPlatformManager = withHttpPipeline(httpPipeline, AppPlatformManager.configure()) + .authenticate(null, profile); + this.privateDnsZoneManager = withHttpPipeline(httpPipeline, PrivateDnsZoneManager.configure()) + .authenticate(null, profile); this.authenticated = authenticated; this.subscriptionId = profile.getSubscriptionId(); this.tenantId = profile.getTenantId(); @@ -606,24 +630,24 @@ public Vaults vaults() { // return batchManager.batchAccounts(); // } -// /** -// * @return entry point to managing traffic manager profiles. -// */ -// public TrafficManagerProfiles trafficManagerProfiles() { -// return trafficManager.profiles(); -// } -// -// /** @return entry point to managing Redis Caches. */ -// public RedisCaches redisCaches() { -// return redisManager.redisCaches(); -// } -// -// /** -// * @return entry point to managing cdn manager profiles. -// */ -// public CdnProfiles cdnProfiles() { -// return cdnManager.profiles(); -// } + /** + * @return entry point to managing traffic manager profiles. + */ + public TrafficManagerProfiles trafficManagerProfiles() { + return trafficManager.profiles(); + } + + /** @return entry point to managing Redis Caches. */ + public RedisCaches redisCaches() { + return redisManager.redisCaches(); + } + + /** + * @return entry point to managing cdn manager profiles. + */ + public CdnProfiles cdnProfiles() { + return cdnManager.profiles(); + } /** @return entry point to managing DNS zones. */ public DnsZones dnsZones() { @@ -660,17 +684,17 @@ public AppServiceCertificateOrders appServiceCertificateOrders() { return appServiceManager.certificateOrders(); } -// /** @return entry point to managing Sql server. */ -// public SqlServers sqlServers() { -// return sqlServerManager.sqlServers(); -// } -// -// /** -// * @return entry point to managing Service Bus. -// */ -// public ServiceBusNamespaces serviceBusNamespaces() { -// return serviceBusManager.namespaces(); -// } + /** @return entry point to managing Sql server. */ + public SqlServers sqlServers() { + return sqlServerManager.sqlServers(); + } + + /** + * @return entry point to managing Service Bus. + */ + public ServiceBusNamespaces serviceBusNamespaces() { + return serviceBusManager.namespaces(); + } /** @return entry point to managing Service Bus operations. */ // TODO: To be revisited in the future @@ -684,25 +708,25 @@ public KubernetesClusters kubernetesClusters() { return containerServiceManager.kubernetesClusters(); } -// /** @return entry point to managing Azure Container Instances. */ -// public ContainerGroups containerGroups() { -// return containerInstanceManager.containerGroups(); -// } -// -// /** @return entry point to managing Container Registries. */ -// public Registries containerRegistries() { -// return containerRegistryManager.containerRegistries(); -// } -// -// /** @return entry point to managing Container Registry RegistryTasks. */ -// public RegistryTasks containerRegistryTasks() { -// return containerRegistryManager.containerRegistryTasks(); -// } -// -// /** @return entry point to managing Container Registry RegistryTask Runs. */ -// public RegistryTaskRuns containerRegistryTaskRuns() { -// return containerRegistryManager.registryTaskRuns(); -// } + /** @return entry point to managing Azure Container Instances. */ + public ContainerGroups containerGroups() { + return containerInstanceManager.containerGroups(); + } + + /** @return entry point to managing Container Registries. */ + public Registries containerRegistries() { + return containerRegistryManager.containerRegistries(); + } + + /** @return entry point to managing Container Registry RegistryTasks. */ + public RegistryTasks containerRegistryTasks() { + return containerRegistryManager.containerRegistryTasks(); + } + + /** @return entry point to managing Container Registry RegistryTask Runs. */ + public RegistryTaskRuns containerRegistryTaskRuns() { + return containerRegistryManager.registryTaskRuns(); + } /** @return entry point to managing Container Regsitries. */ public CosmosDBAccounts cosmosDBAccounts() { @@ -757,26 +781,26 @@ public AutoscaleSettings autoscaleSettings() { return this.monitorManager.autoscaleSettings(); } -// /** -// * @return entry point to managing event hub namespaces. -// */ -// public EventHubNamespaces eventHubNamespaces() { -// return this.eventHubsManager.namespaces(); -// } -// -// /** -// * @return entry point to managing event hubs. -// */ -// public EventHubs eventHubs() { -// return this.eventHubsManager.eventHubs(); -// } -// -// /** -// * @return entry point to managing event hub namespace geo disaster recovery. -// */ -// public EventHubDisasterRecoveryPairings eventHubDisasterRecoveryPairings() { -// return this.eventHubsManager.eventHubDisasterRecoveryPairings(); -// } + /** + * @return entry point to managing event hub namespaces. + */ + public EventHubNamespaces eventHubNamespaces() { + return this.eventHubsManager.namespaces(); + } + + /** + * @return entry point to managing event hubs. + */ + public EventHubs eventHubs() { + return this.eventHubsManager.eventHubs(); + } + + /** + * @return entry point to managing event hub namespace geo disaster recovery. + */ + public EventHubDisasterRecoveryPairings eventHubDisasterRecoveryPairings() { + return this.eventHubsManager.eventHubDisasterRecoveryPairings(); + } /** @return entry point to manage compute galleries. */ public Galleries galleries() { @@ -808,13 +832,13 @@ public ManagementPolicies storageManagementPolicies() { return this.storageManager.managementPolicies(); } -// /** @return the spring service management API entry point */ -// public SpringServices springServices() { -// return this.appPlatformManager.springServices(); -// } -// -// /** @return the private DNS zone management API entry point */ -// public PrivateDnsZones privateDnsZones() { -// return this.privateDnsZoneManager.privateZones(); -// } + /** @return the spring service management API entry point */ + public SpringServices springServices() { + return this.appPlatformManager.springServices(); + } + + /** @return the private DNS zone management API entry point */ + public PrivateDnsZones privateDnsZones() { + return this.privateDnsZoneManager.privateZones(); + } } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/main/java/module-info.java b/sdk/resourcemanager/azure-resourcemanager/src/main/java/module-info.java index c1b7d9d69294..c19067d43344 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/main/java/module-info.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/main/java/module-info.java @@ -3,21 +3,21 @@ module com.azure.resourcemanager { requires transitive com.azure.resourcemanager.resources; -// requires transitive com.azure.resourcemanager.appplatform; + requires transitive com.azure.resourcemanager.appplatform; requires transitive com.azure.resourcemanager.appservice; -// requires transitive com.azure.resourcemanager.cdn; + requires transitive com.azure.resourcemanager.cdn; requires transitive com.azure.resourcemanager.compute; -// requires transitive com.azure.resourcemanager.containerinstance; -// requires transitive com.azure.resourcemanager.containerregistry; + requires transitive com.azure.resourcemanager.containerinstance; + requires transitive com.azure.resourcemanager.containerregistry; requires transitive com.azure.resourcemanager.containerservice; requires transitive com.azure.resourcemanager.cosmos; -// requires transitive com.azure.resourcemanager.eventhubs; + requires transitive com.azure.resourcemanager.eventhubs; requires transitive com.azure.resourcemanager.monitor; -// requires transitive com.azure.resourcemanager.privatedns; -// requires transitive com.azure.resourcemanager.redis; -// requires transitive com.azure.resourcemanager.servicebus; -// requires transitive com.azure.resourcemanager.sql; -// requires transitive com.azure.resourcemanager.trafficmanager; + requires transitive com.azure.resourcemanager.privatedns; + requires transitive com.azure.resourcemanager.redis; + requires transitive com.azure.resourcemanager.servicebus; + requires transitive com.azure.resourcemanager.sql; + requires transitive com.azure.resourcemanager.trafficmanager; exports com.azure.resourcemanager; } diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java index f55948e73f85..075d90df7fdc 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/AzureResourceManagerTests.java @@ -9,9 +9,8 @@ import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.rest.PagedIterable; -import com.azure.core.management.Region; import com.azure.core.management.exception.ManagementException; -import com.azure.core.management.profile.AzureProfile; +import com.azure.resourcemanager.authorization.models.BuiltInRole; import com.azure.resourcemanager.compute.models.CachingTypes; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; import com.azure.resourcemanager.compute.models.PowerState; @@ -21,6 +20,12 @@ import com.azure.resourcemanager.compute.models.VirtualMachinePublisher; import com.azure.resourcemanager.compute.models.VirtualMachineSizeTypes; import com.azure.resourcemanager.compute.models.VirtualMachineSku; +import com.azure.resourcemanager.containerinstance.models.Container; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; +import com.azure.resourcemanager.containerinstance.models.Operation; +import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType; +import com.azure.resourcemanager.msi.models.Identity; import com.azure.resourcemanager.network.models.Access; import com.azure.resourcemanager.network.models.ConnectionMonitor; import com.azure.resourcemanager.network.models.ConnectionMonitorQueryResult; @@ -38,8 +43,13 @@ import com.azure.resourcemanager.network.models.SecurityGroupView; import com.azure.resourcemanager.network.models.Topology; import com.azure.resourcemanager.network.models.VerificationIPFlow; -import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; import com.azure.resourcemanager.resources.fluentcore.arm.implementation.AzureConfigurableImpl; +import com.azure.resourcemanager.storage.models.StorageAccountSkuType; +import com.azure.resourcemanager.test.utils.TestUtilities; +import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.fluentcore.model.Creatable; +import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.resources.fluentcore.utils.HttpPipelineProvider; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.resources.models.Deployment; @@ -50,15 +60,6 @@ import com.azure.resourcemanager.resources.models.RegionType; import com.azure.resourcemanager.resources.models.Subscription; import com.azure.resourcemanager.storage.models.StorageAccount; -import com.azure.resourcemanager.storage.models.StorageAccountSkuType; -import com.azure.resourcemanager.test.ResourceManagerTestBase; -import com.azure.resourcemanager.test.utils.TestDelayProvider; -import com.azure.resourcemanager.test.utils.TestIdentifierProvider; -import com.azure.resourcemanager.test.utils.TestUtilities; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; - import java.io.IOException; import java.text.MessageFormat; import java.time.Duration; @@ -68,9 +69,18 @@ import java.util.Collection; import java.util.List; import java.util.Locale; +import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +import com.azure.resourcemanager.test.ResourceManagerTestBase; +import com.azure.resourcemanager.test.utils.TestDelayProvider; +import com.azure.resourcemanager.test.utils.TestIdentifierProvider; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; public class AzureResourceManagerTests extends ResourceManagerTestBase { private AzureResourceManager azureResourceManager; @@ -1085,16 +1095,16 @@ public void createStorageAccount() throws Exception { // new TestBatch().runTest(azure.batchAccounts(), azure.resourceGroups()); // } -// @Test -// public void testTrafficManager() throws Exception { -// new TestTrafficManager(azureResourceManager.publicIpAddresses()) -// .runTest(azureResourceManager.trafficManagerProfiles(), azureResourceManager.resourceGroups()); -// } -// -// @Test -// public void testRedis() throws Exception { -// new TestRedis().runTest(azureResourceManager.redisCaches(), azureResourceManager.resourceGroups()); -// } + @Test + public void testTrafficManager() throws Exception { + new TestTrafficManager(azureResourceManager.publicIpAddresses()) + .runTest(azureResourceManager.trafficManagerProfiles(), azureResourceManager.resourceGroups()); + } + + @Test + public void testRedis() throws Exception { + new TestRedis().runTest(azureResourceManager.redisCaches(), azureResourceManager.resourceGroups()); + } // @Test // public void testCdnManager() throws Exception { @@ -1107,15 +1117,15 @@ public void testDnsZones() throws Exception { new TestDns().runTest(azureResourceManager.dnsZones(), azureResourceManager.resourceGroups()); } -// @Test -// public void testPrivateDnsZones() throws Exception { -// new TestPrivateDns().runTest(azureResourceManager.privateDnsZones(), azureResourceManager.resourceGroups()); -// } -// -// @Test -// public void testSqlServer() throws Exception { -// new TestSql().runTest(azureResourceManager.sqlServers(), azureResourceManager.resourceGroups()); -// } + @Test + public void testPrivateDnsZones() throws Exception { + new TestPrivateDns().runTest(azureResourceManager.privateDnsZones(), azureResourceManager.resourceGroups()); + } + + @Test + public void testSqlServer() throws Exception { + new TestSql().runTest(azureResourceManager.sqlServers(), azureResourceManager.resourceGroups()); + } @Test public void testResourceStreaming() throws Exception { @@ -1127,145 +1137,145 @@ public void testKubernetesCluster() throws Exception { new TestKubernetesCluster().runTest(azureResourceManager.kubernetesClusters(), azureResourceManager.resourceGroups()); } -// @Test -// public void testContainerInstanceWithPublicIpAddressWithSystemAssignedMsi() throws Exception { -// new TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI() -// .runTest(azureResourceManager.containerGroups(), azureResourceManager.resourceGroups(), azureResourceManager.subscriptionId()); -// } - -// @Test -// public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() throws Exception { -// final String cgName = generateRandomResourceName("aci", 10); -// final String rgName = generateRandomResourceName("rgaci", 10); -// String identityName1 = generateRandomResourceName("msi-id", 15); -// String identityName2 = generateRandomResourceName("msi-id", 15); -// -// final Identity createdIdentity = -// azureResourceManager -// .identities() -// .define(identityName1) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withAccessToCurrentResourceGroup(BuiltInRole.READER) -// .create(); -// -// Creatable creatableIdentity = -// azureResourceManager -// .identities() -// .define(identityName2) -// .withRegion(Region.US_WEST) -// .withExistingResourceGroup(rgName) -// .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); -// -// List dnsServers = new ArrayList(); -// dnsServers.add("dnsServer1"); -// ContainerGroup containerGroup = -// azureResourceManager -// .containerGroups() -// .define(cgName) -// .withRegion(Region.US_EAST2) -// .withExistingResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .withEmptyDirectoryVolume("emptydir1") -// .defineContainerInstance("tomcat") -// .withImage("tomcat") -// .withExternalTcpPort(8080) -// .withCpuCoreCount(1) -// .withEnvironmentVariable("ENV1", "value1") -// .attach() -// .defineContainerInstance("nginx") -// .withImage("nginx") -// .withExternalTcpPort(80) -// .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") -// .attach() -// .withExistingUserAssignedManagedServiceIdentity(createdIdentity) -// .withNewUserAssignedManagedServiceIdentity(creatableIdentity) -// .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) -// .withDnsPrefix(cgName) -// .withTag("tag1", "value1") -// .create(); -// -// Assertions.assertEquals(cgName, containerGroup.name()); -// Assertions.assertEquals("Linux", containerGroup.osType().toString()); -// Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); -// Assertions.assertEquals(1, containerGroup.volumes().size()); -// Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); -// Assertions.assertNotNull(containerGroup.ipAddress()); -// Assertions.assertTrue(containerGroup.isIPAddressPublic()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(2, containerGroup.externalPorts().size()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); -// Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); -// Assertions.assertEquals(2, containerGroup.containers().size()); -// Container tomcatContainer = containerGroup.containers().get("tomcat"); -// Assertions.assertNotNull(tomcatContainer); -// Container nginxContainer = containerGroup.containers().get("nginx"); -// Assertions.assertNotNull(nginxContainer); -// Assertions.assertEquals("tomcat", tomcatContainer.name()); -// Assertions.assertEquals("tomcat", tomcatContainer.image()); -// Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, tomcatContainer.ports().size()); -// Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); -// Assertions.assertNull(tomcatContainer.volumeMounts()); -// Assertions.assertNull(tomcatContainer.command()); -// Assertions.assertNotNull(tomcatContainer.environmentVariables()); -// Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); -// Assertions.assertEquals("nginx", nginxContainer.name()); -// Assertions.assertEquals("nginx", nginxContainer.image()); -// Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, nginxContainer.ports().size()); -// Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); -// Assertions.assertNull(nginxContainer.volumeMounts()); -// Assertions.assertNull(nginxContainer.command()); -// Assertions.assertNotNull(nginxContainer.environmentVariables()); -// Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); -// Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); -// Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); -// Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); -// Assertions.assertEquals(ResourceIdentityType.USER_ASSIGNED, containerGroup.managedServiceIdentityType()); -// Assertions.assertNull(containerGroup.systemAssignedManagedServiceIdentityPrincipalId()); // No Local MSI enabled -// -// // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine -// // -// Set emsiIds = containerGroup.userAssignedManagedServiceIdentityIds(); -// Assertions.assertNotNull(emsiIds); -// Assertions.assertEquals(2, emsiIds.size()); -// Assertions.assertEquals(cgName, containerGroup.dnsPrefix()); -// -// // TODO: add network and dns testing when questions have been answered -// -// ContainerGroup containerGroup2 = azureResourceManager.containerGroups().getByResourceGroup(rgName, cgName); -// -// List containerGroupList = -// azureResourceManager.containerGroups().listByResourceGroup(rgName).stream().collect(Collectors.toList()); -// Assertions.assertTrue(containerGroupList.size() > 0); -// -// containerGroup.refresh(); -// -// Set containerGroupOperations = -// azureResourceManager.containerGroups().listOperations().stream().collect(Collectors.toSet()); -// // Number of supported operation can change hence don't assert with a predefined number. -// Assertions.assertTrue(containerGroupOperations.size() > 0); -// } -// -// @Disabled("Cannot run test due to unknown parameter") -// @Test -// public void testContainerInstanceWithPrivateIpAddress() throws Exception { -// // LIVE ONLY TEST BECAUSE IT REQUIRES SUBSCRIPTION ID -// if (!isPlaybackMode()) { -// new TestContainerInstanceWithPrivateIpAddress() -// .runTest(azureResourceManager.containerGroups(), azureResourceManager.resourceGroups(), azureResourceManager.subscriptionId()); -// } -// } -// -// @Test -// public void testContainerRegistry() throws Exception { -// new TestContainerRegistry().runTest(azureResourceManager.containerRegistries(), azureResourceManager.resourceGroups()); -// } + @Test + public void testContainerInstanceWithPublicIpAddressWithSystemAssignedMsi() throws Exception { + new TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI() + .runTest(azureResourceManager.containerGroups(), azureResourceManager.resourceGroups(), azureResourceManager.subscriptionId()); + } + + @Test + public void testContainerInstanceWithPublicIpAddressWithUserAssignedMsi() throws Exception { + final String cgName = generateRandomResourceName("aci", 10); + final String rgName = generateRandomResourceName("rgaci", 10); + String identityName1 = generateRandomResourceName("msi-id", 15); + String identityName2 = generateRandomResourceName("msi-id", 15); + + final Identity createdIdentity = + azureResourceManager + .identities() + .define(identityName1) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withAccessToCurrentResourceGroup(BuiltInRole.READER) + .create(); + + Creatable creatableIdentity = + azureResourceManager + .identities() + .define(identityName2) + .withRegion(Region.US_WEST) + .withExistingResourceGroup(rgName) + .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); + + List dnsServers = new ArrayList(); + dnsServers.add("dnsServer1"); + ContainerGroup containerGroup = + azureResourceManager + .containerGroups() + .define(cgName) + .withRegion(Region.US_EAST2) + .withExistingResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withEmptyDirectoryVolume("emptydir1") + .defineContainerInstance("tomcat") + .withImage("tomcat") + .withExternalTcpPort(8080) + .withCpuCoreCount(1) + .withEnvironmentVariable("ENV1", "value1") + .attach() + .defineContainerInstance("nginx") + .withImage("nginx") + .withExternalTcpPort(80) + .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") + .attach() + .withExistingUserAssignedManagedServiceIdentity(createdIdentity) + .withNewUserAssignedManagedServiceIdentity(creatableIdentity) + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withDnsPrefix(cgName) + .withTag("tag1", "value1") + .create(); + + Assertions.assertEquals(cgName, containerGroup.name()); + Assertions.assertEquals("Linux", containerGroup.osType().toString()); + Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); + Assertions.assertEquals(1, containerGroup.volumes().size()); + Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); + Assertions.assertNotNull(containerGroup.ipAddress()); + Assertions.assertTrue(containerGroup.isIPAddressPublic()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(2, containerGroup.externalPorts().size()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); + Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); + Assertions.assertEquals(2, containerGroup.containers().size()); + Container tomcatContainer = containerGroup.containers().get("tomcat"); + Assertions.assertNotNull(tomcatContainer); + Container nginxContainer = containerGroup.containers().get("nginx"); + Assertions.assertNotNull(nginxContainer); + Assertions.assertEquals("tomcat", tomcatContainer.name()); + Assertions.assertEquals("tomcat", tomcatContainer.image()); + Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, tomcatContainer.ports().size()); + Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); + Assertions.assertNull(tomcatContainer.volumeMounts()); + Assertions.assertNull(tomcatContainer.command()); + Assertions.assertNotNull(tomcatContainer.environmentVariables()); + Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); + Assertions.assertEquals("nginx", nginxContainer.name()); + Assertions.assertEquals("nginx", nginxContainer.image()); + Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, nginxContainer.ports().size()); + Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); + Assertions.assertNull(nginxContainer.volumeMounts()); + Assertions.assertNull(nginxContainer.command()); + Assertions.assertNotNull(nginxContainer.environmentVariables()); + Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); + Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); + Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); + Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); + Assertions.assertEquals(ResourceIdentityType.USER_ASSIGNED, containerGroup.managedServiceIdentityType()); + Assertions.assertNull(containerGroup.systemAssignedManagedServiceIdentityPrincipalId()); // No Local MSI enabled + + // Ensure the "User Assigned (External) MSI" id can be retrieved from the virtual machine + // + Set emsiIds = containerGroup.userAssignedManagedServiceIdentityIds(); + Assertions.assertNotNull(emsiIds); + Assertions.assertEquals(2, emsiIds.size()); + Assertions.assertEquals(cgName, containerGroup.dnsPrefix()); + + // TODO: add network and dns testing when questions have been answered + + ContainerGroup containerGroup2 = azureResourceManager.containerGroups().getByResourceGroup(rgName, cgName); + + List containerGroupList = + azureResourceManager.containerGroups().listByResourceGroup(rgName).stream().collect(Collectors.toList()); + Assertions.assertTrue(containerGroupList.size() > 0); + + containerGroup.refresh(); + + Set containerGroupOperations = + azureResourceManager.containerGroups().listOperations().stream().collect(Collectors.toSet()); + // Number of supported operation can change hence don't assert with a predefined number. + Assertions.assertTrue(containerGroupOperations.size() > 0); + } + + @Disabled("Cannot run test due to unknown parameter") + @Test + public void testContainerInstanceWithPrivateIpAddress() throws Exception { + // LIVE ONLY TEST BECAUSE IT REQUIRES SUBSCRIPTION ID + if (!isPlaybackMode()) { + new TestContainerInstanceWithPrivateIpAddress() + .runTest(azureResourceManager.containerGroups(), azureResourceManager.resourceGroups(), azureResourceManager.subscriptionId()); + } + } + + @Test + public void testContainerRegistry() throws Exception { + new TestContainerRegistry().runTest(azureResourceManager.containerRegistries(), azureResourceManager.resourceGroups()); + } @Test public void testCosmosDB() throws Exception { diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPrivateIpAddress.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPrivateIpAddress.java index dc41815b244e..72047f7a3e6a 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPrivateIpAddress.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPrivateIpAddress.java @@ -1,238 +1,238 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -//package com.azure.resourcemanager; -// -//import com.azure.resourcemanager.authorization.models.BuiltInRole; -//import com.azure.resourcemanager.containerinstance.models.Container; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroups; -//import com.azure.resourcemanager.containerinstance.models.ContainerPort; -//import com.azure.resourcemanager.containerinstance.models.EnvironmentVariable; -//import com.azure.resourcemanager.containerinstance.models.Operation; -//import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType; -//import com.azure.resourcemanager.containerinstance.models.Volume; -//import com.azure.resourcemanager.containerinstance.models.VolumeMount; -//import com.azure.core.management.Region; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.stream.Collectors; -//import org.junit.jupiter.api.Assertions; -// -//public class TestContainerInstanceWithPrivateIpAddress extends TestTemplate { -// -// @Override -// public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { -// final String cgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); -// final String rgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); -// -// final String logAnalyticsWorkspaceId = "REPLACE WITH YOUR LOG ANALYTICS WORKSPACE ID"; -// final String logAnalyticsWorkspaceKey = "REPLACE WITH YOUR LOG ANALYTICS WORKSPACE KEY"; -// final String networkProfileSubscriptionId = "REPLACE WITH YOUR NETWORK PROFILE SUBSCRIPTION ID"; -// final String networkProfileResourceGroupName = "REPLACE WITH YOUR NETWORK PROFILE RESOURCE GROUP NAME"; -// final String networkProfileName = "REPLEACE WITH YOUR NETWORK PROFILE NAME"; -// final List dnsServerNames = new ArrayList(); -// dnsServerNames.add("dnsServer1"); -// -// List dnsServers = new ArrayList(); -// dnsServers.add("dnsServer1"); -// ContainerGroup containerGroup = -// containerGroups -// .define(cgName) -// .withRegion(Region.US_WEST) -// .withNewResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .withEmptyDirectoryVolume("emptydir1") -// .defineContainerInstance("tomcat") -// .withImage("tomcat") -// .withExternalTcpPort(8080) -// .withCpuCoreCount(1) -// .withEnvironmentVariable("ENV1", "value1") -// .attach() -// .defineContainerInstance("nginx") -// .withImage("nginx") -// .withExternalTcpPort(80) -// .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") -// .attach() -// .withSystemAssignedManagedServiceIdentity() -// .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) -// .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) -// .withLogAnalytics(logAnalyticsWorkspaceId, logAnalyticsWorkspaceKey) -// .withExistingNetworkProfile(networkProfileSubscriptionId, networkProfileResourceGroupName, networkProfileName) -// .withDnsConfiguration(dnsServerNames, "dnsSearchDomains", "dnsOptions") -// .withTag("tag1", "value1") -// .create(); -// -// Assertions.assertEquals(cgName, containerGroup.name()); -// Assertions.assertEquals("Linux", containerGroup.osType().toString()); -// Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); -// Assertions.assertEquals(1, containerGroup.volumes().size()); -// Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); -// Assertions.assertNotNull(containerGroup.ipAddress()); -// Assertions.assertTrue(containerGroup.isIPAddressPrivate()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(2, containerGroup.externalPorts().size()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); -// Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); -// Assertions.assertEquals(2, containerGroup.containers().size()); -// Container tomcatContainer = containerGroup.containers().get("tomcat"); -// Assertions.assertNotNull(tomcatContainer); -// Container nginxContainer = containerGroup.containers().get("nginx"); -// Assertions.assertNotNull(nginxContainer); -// Assertions.assertEquals("tomcat", tomcatContainer.name()); -// Assertions.assertEquals("tomcat", tomcatContainer.image()); -// Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, tomcatContainer.ports().size()); -// Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); -// Assertions.assertNull(tomcatContainer.volumeMounts()); -// Assertions.assertNull(tomcatContainer.command()); -// Assertions.assertNotNull(tomcatContainer.environmentVariables()); -// Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); -// Assertions.assertEquals("nginx", nginxContainer.name()); -// Assertions.assertEquals("nginx", nginxContainer.image()); -// Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, nginxContainer.ports().size()); -// Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); -// Assertions.assertNull(nginxContainer.volumeMounts()); -// Assertions.assertNull(nginxContainer.command()); -// Assertions.assertNotNull(nginxContainer.environmentVariables()); -// Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); -// Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); -// Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); -// Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); -// Assertions.assertEquals(ResourceIdentityType.SYSTEM_ASSIGNED, containerGroup.managedServiceIdentityType()); -// Assertions.assertEquals(logAnalyticsWorkspaceId, containerGroup.logAnalytics().workspaceId()); -// Assertions -// .assertEquals( -// "/subscriptions/" -// + networkProfileSubscriptionId -// + "/resourceGroups/" -// + networkProfileResourceGroupName -// + "/providers/Microsoft.Network/networkProfiles/" -// + networkProfileName, -// containerGroup.networkProfileId()); -// Assertions.assertEquals("dnsServer1", containerGroup.dnsConfig().nameServers().get(0)); -// Assertions.assertEquals("dnsSearchDomains", containerGroup.dnsConfig().searchDomains()); -// Assertions.assertEquals("dnsOptions", containerGroup.dnsConfig().options()); -// -// ContainerGroup containerGroup2 = containerGroups.getByResourceGroup(rgName, cgName); -// -// List containerGroupList = -// containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); -// Assertions.assertTrue(containerGroupList.size() > 0); -// -// containerGroup.refresh(); -// -// Set containerGroupOperations = containerGroups.listOperations().stream().collect(Collectors.toSet()); -// // Number of supported operation can change hence don't assert with a predefined number. -// Assertions.assertTrue(containerGroupOperations.size() > 0); -// -// return containerGroup; -// } -// -// @Override -// public ContainerGroup updateResource(ContainerGroup containerGroup) throws Exception { -// containerGroup.update().withoutTag("tag1").withTag("tag2", "value2").apply(); -// Assertions.assertFalse(containerGroup.tags().containsKey("tag")); -// Assertions.assertTrue(containerGroup.tags().containsKey("tag2")); -// -// containerGroup.restart(); -// containerGroup.stop(); -// -// return containerGroup; -// } -// -// @Override -// public 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()); -// } -//} + +package com.azure.resourcemanager; + +import com.azure.resourcemanager.authorization.models.BuiltInRole; +import com.azure.resourcemanager.containerinstance.models.Container; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; +import com.azure.resourcemanager.containerinstance.models.ContainerGroups; +import com.azure.resourcemanager.containerinstance.models.ContainerPort; +import com.azure.resourcemanager.containerinstance.models.EnvironmentVariable; +import com.azure.resourcemanager.containerinstance.models.Operation; +import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType; +import com.azure.resourcemanager.containerinstance.models.Volume; +import com.azure.resourcemanager.containerinstance.models.VolumeMount; +import com.azure.core.management.Region; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; + +public class TestContainerInstanceWithPrivateIpAddress extends TestTemplate { + + @Override + public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { + final String cgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); + final String rgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); + + final String logAnalyticsWorkspaceId = "REPLACE WITH YOUR LOG ANALYTICS WORKSPACE ID"; + final String logAnalyticsWorkspaceKey = "REPLACE WITH YOUR LOG ANALYTICS WORKSPACE KEY"; + final String networkProfileSubscriptionId = "REPLACE WITH YOUR NETWORK PROFILE SUBSCRIPTION ID"; + final String networkProfileResourceGroupName = "REPLACE WITH YOUR NETWORK PROFILE RESOURCE GROUP NAME"; + final String networkProfileName = "REPLEACE WITH YOUR NETWORK PROFILE NAME"; + final List dnsServerNames = new ArrayList(); + dnsServerNames.add("dnsServer1"); + + List dnsServers = new ArrayList(); + dnsServers.add("dnsServer1"); + ContainerGroup containerGroup = + containerGroups + .define(cgName) + .withRegion(Region.US_WEST) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withEmptyDirectoryVolume("emptydir1") + .defineContainerInstance("tomcat") + .withImage("tomcat") + .withExternalTcpPort(8080) + .withCpuCoreCount(1) + .withEnvironmentVariable("ENV1", "value1") + .attach() + .defineContainerInstance("nginx") + .withImage("nginx") + .withExternalTcpPort(80) + .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") + .attach() + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withLogAnalytics(logAnalyticsWorkspaceId, logAnalyticsWorkspaceKey) + .withExistingNetworkProfile(networkProfileSubscriptionId, networkProfileResourceGroupName, networkProfileName) + .withDnsConfiguration(dnsServerNames, "dnsSearchDomains", "dnsOptions") + .withTag("tag1", "value1") + .create(); + + Assertions.assertEquals(cgName, containerGroup.name()); + Assertions.assertEquals("Linux", containerGroup.osType().toString()); + Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); + Assertions.assertEquals(1, containerGroup.volumes().size()); + Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); + Assertions.assertNotNull(containerGroup.ipAddress()); + Assertions.assertTrue(containerGroup.isIPAddressPrivate()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(2, containerGroup.externalPorts().size()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); + Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); + Assertions.assertEquals(2, containerGroup.containers().size()); + Container tomcatContainer = containerGroup.containers().get("tomcat"); + Assertions.assertNotNull(tomcatContainer); + Container nginxContainer = containerGroup.containers().get("nginx"); + Assertions.assertNotNull(nginxContainer); + Assertions.assertEquals("tomcat", tomcatContainer.name()); + Assertions.assertEquals("tomcat", tomcatContainer.image()); + Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, tomcatContainer.ports().size()); + Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); + Assertions.assertNull(tomcatContainer.volumeMounts()); + Assertions.assertNull(tomcatContainer.command()); + Assertions.assertNotNull(tomcatContainer.environmentVariables()); + Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); + Assertions.assertEquals("nginx", nginxContainer.name()); + Assertions.assertEquals("nginx", nginxContainer.image()); + Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, nginxContainer.ports().size()); + Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); + Assertions.assertNull(nginxContainer.volumeMounts()); + Assertions.assertNull(nginxContainer.command()); + Assertions.assertNotNull(nginxContainer.environmentVariables()); + Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); + Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); + Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); + Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); + Assertions.assertEquals(ResourceIdentityType.SYSTEM_ASSIGNED, containerGroup.managedServiceIdentityType()); + Assertions.assertEquals(logAnalyticsWorkspaceId, containerGroup.logAnalytics().workspaceId()); + Assertions + .assertEquals( + "/subscriptions/" + + networkProfileSubscriptionId + + "/resourceGroups/" + + networkProfileResourceGroupName + + "/providers/Microsoft.Network/networkProfiles/" + + networkProfileName, + containerGroup.networkProfileId()); + Assertions.assertEquals("dnsServer1", containerGroup.dnsConfig().nameServers().get(0)); + Assertions.assertEquals("dnsSearchDomains", containerGroup.dnsConfig().searchDomains()); + Assertions.assertEquals("dnsOptions", containerGroup.dnsConfig().options()); + + ContainerGroup containerGroup2 = containerGroups.getByResourceGroup(rgName, cgName); + + List containerGroupList = + containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); + Assertions.assertTrue(containerGroupList.size() > 0); + + containerGroup.refresh(); + + Set containerGroupOperations = containerGroups.listOperations().stream().collect(Collectors.toSet()); + // Number of supported operation can change hence don't assert with a predefined number. + Assertions.assertTrue(containerGroupOperations.size() > 0); + + return containerGroup; + } + + @Override + public ContainerGroup updateResource(ContainerGroup containerGroup) throws Exception { + containerGroup.update().withoutTag("tag1").withTag("tag2", "value2").apply(); + Assertions.assertFalse(containerGroup.tags().containsKey("tag")); + Assertions.assertTrue(containerGroup.tags().containsKey("tag2")); + + containerGroup.restart(); + containerGroup.stop(); + + return containerGroup; + } + + @Override + public 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()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java index b1ab2d4a95f5..435a4212f531 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI.java @@ -1,216 +1,216 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -//package com.azure.resourcemanager; -// -//import com.azure.resourcemanager.authorization.models.BuiltInRole; -//import com.azure.resourcemanager.containerinstance.models.Container; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroup; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; -//import com.azure.resourcemanager.containerinstance.models.ContainerGroups; -//import com.azure.resourcemanager.containerinstance.models.ContainerPort; -//import com.azure.resourcemanager.containerinstance.models.EnvironmentVariable; -//import com.azure.resourcemanager.containerinstance.models.Operation; -//import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType; -//import com.azure.resourcemanager.containerinstance.models.Volume; -//import com.azure.resourcemanager.containerinstance.models.VolumeMount; -//import com.azure.core.management.Region; -//import java.util.ArrayList; -//import java.util.List; -//import java.util.Map; -//import java.util.Set; -//import java.util.stream.Collectors; -//import org.junit.jupiter.api.Assertions; -// -//public class TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI -// extends TestTemplate { -// -// @Override -// public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { -// final String cgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); -// final String rgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); -// -// List dnsServers = new ArrayList(); -// dnsServers.add("dnsServer1"); -// ContainerGroup containerGroup = -// containerGroups -// .define(cgName) -// .withRegion(Region.US_EAST2) -// .withNewResourceGroup(rgName) -// .withLinux() -// .withPublicImageRegistryOnly() -// .withEmptyDirectoryVolume("emptydir1") -// .defineContainerInstance("tomcat") -// .withImage("tomcat") -// .withExternalTcpPort(8080) -// .withCpuCoreCount(1) -// .withEnvironmentVariable("ENV1", "value1") -// .attach() -// .defineContainerInstance("nginx") -// .withImage("nginx") -// .withExternalTcpPort(80) -// .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") -// .attach() -// .withSystemAssignedManagedServiceIdentity() -// .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) -// .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) -// .withDnsPrefix(cgName) -// .withTag("tag1", "value1") -// .create(); -// -// Assertions.assertEquals(cgName, containerGroup.name()); -// Assertions.assertEquals("Linux", containerGroup.osType().toString()); -// Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); -// Assertions.assertEquals(1, containerGroup.volumes().size()); -// Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); -// Assertions.assertNotNull(containerGroup.ipAddress()); -// Assertions.assertTrue(containerGroup.isIPAddressPublic()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(2, containerGroup.externalPorts().size()); -// Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); -// Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); -// Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); -// Assertions.assertEquals(2, containerGroup.containers().size()); -// Container tomcatContainer = containerGroup.containers().get("tomcat"); -// Assertions.assertNotNull(tomcatContainer); -// Container nginxContainer = containerGroup.containers().get("nginx"); -// Assertions.assertNotNull(nginxContainer); -// Assertions.assertEquals("tomcat", tomcatContainer.name()); -// Assertions.assertEquals("tomcat", tomcatContainer.image()); -// Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, tomcatContainer.ports().size()); -// Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); -// Assertions.assertNull(tomcatContainer.volumeMounts()); -// Assertions.assertNull(tomcatContainer.command()); -// Assertions.assertNotNull(tomcatContainer.environmentVariables()); -// Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); -// Assertions.assertEquals("nginx", nginxContainer.name()); -// Assertions.assertEquals("nginx", nginxContainer.image()); -// Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); -// Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); -// Assertions.assertEquals(1, nginxContainer.ports().size()); -// Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); -// Assertions.assertNull(nginxContainer.volumeMounts()); -// Assertions.assertNull(nginxContainer.command()); -// Assertions.assertNotNull(nginxContainer.environmentVariables()); -// Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); -// Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); -// Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); -// Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); -// Assertions.assertEquals(ResourceIdentityType.SYSTEM_ASSIGNED, containerGroup.managedServiceIdentityType()); -// Assertions.assertEquals(cgName, containerGroup.dnsPrefix()); -// ContainerGroup containerGroup2 = containerGroups.getByResourceGroup(rgName, cgName); -// -// List containerGroupList = -// containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); -// Assertions.assertTrue(containerGroupList.size() > 0); -// -// containerGroup.refresh(); -// -// Set containerGroupOperations = containerGroups.listOperations().stream().collect(Collectors.toSet()); -// // Number of supported operation can change hence don't assert with a predefined number. -// Assertions.assertTrue(containerGroupOperations.size() > 0); -// -// return containerGroup; -// } -// -// @Override -// public ContainerGroup updateResource(ContainerGroup containerGroup) throws Exception { -// containerGroup.update().withoutTag("tag1").withTag("tag2", "value2").apply(); -// Assertions.assertFalse(containerGroup.tags().containsKey("tag")); -// Assertions.assertTrue(containerGroup.tags().containsKey("tag2")); -// -// containerGroup.restart(); -// containerGroup.stop(); -// -// return containerGroup; -// } -// -// @Override -// public 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()); -// } -//} + +package com.azure.resourcemanager; + +import com.azure.resourcemanager.authorization.models.BuiltInRole; +import com.azure.resourcemanager.containerinstance.models.Container; +import com.azure.resourcemanager.containerinstance.models.ContainerGroup; +import com.azure.resourcemanager.containerinstance.models.ContainerGroupRestartPolicy; +import com.azure.resourcemanager.containerinstance.models.ContainerGroups; +import com.azure.resourcemanager.containerinstance.models.ContainerPort; +import com.azure.resourcemanager.containerinstance.models.EnvironmentVariable; +import com.azure.resourcemanager.containerinstance.models.Operation; +import com.azure.resourcemanager.containerinstance.models.ResourceIdentityType; +import com.azure.resourcemanager.containerinstance.models.Volume; +import com.azure.resourcemanager.containerinstance.models.VolumeMount; +import com.azure.core.management.Region; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; + +public class TestContainerInstanceWithPublicIpAddressWithSystemAssignedMSI + extends TestTemplate { + + @Override + public ContainerGroup createResource(ContainerGroups containerGroups) throws Exception { + final String cgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("aci", 10); + final String rgName = containerGroups.manager().resourceManager().internalContext().randomResourceName("rgaci", 10); + + List dnsServers = new ArrayList(); + dnsServers.add("dnsServer1"); + ContainerGroup containerGroup = + containerGroups + .define(cgName) + .withRegion(Region.US_EAST2) + .withNewResourceGroup(rgName) + .withLinux() + .withPublicImageRegistryOnly() + .withEmptyDirectoryVolume("emptydir1") + .defineContainerInstance("tomcat") + .withImage("tomcat") + .withExternalTcpPort(8080) + .withCpuCoreCount(1) + .withEnvironmentVariable("ENV1", "value1") + .attach() + .defineContainerInstance("nginx") + .withImage("nginx") + .withExternalTcpPort(80) + .withEnvironmentVariableWithSecuredValue("ENV2", "securedValue1") + .attach() + .withSystemAssignedManagedServiceIdentity() + .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) + .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) + .withDnsPrefix(cgName) + .withTag("tag1", "value1") + .create(); + + Assertions.assertEquals(cgName, containerGroup.name()); + Assertions.assertEquals("Linux", containerGroup.osType().toString()); + Assertions.assertEquals(0, containerGroup.imageRegistryServers().size()); + Assertions.assertEquals(1, containerGroup.volumes().size()); + Assertions.assertNotNull(containerGroup.volumes().get("emptydir1")); + Assertions.assertNotNull(containerGroup.ipAddress()); + Assertions.assertTrue(containerGroup.isIPAddressPublic()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(2, containerGroup.externalPorts().size()); + Assertions.assertEquals(2, containerGroup.externalTcpPorts().length); + Assertions.assertEquals(8080, containerGroup.externalTcpPorts()[0]); + Assertions.assertEquals(80, containerGroup.externalTcpPorts()[1]); + Assertions.assertEquals(2, containerGroup.containers().size()); + Container tomcatContainer = containerGroup.containers().get("tomcat"); + Assertions.assertNotNull(tomcatContainer); + Container nginxContainer = containerGroup.containers().get("nginx"); + Assertions.assertNotNull(nginxContainer); + Assertions.assertEquals("tomcat", tomcatContainer.name()); + Assertions.assertEquals("tomcat", tomcatContainer.image()); + Assertions.assertEquals(1.0, tomcatContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, tomcatContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, tomcatContainer.ports().size()); + Assertions.assertEquals(8080, tomcatContainer.ports().get(0).port()); + Assertions.assertNull(tomcatContainer.volumeMounts()); + Assertions.assertNull(tomcatContainer.command()); + Assertions.assertNotNull(tomcatContainer.environmentVariables()); + Assertions.assertEquals(1, tomcatContainer.environmentVariables().size()); + Assertions.assertEquals("nginx", nginxContainer.name()); + Assertions.assertEquals("nginx", nginxContainer.image()); + Assertions.assertEquals(1.0, nginxContainer.resources().requests().cpu(), .1); + Assertions.assertEquals(1.5, nginxContainer.resources().requests().memoryInGB(), .1); + Assertions.assertEquals(1, nginxContainer.ports().size()); + Assertions.assertEquals(80, nginxContainer.ports().get(0).port()); + Assertions.assertNull(nginxContainer.volumeMounts()); + Assertions.assertNull(nginxContainer.command()); + Assertions.assertNotNull(nginxContainer.environmentVariables()); + Assertions.assertEquals(1, nginxContainer.environmentVariables().size()); + Assertions.assertTrue(containerGroup.tags().containsKey("tag1")); + Assertions.assertEquals(ContainerGroupRestartPolicy.NEVER, containerGroup.restartPolicy()); + Assertions.assertTrue(containerGroup.isManagedServiceIdentityEnabled()); + Assertions.assertEquals(ResourceIdentityType.SYSTEM_ASSIGNED, containerGroup.managedServiceIdentityType()); + Assertions.assertEquals(cgName, containerGroup.dnsPrefix()); + ContainerGroup containerGroup2 = containerGroups.getByResourceGroup(rgName, cgName); + + List containerGroupList = + containerGroups.listByResourceGroup(rgName).stream().collect(Collectors.toList()); + Assertions.assertTrue(containerGroupList.size() > 0); + + containerGroup.refresh(); + + Set containerGroupOperations = containerGroups.listOperations().stream().collect(Collectors.toSet()); + // Number of supported operation can change hence don't assert with a predefined number. + Assertions.assertTrue(containerGroupOperations.size() > 0); + + return containerGroup; + } + + @Override + public ContainerGroup updateResource(ContainerGroup containerGroup) throws Exception { + containerGroup.update().withoutTag("tag1").withTag("tag2", "value2").apply(); + Assertions.assertFalse(containerGroup.tags().containsKey("tag")); + Assertions.assertTrue(containerGroup.tags().containsKey("tag2")); + + containerGroup.restart(); + containerGroup.stop(); + + return containerGroup; + } + + @Override + public 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()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java index 934bee46149d..a33e1a9a117e 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestContainerRegistry.java @@ -1,176 +1,176 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager; -// -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.resourcemanager.containerregistry.models.Registries; -//import com.azure.resourcemanager.containerregistry.models.Registry; -//import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; -//import com.azure.resourcemanager.containerregistry.models.Webhook; -//import com.azure.resourcemanager.containerregistry.models.WebhookAction; -//import com.azure.core.management.Region; -//import org.junit.jupiter.api.Assertions; -// -//public class TestContainerRegistry extends TestTemplate { -// -// @Override -// public Registry createResource(Registries registries) throws Exception { -// final String testId = registries.manager().resourceManager().internalContext().randomResourceName("", 8); -// final String newName = "acr" + testId; -// final String rgName = "rgacr" + testId; -// Registry registry = -// registries -// .define(newName + "1") -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withStandardSku() -// .withRegistryNameAsAdminUser() -// .withTag("tag1", "value1") -// .create(); -// -// Assertions.assertTrue(registry.adminUserEnabled()); -// -// RegistryCredentials registryCredentials = registry.getCredentials(); -// Assertions.assertNotNull(registryCredentials); -// Assertions.assertEquals(newName + "1", registryCredentials.username()); -// Assertions.assertEquals(2, registryCredentials.accessKeys().size()); -// Assertions.assertEquals(0, registry.webhooks().list().stream().count()); -// -// Registry registry2 = -// registries -// .define(newName + "2") -// .withRegion(Region.US_EAST) -// .withNewResourceGroup(rgName) -// .withBasicSku() -// .withRegistryNameAsAdminUser() -// .defineWebhook("webhookbing1") -// .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) -// .withServiceUri("https://www.bing.com") -// .withRepositoriesScope("") -// .withTag("tag", "value") -// .withCustomHeader("name", "value") -// .attach() -// .defineWebhook("webhookbing2") -// .withTriggerWhen(WebhookAction.PUSH) -// .withServiceUri("https://www.bing.com") -// .enabled(false) -// .withRepositoriesScope("") -// .withTag("tag", "value") -// .withCustomHeader("name", "value") -// .attach() -// .withTag("tag1", "value1") -// .create(); -// -// Assertions.assertTrue(registry2.adminUserEnabled()); -// -// RegistryCredentials registryCredentials2 = registry2.getCredentials(); -// Assertions.assertNotNull(registryCredentials2); -// Assertions.assertEquals(newName + "2", registryCredentials2.username()); -// Assertions.assertEquals(2, registryCredentials2.accessKeys().size()); -// -// PagedIterable webhooksList = registry2.webhooks().list(); -// -// Assertions.assertEquals(2, webhooksList.stream().count()); -// Webhook webhook = registry2.webhooks().get("webhookbing1"); -// Assertions.assertTrue(webhook.isEnabled()); -// Assertions.assertTrue(webhook.tags().containsKey("tag")); -// Assertions.assertEquals("https://www.bing.com", webhook.serviceUri()); -// Assertions.assertTrue(webhook.isEnabled()); -// Assertions.assertEquals(2, webhook.triggers().size()); -// -// webhook = registries.webhooks().get(rgName, registry2.name(), "webhookbing2"); -// Assertions.assertFalse(webhook.isEnabled()); -// Assertions.assertTrue(webhook.tags().containsKey("tag")); -// Assertions.assertEquals("https://www.bing.com", webhook.serviceUri()); -// Assertions.assertFalse(webhook.isEnabled()); -// Assertions.assertEquals(1, webhook.triggers().size()); -// Assertions.assertEquals(WebhookAction.PUSH, webhook.triggers().toArray()[0]); -// -// Registry registry3 = registries.getById(webhook.parentId()); -// -// return registry3; -// } -// -// @Override -// public Registry updateResource(Registry resource) throws Exception { -// resource -// .update() -// .withoutWebhook("webhookbing1") -// .defineWebhook("webhookms") -// .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) -// .withServiceUri("https://www.microsoft.com") -// .withRepositoriesScope("") -// .enabled(true) -// .attach() -// .updateWebhook("webhookbing2") -// .withServiceUri("https://www.bing.com/maps") -// .withTriggerWhen(WebhookAction.DELETE) -// .withCustomHeader("header", "value") -// .withoutTag("tag") -// .withTag("tag2", "value") -// .parent() -// .withStandardSku() -// .withoutTag("tag1") -// .withTag("tag2", "value") -// .apply(); -// -// Assertions.assertTrue(resource.tags().containsKey("tag2")); -// Assertions.assertFalse(resource.tags().containsKey("tag1")); -// -// Webhook webhook = resource.webhooks().get("webhookbing2"); -// Assertions.assertFalse(webhook.tags().containsKey("tag")); -// Assertions.assertTrue(webhook.tags().containsKey("tag2")); -// Assertions.assertEquals("https://www.bing.com/maps", webhook.serviceUri()); -// Assertions.assertFalse(webhook.isEnabled()); -// Assertions.assertEquals(1, webhook.triggers().size()); -// Assertions.assertEquals(WebhookAction.DELETE, webhook.triggers().toArray()[0]); -// -// webhook.refresh(); -// webhook.enable(); -// Assertions.assertTrue(webhook.isEnabled()); -// -// webhook -// .update() -// .withCustomHeader("header1", "value1") -// .enabled(false) -// .withServiceUri("https://www.msn.com") -// .withRepositoriesScope("") -// .withTriggerWhen(WebhookAction.PUSH) -// .withoutTag("tag2") -// .withTag("tag3", "value") -// .apply(); -// -// Assertions.assertFalse(webhook.isEnabled()); -// Assertions.assertTrue(webhook.tags().containsKey("tag3")); -// Assertions.assertEquals("https://www.msn.com", webhook.serviceUri()); -// Assertions.assertFalse(webhook.isEnabled()); -// Assertions.assertEquals(1, webhook.triggers().size()); -// Assertions.assertEquals(WebhookAction.PUSH, webhook.triggers().toArray()[0]); -// -// webhook.ping(); -// Assertions.assertNotNull(webhook.listEvents()); -// -// resource.webhooks().delete("webhookbing2"); -// -// return resource; -// } -// -// @Override -// public void print(Registry resource) { -// System -// .out -// .println( -// new StringBuilder() -// .append("Regsitry: ") -// .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()) -// .toString()); -// } -//} +package com.azure.resourcemanager; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.resourcemanager.containerregistry.models.Registries; +import com.azure.resourcemanager.containerregistry.models.Registry; +import com.azure.resourcemanager.containerregistry.models.RegistryCredentials; +import com.azure.resourcemanager.containerregistry.models.Webhook; +import com.azure.resourcemanager.containerregistry.models.WebhookAction; +import com.azure.core.management.Region; +import org.junit.jupiter.api.Assertions; + +public class TestContainerRegistry extends TestTemplate { + + @Override + public Registry createResource(Registries registries) throws Exception { + final String testId = registries.manager().resourceManager().internalContext().randomResourceName("", 8); + final String newName = "acr" + testId; + final String rgName = "rgacr" + testId; + Registry registry = + registries + .define(newName + "1") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withStandardSku() + .withRegistryNameAsAdminUser() + .withTag("tag1", "value1") + .create(); + + Assertions.assertTrue(registry.adminUserEnabled()); + + RegistryCredentials registryCredentials = registry.getCredentials(); + Assertions.assertNotNull(registryCredentials); + Assertions.assertEquals(newName + "1", registryCredentials.username()); + Assertions.assertEquals(2, registryCredentials.accessKeys().size()); + Assertions.assertEquals(0, registry.webhooks().list().stream().count()); + + Registry registry2 = + registries + .define(newName + "2") + .withRegion(Region.US_EAST) + .withNewResourceGroup(rgName) + .withBasicSku() + .withRegistryNameAsAdminUser() + .defineWebhook("webhookbing1") + .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) + .withServiceUri("https://www.bing.com") + .withRepositoriesScope("") + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() + .defineWebhook("webhookbing2") + .withTriggerWhen(WebhookAction.PUSH) + .withServiceUri("https://www.bing.com") + .enabled(false) + .withRepositoriesScope("") + .withTag("tag", "value") + .withCustomHeader("name", "value") + .attach() + .withTag("tag1", "value1") + .create(); + + Assertions.assertTrue(registry2.adminUserEnabled()); + + RegistryCredentials registryCredentials2 = registry2.getCredentials(); + Assertions.assertNotNull(registryCredentials2); + Assertions.assertEquals(newName + "2", registryCredentials2.username()); + Assertions.assertEquals(2, registryCredentials2.accessKeys().size()); + + PagedIterable webhooksList = registry2.webhooks().list(); + + Assertions.assertEquals(2, webhooksList.stream().count()); + Webhook webhook = registry2.webhooks().get("webhookbing1"); + Assertions.assertTrue(webhook.isEnabled()); + Assertions.assertTrue(webhook.tags().containsKey("tag")); + Assertions.assertEquals("https://www.bing.com", webhook.serviceUri()); + Assertions.assertTrue(webhook.isEnabled()); + Assertions.assertEquals(2, webhook.triggers().size()); + + webhook = registries.webhooks().get(rgName, registry2.name(), "webhookbing2"); + Assertions.assertFalse(webhook.isEnabled()); + Assertions.assertTrue(webhook.tags().containsKey("tag")); + Assertions.assertEquals("https://www.bing.com", webhook.serviceUri()); + Assertions.assertFalse(webhook.isEnabled()); + Assertions.assertEquals(1, webhook.triggers().size()); + Assertions.assertEquals(WebhookAction.PUSH, webhook.triggers().toArray()[0]); + + Registry registry3 = registries.getById(webhook.parentId()); + + return registry3; + } + + @Override + public Registry updateResource(Registry resource) throws Exception { + resource + .update() + .withoutWebhook("webhookbing1") + .defineWebhook("webhookms") + .withTriggerWhen(WebhookAction.PUSH, WebhookAction.DELETE) + .withServiceUri("https://www.microsoft.com") + .withRepositoriesScope("") + .enabled(true) + .attach() + .updateWebhook("webhookbing2") + .withServiceUri("https://www.bing.com/maps") + .withTriggerWhen(WebhookAction.DELETE) + .withCustomHeader("header", "value") + .withoutTag("tag") + .withTag("tag2", "value") + .parent() + .withStandardSku() + .withoutTag("tag1") + .withTag("tag2", "value") + .apply(); + + Assertions.assertTrue(resource.tags().containsKey("tag2")); + Assertions.assertFalse(resource.tags().containsKey("tag1")); + + Webhook webhook = resource.webhooks().get("webhookbing2"); + Assertions.assertFalse(webhook.tags().containsKey("tag")); + Assertions.assertTrue(webhook.tags().containsKey("tag2")); + Assertions.assertEquals("https://www.bing.com/maps", webhook.serviceUri()); + Assertions.assertFalse(webhook.isEnabled()); + Assertions.assertEquals(1, webhook.triggers().size()); + Assertions.assertEquals(WebhookAction.DELETE, webhook.triggers().toArray()[0]); + + webhook.refresh(); + webhook.enable(); + Assertions.assertTrue(webhook.isEnabled()); + + webhook + .update() + .withCustomHeader("header1", "value1") + .enabled(false) + .withServiceUri("https://www.msn.com") + .withRepositoriesScope("") + .withTriggerWhen(WebhookAction.PUSH) + .withoutTag("tag2") + .withTag("tag3", "value") + .apply(); + + Assertions.assertFalse(webhook.isEnabled()); + Assertions.assertTrue(webhook.tags().containsKey("tag3")); + Assertions.assertEquals("https://www.msn.com", webhook.serviceUri()); + Assertions.assertFalse(webhook.isEnabled()); + Assertions.assertEquals(1, webhook.triggers().size()); + Assertions.assertEquals(WebhookAction.PUSH, webhook.triggers().toArray()[0]); + + webhook.ping(); + Assertions.assertNotNull(webhook.listEvents()); + + resource.webhooks().delete("webhookbing2"); + + return resource; + } + + @Override + public void print(Registry resource) { + System + .out + .println( + new StringBuilder() + .append("Regsitry: ") + .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()) + .toString()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java index 16b2a66df11b..c31fdd62a87e 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestPrivateDns.java @@ -1,409 +1,409 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager; -// -//import com.azure.core.http.rest.PagedIterable; -//import com.azure.resourcemanager.privatedns.models.ARecordSet; -//import com.azure.resourcemanager.privatedns.models.AaaaRecordSet; -//import com.azure.resourcemanager.privatedns.models.CnameRecordSet; -//import com.azure.resourcemanager.privatedns.models.MxRecord; -//import com.azure.resourcemanager.privatedns.models.MxRecordSet; -//import com.azure.resourcemanager.privatedns.models.PrivateDnsRecordSet; -//import com.azure.resourcemanager.privatedns.models.PrivateDnsZone; -//import com.azure.resourcemanager.privatedns.models.PrivateDnsZones; -//import com.azure.resourcemanager.privatedns.models.PtrRecordSet; -//import com.azure.resourcemanager.privatedns.models.RecordType; -//import com.azure.resourcemanager.privatedns.models.SoaRecord; -//import com.azure.resourcemanager.privatedns.models.SoaRecordSet; -//import com.azure.resourcemanager.privatedns.models.SrvRecord; -//import com.azure.resourcemanager.privatedns.models.SrvRecordSet; -//import com.azure.resourcemanager.privatedns.models.TxtRecord; -//import com.azure.resourcemanager.privatedns.models.TxtRecordSet; -//import com.azure.core.management.Region; -//import org.junit.jupiter.api.Assertions; -// -//import java.util.HashMap; -// -//import static com.azure.resourcemanager.privatedns.models.RecordType.AAAA; -//import static com.azure.resourcemanager.privatedns.models.RecordType.MX; -//import static com.azure.resourcemanager.privatedns.models.RecordType.PTR; -//import static com.azure.resourcemanager.privatedns.models.RecordType.SOA; -//import static com.azure.resourcemanager.privatedns.models.RecordType.SRV; -//import static com.azure.resourcemanager.privatedns.models.RecordType.TXT; -// -//public class TestPrivateDns extends TestTemplate { -// @Override -// public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception { -// final Region region = Region.US_EAST; -// final String testId = resources.manager().resourceManager().internalContext().randomResourceName("", 8); -// final String groupName = "rg" + testId; -// final String topLevelDomain = "www.contoso" + testId + ".com"; -// -// PrivateDnsZone resource = resources.define(topLevelDomain) -// .withNewResourceGroup(groupName, region) -// .defineARecordSet("www") -// .withIPv4Address("23.96.104.40") -// .withIPv4Address("24.97.105.41") -// .withTimeToLive(7200) // Overwrite default 3600 seconds -// .attach() -// .defineAaaaRecordSet("www") -// .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") -// .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") -// .attach() -// .defineMxRecordSet("email") -// .withMailExchange("mail.contoso-mail-exchange1.com", 1) -// .withMailExchange("mail.contoso-mail-exchange2.com", 2) -// .withMetadata("mxa", "mxaa") -// .withMetadata("mxb", "mxbb") -// .attach() -// .defineTxtRecordSet("@") -// .withText("windows-apps-verification=2ZzjfideIJFLFje83") -// .attach() -// .defineTxtRecordSet("www") -// .withText("some info about www.contoso.com") -// .attach() -// .defineSrvRecordSet("_sip._tcp") -// .withRecord("bigbox.contoso-service.com", 5060, 10, 60) -// .withRecord("smallbox1.contoso-service.com", 5060, 10, 20) -// .withRecord("smallbox2.contoso-service.com", 5060, 10, 20) -// .withRecord("backupbox.contoso-service.com", 5060, 10, 0) -// .attach() -// .definePtrRecordSet("40") -// .withTargetDomainName("www.contoso.com") -// .withTargetDomainName("mail.contoso.com") -// .attach() -// .definePtrRecordSet("41") -// .withTargetDomainName("www.contoso.com") -// .withTargetDomainName("mail.contoso.com") -// .attach() -// .withCnameRecordSet("documents", "doc.contoso.com") -// .withCnameRecordSet("userguide", "doc.contoso.com") -// .withTag("a", "aa") -// .withTag("b", "bb") -// .create(); -// -// // Check Dns zone properties -// Assertions.assertTrue(resource.name().startsWith(topLevelDomain)); -// Assertions.assertTrue(resource.tags().size() == 2); -// -// // Check SOA record - external child resource (created by default) -// SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); -// Assertions.assertTrue(soaRecordSet.name().startsWith("@")); -// SoaRecord soaRecord = soaRecordSet.record(); -// Assertions.assertNotNull(soaRecord); -// -// // Check explicitly created external child resources [A, AAAA, MX, TXT, SRV, PTR, CNAME] -// // -// -// // Check A records -// PagedIterable aRecordSets = resource.aRecordSets().list(); -// Assertions.assertTrue(aRecordSets.stream().count() == 1); -// Assertions.assertTrue(aRecordSets.iterator().next().timeToLive() == 7200); -// -// // Check AAAA records -// PagedIterable aaaaRecordSets = resource.aaaaRecordSets().list(); -// Assertions.assertTrue(aaaaRecordSets.stream().count() == 1); -// Assertions.assertTrue(aaaaRecordSets.iterator().next().name().startsWith("www")); -// Assertions.assertTrue(aaaaRecordSets.iterator().next().ipv6Addresses().size() == 2); -// -// // Check MX records -// PagedIterable mxRecordSets = resource.mxRecordSets().list(); -// Assertions.assertTrue(mxRecordSets.stream().count() == 1); -// MxRecordSet mxRecordSet = mxRecordSets.iterator().next(); -// Assertions.assertNotNull(mxRecordSet); -// Assertions.assertTrue(mxRecordSet.name().startsWith("email")); -// Assertions.assertTrue(mxRecordSet.metadata().size() == 2); -// Assertions.assertTrue(mxRecordSet.records().size() == 2); -// for (MxRecord mxRecord : mxRecordSet.records()) { -// Assertions.assertTrue(mxRecord.exchange().startsWith("mail.contoso-mail-exchange1.com") -// || mxRecord.exchange().startsWith("mail.contoso-mail-exchange2.com")); -// Assertions.assertTrue(mxRecord.preference() == 1 -// || mxRecord.preference() == 2); -// } -// -// // Check TXT records -// PagedIterable txtRecordSets = resource.txtRecordSets().list(); -// Assertions.assertTrue(txtRecordSets.stream().count() == 2); -// -// // Check SRV records -// PagedIterable srvRecordSets = resource.srvRecordSets().list(); -// Assertions.assertTrue(srvRecordSets.stream().count() == 1); -// -// // Check PTR records -// PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); -// Assertions.assertTrue(ptrRecordSets.stream().count() == 2); -// -// // Check CNAME records -// PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); -// Assertions.assertTrue(cnameRecordSets.stream().count() == 2); -// -// // Check Generic record set listing -// PagedIterable recordSets = resource.listRecordSets(); -// HashMap typeToCount = new HashMap(); -// typeToCount.put(RecordType.A, 0); -// typeToCount.put(AAAA, 0); -// typeToCount.put(RecordType.CNAME, 0); -// typeToCount.put(MX, 0); -// typeToCount.put(PTR, 0); -// typeToCount.put(SOA, 0); -// typeToCount.put(SRV, 0); -// typeToCount.put(TXT, 0); -// for (PrivateDnsRecordSet recordSet : recordSets) { -// Assertions.assertNotNull(recordSet); -// switch (recordSet.recordType()) { -// case TXT: -// TxtRecordSet txtRS = (TxtRecordSet) recordSet; -// Assertions.assertNotNull(txtRS); -// typeToCount.put(TXT, typeToCount.get(TXT) + 1); -// break; -// case SRV: -// SrvRecordSet srvRS = (SrvRecordSet) recordSet; -// Assertions.assertNotNull(srvRS); -// typeToCount.put(SRV, typeToCount.get(SRV) + 1); -// break; -// case SOA: -// SoaRecordSet soaRS = (SoaRecordSet) recordSet; -// Assertions.assertNotNull(soaRS); -// typeToCount.put(SOA, typeToCount.get(SOA) + 1); -// break; -// case PTR: -// PtrRecordSet ptrRS = (PtrRecordSet) recordSet; -// Assertions.assertNotNull(ptrRS); -// typeToCount.put(PTR, typeToCount.get(PTR) + 1); -// break; -// case A: -// ARecordSet aRS = (ARecordSet) recordSet; -// Assertions.assertNotNull(aRS); -// typeToCount.put(RecordType.A, typeToCount.get(RecordType.A) + 1); -// break; -// case AAAA: -// AaaaRecordSet aaaaRS = (AaaaRecordSet) recordSet; -// Assertions.assertNotNull(aaaaRS); -// typeToCount.put(AAAA, typeToCount.get(AAAA) + 1); -// break; -// case CNAME: -// CnameRecordSet cnameRS = (CnameRecordSet) recordSet; -// Assertions.assertNotNull(cnameRS); -// typeToCount.put(RecordType.CNAME, typeToCount.get(RecordType.CNAME) + 1); -// break; -// case MX: -// MxRecordSet mxRS = (MxRecordSet) recordSet; -// Assertions.assertNotNull(mxRS); -// typeToCount.put(MX, typeToCount.get(MX) + 1); -// break; -// default: -// Assertions.assertNotNull(recordSet); -// } -// } -// Assertions.assertTrue(typeToCount.get(SOA) == 1); -// Assertions.assertTrue(typeToCount.get(RecordType.A) == 1); -// Assertions.assertTrue(typeToCount.get(AAAA) == 1); -// Assertions.assertTrue(typeToCount.get(MX) == 1); -// Assertions.assertTrue(typeToCount.get(TXT) == 2); -// Assertions.assertTrue(typeToCount.get(SRV) == 1); -// Assertions.assertTrue(typeToCount.get(PTR) == 2); -// Assertions.assertTrue(typeToCount.get(RecordType.CNAME) == 2); -// return resource; -// } -// -// @Override -// public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { -// resource.update() -// .withoutTxtRecordSet("www") -// .withoutCNameRecordSet("userguide") -// .withCnameRecordSet("help", "doc.contoso.com") -// .updateARecordSet("www") -// .withoutIPv4Address("23.96.104.40") -// .withIPv4Address("23.96.104.42") -// .parent() -// .updateSrvRecordSet("_sip._tcp") -// .withoutRecord("bigbox.contoso-service.com", 5060, 10, 60) -// .withRecord("mainbox.contoso-service.com", 5060, 10, 60) -// .parent() -// .updateSoaRecord() -// .withNegativeResponseCachingTimeToLiveInSeconds(600) -// .withTimeToLive(7200) -// .parent() -// .defineMxRecordSet("email-internal") -// .withMailExchange("mail.contoso-mail-exchange1.com", 1) -// .withMailExchange("mail.contoso-mail-exchange2.com", 2) -// .attach() -// .apply(); -// -// // Check TXT records -// PagedIterable txtRecordSets = resource.txtRecordSets().list(); -// Assertions.assertEquals(txtRecordSets.stream().count(), 1); -// -// // Check CNAME records -// PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); -// Assertions.assertEquals(cnameRecordSets.stream().count(), 2); -// for (CnameRecordSet cnameRecordSet : cnameRecordSets) { -// Assertions.assertTrue(cnameRecordSet.canonicalName().startsWith("doc.contoso.com")); -// Assertions.assertTrue(cnameRecordSet.name().startsWith("documents") -// || cnameRecordSet.name().startsWith("help")); -// } -// -// // Check A records -// PagedIterable aRecordSets = resource.aRecordSets().list(); -// Assertions.assertEquals(aRecordSets.stream().count(), 1); -// ARecordSet aRecordSet = aRecordSets.iterator().next(); -// Assertions.assertEquals(aRecordSet.ipv4Addresses().size(), 2); -// for (String ipV4Address : aRecordSet.ipv4Addresses()) { -// Assertions.assertFalse(ipV4Address.startsWith("23.96.104.40")); -// } -// -// // Check SRV records -// PagedIterable srvRecordSets = resource.srvRecordSets().list(); -// Assertions.assertTrue(srvRecordSets.stream().count() == 1); -// SrvRecordSet srvRecordSet = srvRecordSets.iterator().next(); -// Assertions.assertTrue(srvRecordSet.records().size() == 4); -// for (SrvRecord srvRecord : srvRecordSet.records()) { -// Assertions.assertFalse(srvRecord.target().startsWith("bigbox.contoso-service.com")); -// } -// -// // Check SOA Records -// SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); -// Assertions.assertTrue(soaRecordSet.name().startsWith("@")); -// SoaRecord soaRecord = soaRecordSet.record(); -// Assertions.assertNotNull(soaRecord); -// Assertions.assertEquals(soaRecord.minimumTtl(), Long.valueOf(600)); -// Assertions.assertTrue(soaRecordSet.timeToLive() == 7200); -// -// // Check MX records -// PagedIterable mxRecordSets = resource.mxRecordSets().list(); -// Assertions.assertTrue(mxRecordSets.stream().count() == 2); -// -// resource.update() -// .updateMxRecordSet("email") -// .withoutMailExchange("mail.contoso-mail-exchange2.com", 2) -// .withoutMetadata("mxa") -// .withMetadata("mxc", "mxcc") -// .withMetadata("mxd", "mxdd") -// .parent() -// .withTag("d", "dd") -// .apply(); -// -// Assertions.assertTrue(resource.tags().size() == 3); -// // Check "mail" MX record -// MxRecordSet mxRecordSet = resource.mxRecordSets().getByName("email"); -// Assertions.assertTrue(mxRecordSet.records().size() == 1); -// Assertions.assertTrue(mxRecordSet.metadata().size() == 3); -// Assertions.assertTrue(mxRecordSet.records().get(0).exchange().startsWith("mail.contoso-mail-exchange1.com")); -// -// return resource; -// } -// -// @Override -// public void print(PrivateDnsZone resource) { -// StringBuilder info = new StringBuilder(); -// info.append("Dns Zone: ").append(resource.id()) -// .append("\n\tName (Top level domain): ").append(resource.name()) -// .append("\n\tResource group: ").append(resource.resourceGroupName()) -// .append("\n\tRegion: ").append(resource.regionName()) -// .append("\n\tTags: ").append(resource.tags()); -// SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); -// 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 = resource.aRecordSets().list(); -// info.append("\n\tA Record sets:"); -// for (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 = resource.aaaaRecordSets().list(); -// info.append("\n\tAAAA Record sets:"); -// for (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 = resource.cnameRecordSets().list(); -// info.append("\n\tCNAME Record sets:"); -// 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()); -// } -// -// PagedIterable mxRecordSets = resource.mxRecordSets().list(); -// info.append("\n\tMX Record sets:"); -// 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()) -// .append("\n\t\tRecords: "); -// for (MxRecord mxRecord : mxRecordSet.records()) { -// info.append("\n\t\t\tExchange server, Preference: ") -// .append(mxRecord.exchange()) -// .append(" ") -// .append(mxRecord.preference()); -// } -// } -// -// PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); -// info.append("\n\tPTR Record sets:"); -// for (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 = resource.srvRecordSets().list(); -// info.append("\n\tSRV Record sets:"); -// for (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 (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 = resource.txtRecordSets().list(); -// info.append("\n\tTXT Record sets:"); -// for (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 (TxtRecord txtRecord : txtRecordSet.records()) { -// if (txtRecord.value().size() > 0) { -// info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); -// } -// } -// } -// System.out.println(info.toString()); -// } -//} +package com.azure.resourcemanager; + +import com.azure.core.http.rest.PagedIterable; +import com.azure.resourcemanager.privatedns.models.ARecordSet; +import com.azure.resourcemanager.privatedns.models.AaaaRecordSet; +import com.azure.resourcemanager.privatedns.models.CnameRecordSet; +import com.azure.resourcemanager.privatedns.models.MxRecord; +import com.azure.resourcemanager.privatedns.models.MxRecordSet; +import com.azure.resourcemanager.privatedns.models.PrivateDnsRecordSet; +import com.azure.resourcemanager.privatedns.models.PrivateDnsZone; +import com.azure.resourcemanager.privatedns.models.PrivateDnsZones; +import com.azure.resourcemanager.privatedns.models.PtrRecordSet; +import com.azure.resourcemanager.privatedns.models.RecordType; +import com.azure.resourcemanager.privatedns.models.SoaRecord; +import com.azure.resourcemanager.privatedns.models.SoaRecordSet; +import com.azure.resourcemanager.privatedns.models.SrvRecord; +import com.azure.resourcemanager.privatedns.models.SrvRecordSet; +import com.azure.resourcemanager.privatedns.models.TxtRecord; +import com.azure.resourcemanager.privatedns.models.TxtRecordSet; +import com.azure.core.management.Region; +import org.junit.jupiter.api.Assertions; + +import java.util.HashMap; + +import static com.azure.resourcemanager.privatedns.models.RecordType.AAAA; +import static com.azure.resourcemanager.privatedns.models.RecordType.MX; +import static com.azure.resourcemanager.privatedns.models.RecordType.PTR; +import static com.azure.resourcemanager.privatedns.models.RecordType.SOA; +import static com.azure.resourcemanager.privatedns.models.RecordType.SRV; +import static com.azure.resourcemanager.privatedns.models.RecordType.TXT; + +public class TestPrivateDns extends TestTemplate { + @Override + public PrivateDnsZone createResource(PrivateDnsZones resources) throws Exception { + final Region region = Region.US_EAST; + final String testId = resources.manager().resourceManager().internalContext().randomResourceName("", 8); + final String groupName = "rg" + testId; + final String topLevelDomain = "www.contoso" + testId + ".com"; + + PrivateDnsZone resource = resources.define(topLevelDomain) + .withNewResourceGroup(groupName, region) + .defineARecordSet("www") + .withIPv4Address("23.96.104.40") + .withIPv4Address("24.97.105.41") + .withTimeToLive(7200) // Overwrite default 3600 seconds + .attach() + .defineAaaaRecordSet("www") + .withIPv6Address("2001:0db8:85a3:0000:0000:8a2e:0370:7334") + .withIPv6Address("2002:0db9:85a4:0000:0000:8a2e:0371:7335") + .attach() + .defineMxRecordSet("email") + .withMailExchange("mail.contoso-mail-exchange1.com", 1) + .withMailExchange("mail.contoso-mail-exchange2.com", 2) + .withMetadata("mxa", "mxaa") + .withMetadata("mxb", "mxbb") + .attach() + .defineTxtRecordSet("@") + .withText("windows-apps-verification=2ZzjfideIJFLFje83") + .attach() + .defineTxtRecordSet("www") + .withText("some info about www.contoso.com") + .attach() + .defineSrvRecordSet("_sip._tcp") + .withRecord("bigbox.contoso-service.com", 5060, 10, 60) + .withRecord("smallbox1.contoso-service.com", 5060, 10, 20) + .withRecord("smallbox2.contoso-service.com", 5060, 10, 20) + .withRecord("backupbox.contoso-service.com", 5060, 10, 0) + .attach() + .definePtrRecordSet("40") + .withTargetDomainName("www.contoso.com") + .withTargetDomainName("mail.contoso.com") + .attach() + .definePtrRecordSet("41") + .withTargetDomainName("www.contoso.com") + .withTargetDomainName("mail.contoso.com") + .attach() + .withCnameRecordSet("documents", "doc.contoso.com") + .withCnameRecordSet("userguide", "doc.contoso.com") + .withTag("a", "aa") + .withTag("b", "bb") + .create(); + + // Check Dns zone properties + Assertions.assertTrue(resource.name().startsWith(topLevelDomain)); + Assertions.assertTrue(resource.tags().size() == 2); + + // Check SOA record - external child resource (created by default) + SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); + Assertions.assertTrue(soaRecordSet.name().startsWith("@")); + SoaRecord soaRecord = soaRecordSet.record(); + Assertions.assertNotNull(soaRecord); + + // Check explicitly created external child resources [A, AAAA, MX, TXT, SRV, PTR, CNAME] + // + + // Check A records + PagedIterable aRecordSets = resource.aRecordSets().list(); + Assertions.assertTrue(aRecordSets.stream().count() == 1); + Assertions.assertTrue(aRecordSets.iterator().next().timeToLive() == 7200); + + // Check AAAA records + PagedIterable aaaaRecordSets = resource.aaaaRecordSets().list(); + Assertions.assertTrue(aaaaRecordSets.stream().count() == 1); + Assertions.assertTrue(aaaaRecordSets.iterator().next().name().startsWith("www")); + Assertions.assertTrue(aaaaRecordSets.iterator().next().ipv6Addresses().size() == 2); + + // Check MX records + PagedIterable mxRecordSets = resource.mxRecordSets().list(); + Assertions.assertTrue(mxRecordSets.stream().count() == 1); + MxRecordSet mxRecordSet = mxRecordSets.iterator().next(); + Assertions.assertNotNull(mxRecordSet); + Assertions.assertTrue(mxRecordSet.name().startsWith("email")); + Assertions.assertTrue(mxRecordSet.metadata().size() == 2); + Assertions.assertTrue(mxRecordSet.records().size() == 2); + for (MxRecord mxRecord : mxRecordSet.records()) { + Assertions.assertTrue(mxRecord.exchange().startsWith("mail.contoso-mail-exchange1.com") + || mxRecord.exchange().startsWith("mail.contoso-mail-exchange2.com")); + Assertions.assertTrue(mxRecord.preference() == 1 + || mxRecord.preference() == 2); + } + + // Check TXT records + PagedIterable txtRecordSets = resource.txtRecordSets().list(); + Assertions.assertTrue(txtRecordSets.stream().count() == 2); + + // Check SRV records + PagedIterable srvRecordSets = resource.srvRecordSets().list(); + Assertions.assertTrue(srvRecordSets.stream().count() == 1); + + // Check PTR records + PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); + Assertions.assertTrue(ptrRecordSets.stream().count() == 2); + + // Check CNAME records + PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); + Assertions.assertTrue(cnameRecordSets.stream().count() == 2); + + // Check Generic record set listing + PagedIterable recordSets = resource.listRecordSets(); + HashMap typeToCount = new HashMap(); + typeToCount.put(RecordType.A, 0); + typeToCount.put(AAAA, 0); + typeToCount.put(RecordType.CNAME, 0); + typeToCount.put(MX, 0); + typeToCount.put(PTR, 0); + typeToCount.put(SOA, 0); + typeToCount.put(SRV, 0); + typeToCount.put(TXT, 0); + for (PrivateDnsRecordSet recordSet : recordSets) { + Assertions.assertNotNull(recordSet); + switch (recordSet.recordType()) { + case TXT: + TxtRecordSet txtRS = (TxtRecordSet) recordSet; + Assertions.assertNotNull(txtRS); + typeToCount.put(TXT, typeToCount.get(TXT) + 1); + break; + case SRV: + SrvRecordSet srvRS = (SrvRecordSet) recordSet; + Assertions.assertNotNull(srvRS); + typeToCount.put(SRV, typeToCount.get(SRV) + 1); + break; + case SOA: + SoaRecordSet soaRS = (SoaRecordSet) recordSet; + Assertions.assertNotNull(soaRS); + typeToCount.put(SOA, typeToCount.get(SOA) + 1); + break; + case PTR: + PtrRecordSet ptrRS = (PtrRecordSet) recordSet; + Assertions.assertNotNull(ptrRS); + typeToCount.put(PTR, typeToCount.get(PTR) + 1); + break; + case A: + ARecordSet aRS = (ARecordSet) recordSet; + Assertions.assertNotNull(aRS); + typeToCount.put(RecordType.A, typeToCount.get(RecordType.A) + 1); + break; + case AAAA: + AaaaRecordSet aaaaRS = (AaaaRecordSet) recordSet; + Assertions.assertNotNull(aaaaRS); + typeToCount.put(AAAA, typeToCount.get(AAAA) + 1); + break; + case CNAME: + CnameRecordSet cnameRS = (CnameRecordSet) recordSet; + Assertions.assertNotNull(cnameRS); + typeToCount.put(RecordType.CNAME, typeToCount.get(RecordType.CNAME) + 1); + break; + case MX: + MxRecordSet mxRS = (MxRecordSet) recordSet; + Assertions.assertNotNull(mxRS); + typeToCount.put(MX, typeToCount.get(MX) + 1); + break; + default: + Assertions.assertNotNull(recordSet); + } + } + Assertions.assertTrue(typeToCount.get(SOA) == 1); + Assertions.assertTrue(typeToCount.get(RecordType.A) == 1); + Assertions.assertTrue(typeToCount.get(AAAA) == 1); + Assertions.assertTrue(typeToCount.get(MX) == 1); + Assertions.assertTrue(typeToCount.get(TXT) == 2); + Assertions.assertTrue(typeToCount.get(SRV) == 1); + Assertions.assertTrue(typeToCount.get(PTR) == 2); + Assertions.assertTrue(typeToCount.get(RecordType.CNAME) == 2); + return resource; + } + + @Override + public PrivateDnsZone updateResource(PrivateDnsZone resource) throws Exception { + resource.update() + .withoutTxtRecordSet("www") + .withoutCNameRecordSet("userguide") + .withCnameRecordSet("help", "doc.contoso.com") + .updateARecordSet("www") + .withoutIPv4Address("23.96.104.40") + .withIPv4Address("23.96.104.42") + .parent() + .updateSrvRecordSet("_sip._tcp") + .withoutRecord("bigbox.contoso-service.com", 5060, 10, 60) + .withRecord("mainbox.contoso-service.com", 5060, 10, 60) + .parent() + .updateSoaRecord() + .withNegativeResponseCachingTimeToLiveInSeconds(600) + .withTimeToLive(7200) + .parent() + .defineMxRecordSet("email-internal") + .withMailExchange("mail.contoso-mail-exchange1.com", 1) + .withMailExchange("mail.contoso-mail-exchange2.com", 2) + .attach() + .apply(); + + // Check TXT records + PagedIterable txtRecordSets = resource.txtRecordSets().list(); + Assertions.assertEquals(txtRecordSets.stream().count(), 1); + + // Check CNAME records + PagedIterable cnameRecordSets = resource.cnameRecordSets().list(); + Assertions.assertEquals(cnameRecordSets.stream().count(), 2); + for (CnameRecordSet cnameRecordSet : cnameRecordSets) { + Assertions.assertTrue(cnameRecordSet.canonicalName().startsWith("doc.contoso.com")); + Assertions.assertTrue(cnameRecordSet.name().startsWith("documents") + || cnameRecordSet.name().startsWith("help")); + } + + // Check A records + PagedIterable aRecordSets = resource.aRecordSets().list(); + Assertions.assertEquals(aRecordSets.stream().count(), 1); + ARecordSet aRecordSet = aRecordSets.iterator().next(); + Assertions.assertEquals(aRecordSet.ipv4Addresses().size(), 2); + for (String ipV4Address : aRecordSet.ipv4Addresses()) { + Assertions.assertFalse(ipV4Address.startsWith("23.96.104.40")); + } + + // Check SRV records + PagedIterable srvRecordSets = resource.srvRecordSets().list(); + Assertions.assertTrue(srvRecordSets.stream().count() == 1); + SrvRecordSet srvRecordSet = srvRecordSets.iterator().next(); + Assertions.assertTrue(srvRecordSet.records().size() == 4); + for (SrvRecord srvRecord : srvRecordSet.records()) { + Assertions.assertFalse(srvRecord.target().startsWith("bigbox.contoso-service.com")); + } + + // Check SOA Records + SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); + Assertions.assertTrue(soaRecordSet.name().startsWith("@")); + SoaRecord soaRecord = soaRecordSet.record(); + Assertions.assertNotNull(soaRecord); + Assertions.assertEquals(soaRecord.minimumTtl(), Long.valueOf(600)); + Assertions.assertTrue(soaRecordSet.timeToLive() == 7200); + + // Check MX records + PagedIterable mxRecordSets = resource.mxRecordSets().list(); + Assertions.assertTrue(mxRecordSets.stream().count() == 2); + + resource.update() + .updateMxRecordSet("email") + .withoutMailExchange("mail.contoso-mail-exchange2.com", 2) + .withoutMetadata("mxa") + .withMetadata("mxc", "mxcc") + .withMetadata("mxd", "mxdd") + .parent() + .withTag("d", "dd") + .apply(); + + Assertions.assertTrue(resource.tags().size() == 3); + // Check "mail" MX record + MxRecordSet mxRecordSet = resource.mxRecordSets().getByName("email"); + Assertions.assertTrue(mxRecordSet.records().size() == 1); + Assertions.assertTrue(mxRecordSet.metadata().size() == 3); + Assertions.assertTrue(mxRecordSet.records().get(0).exchange().startsWith("mail.contoso-mail-exchange1.com")); + + return resource; + } + + @Override + public void print(PrivateDnsZone resource) { + StringBuilder info = new StringBuilder(); + info.append("Dns Zone: ").append(resource.id()) + .append("\n\tName (Top level domain): ").append(resource.name()) + .append("\n\tResource group: ").append(resource.resourceGroupName()) + .append("\n\tRegion: ").append(resource.regionName()) + .append("\n\tTags: ").append(resource.tags()); + SoaRecordSet soaRecordSet = resource.getSoaRecordSet(); + 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 = resource.aRecordSets().list(); + info.append("\n\tA Record sets:"); + for (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 = resource.aaaaRecordSets().list(); + info.append("\n\tAAAA Record sets:"); + for (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 = resource.cnameRecordSets().list(); + info.append("\n\tCNAME Record sets:"); + 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()); + } + + PagedIterable mxRecordSets = resource.mxRecordSets().list(); + info.append("\n\tMX Record sets:"); + 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()) + .append("\n\t\tRecords: "); + for (MxRecord mxRecord : mxRecordSet.records()) { + info.append("\n\t\t\tExchange server, Preference: ") + .append(mxRecord.exchange()) + .append(" ") + .append(mxRecord.preference()); + } + } + + PagedIterable ptrRecordSets = resource.ptrRecordSets().list(); + info.append("\n\tPTR Record sets:"); + for (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 = resource.srvRecordSets().list(); + info.append("\n\tSRV Record sets:"); + for (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 (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 = resource.txtRecordSets().list(); + info.append("\n\tTXT Record sets:"); + for (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 (TxtRecord txtRecord : txtRecordSet.records()) { + if (txtRecord.value().size() > 0) { + info.append("\n\t\t\tValue: ").append(txtRecord.value().get(0)); + } + } + } + System.out.println(info.toString()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java index da502a1e267b..06afd627b6a9 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestRedis.java @@ -1,51 +1,51 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -// -//package com.azure.resourcemanager; -// -//import com.azure.resourcemanager.redis.models.RedisCache; -//import com.azure.resourcemanager.redis.models.RedisCaches; -//import com.azure.core.management.Region; -//import com.google.common.util.concurrent.SettableFuture; -//import org.junit.jupiter.api.Assertions; -//import reactor.core.publisher.Mono; -// -//public class TestRedis extends TestTemplate { -// @Override -// public RedisCache createResource(RedisCaches resources) throws Exception { -// final String redisName = resources.manager().resourceManager().internalContext().randomResourceName("redis", 10); -// final RedisCache[] redisCaches = new RedisCache[1]; -// final SettableFuture future = SettableFuture.create(); -// -// Mono resourceStream = -// resources -// .define(redisName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup() -// .withStandardSku() -// .withTag("mytag", "testtag") -// .createAsync(); -// -// resourceStream.subscribe(future::set); -// -// redisCaches[0] = future.get(); -// -// Assertions.assertEquals(redisCaches[0].name(), redisName); -// -// return redisCaches[0]; -// } -// -// @Override -// public RedisCache updateResource(RedisCache resource) throws Exception { -// resource = resource.update().withPremiumSku(2).apply(); -// -// Assertions.assertTrue(resource.isPremium()); -// -// return resource; -// } -// -// @Override -// public void print(RedisCache resource) { -// System.out.println("Redis Cache: " + resource.id() + ", Name: " + resource.name()); -// } -//} + +package com.azure.resourcemanager; + +import com.azure.resourcemanager.redis.models.RedisCache; +import com.azure.resourcemanager.redis.models.RedisCaches; +import com.azure.core.management.Region; +import com.google.common.util.concurrent.SettableFuture; +import org.junit.jupiter.api.Assertions; +import reactor.core.publisher.Mono; + +public class TestRedis extends TestTemplate { + @Override + public RedisCache createResource(RedisCaches resources) throws Exception { + final String redisName = resources.manager().resourceManager().internalContext().randomResourceName("redis", 10); + final RedisCache[] redisCaches = new RedisCache[1]; + final SettableFuture future = SettableFuture.create(); + + Mono resourceStream = + resources + .define(redisName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withStandardSku() + .withTag("mytag", "testtag") + .createAsync(); + + resourceStream.subscribe(future::set); + + redisCaches[0] = future.get(); + + Assertions.assertEquals(redisCaches[0].name(), redisName); + + return redisCaches[0]; + } + + @Override + public RedisCache updateResource(RedisCache resource) throws Exception { + resource = resource.update().withPremiumSku(2).apply(); + + Assertions.assertTrue(resource.isPremium()); + + return resource; + } + + @Override + public void print(RedisCache resource) { + System.out.println("Redis Cache: " + resource.id() + ", Name: " + resource.name()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java index 588beca79aa2..42e663849d92 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestSql.java @@ -1,93 +1,93 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager; -// -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.sql.models.SqlServer; -//import com.azure.resourcemanager.sql.models.SqlServers; -//import com.google.common.util.concurrent.SettableFuture; -//import org.junit.jupiter.api.Assertions; -//import reactor.core.publisher.Mono; -// -//public class TestSql extends TestTemplate { -// @Override -// public SqlServer createResource(SqlServers resources) throws Exception { -// final String sqlServerName = resources.manager().resourceManager().internalContext().randomResourceName("sql", 10); -// final SqlServer[] sqlServers = new SqlServer[1]; -// final SettableFuture future = SettableFuture.create(); -// Mono resourceStream = -// resources -// .define(sqlServerName) -// .withRegion(Region.US_EAST) -// .withNewResourceGroup() -// .withAdministratorLogin("admin32") -// .withAdministratorPassword("Password~1") -// .defineDatabase("database1").attach() -// .defineElasticPool("elasticPool1").withStandardPool().attach() -// .defineDatabase("databaseInEP").withExistingElasticPool("elasticPool1").attach() -// .defineFirewallRule("firewallRule1").withIpAddress("10.10.10.10").attach() -// .withTag("mytag", "testtag") -// .createAsync(); -// -// resourceStream.subscribe(sqlServer -> future.set(sqlServer), error -> future.set(null)); -// -// sqlServers[0] = future.get(); -// -// Assertions.assertNotNull(sqlServers[0].innerModel()); -// -// Assertions.assertNotNull(sqlServers[0].innerModel()); -// // Including master database -// Assertions.assertEquals(sqlServers[0].databases().list().size(), 3); -// Assertions.assertEquals(sqlServers[0].elasticPools().list().size(), 1); -// Assertions.assertEquals(sqlServers[0].firewallRules().list().size(), 2); -// -// return sqlServers[0]; -// } -// -// @Override -// public SqlServer updateResource(SqlServer sqlServer) throws Exception { -// sqlServer = -// sqlServer -// .update() -// .withoutDatabase("database1") -// .withoutDatabase("databaseInEP") -// .withoutElasticPool("elasticPool1") -// .apply(); -// -// Assertions.assertNotNull(sqlServer.innerModel()); -// // Just master database -// Assertions.assertEquals(1, sqlServer.databases().list().size()); -// Assertions.assertEquals(0, sqlServer.elasticPools().list().size()); -// Assertions.assertEquals(2, sqlServer.firewallRules().list().size()); -// -// return sqlServer; -// } -// -// @Override -// public void print(SqlServer sqlServer) { -// System -// .out -// .println( -// new StringBuilder() -// .append("SqlServer : ") -// .append(sqlServer.id()) -// .append(", Name: ") -// .append(sqlServer.name()) -// .toString()); -// System -// .out -// .println( -// new StringBuilder() -// .append("Number of databases : ") -// .append(sqlServer.databases().list().size()) -// .toString()); -// System -// .out -// .println( -// new StringBuilder() -// .append("Number of elastic pools : ") -// .append(sqlServer.elasticPools().list().size()) -// .toString()); -// } -//} +package com.azure.resourcemanager; + +import com.azure.core.management.Region; +import com.azure.resourcemanager.sql.models.SqlServer; +import com.azure.resourcemanager.sql.models.SqlServers; +import com.google.common.util.concurrent.SettableFuture; +import org.junit.jupiter.api.Assertions; +import reactor.core.publisher.Mono; + +public class TestSql extends TestTemplate { + @Override + public SqlServer createResource(SqlServers resources) throws Exception { + final String sqlServerName = resources.manager().resourceManager().internalContext().randomResourceName("sql", 10); + final SqlServer[] sqlServers = new SqlServer[1]; + final SettableFuture future = SettableFuture.create(); + Mono resourceStream = + resources + .define(sqlServerName) + .withRegion(Region.US_EAST) + .withNewResourceGroup() + .withAdministratorLogin("admin32") + .withAdministratorPassword("Password~1") + .defineDatabase("database1").attach() + .defineElasticPool("elasticPool1").withStandardPool().attach() + .defineDatabase("databaseInEP").withExistingElasticPool("elasticPool1").attach() + .defineFirewallRule("firewallRule1").withIpAddress("10.10.10.10").attach() + .withTag("mytag", "testtag") + .createAsync(); + + resourceStream.subscribe(sqlServer -> future.set(sqlServer), error -> future.set(null)); + + sqlServers[0] = future.get(); + + Assertions.assertNotNull(sqlServers[0].innerModel()); + + Assertions.assertNotNull(sqlServers[0].innerModel()); + // Including master database + Assertions.assertEquals(sqlServers[0].databases().list().size(), 3); + Assertions.assertEquals(sqlServers[0].elasticPools().list().size(), 1); + Assertions.assertEquals(sqlServers[0].firewallRules().list().size(), 2); + + return sqlServers[0]; + } + + @Override + public SqlServer updateResource(SqlServer sqlServer) throws Exception { + sqlServer = + sqlServer + .update() + .withoutDatabase("database1") + .withoutDatabase("databaseInEP") + .withoutElasticPool("elasticPool1") + .apply(); + + Assertions.assertNotNull(sqlServer.innerModel()); + // Just master database + Assertions.assertEquals(1, sqlServer.databases().list().size()); + Assertions.assertEquals(0, sqlServer.elasticPools().list().size()); + Assertions.assertEquals(2, sqlServer.firewallRules().list().size()); + + return sqlServer; + } + + @Override + public void print(SqlServer sqlServer) { + System + .out + .println( + new StringBuilder() + .append("SqlServer : ") + .append(sqlServer.id()) + .append(", Name: ") + .append(sqlServer.name()) + .toString()); + System + .out + .println( + new StringBuilder() + .append("Number of databases : ") + .append(sqlServer.databases().list().size()) + .toString()); + System + .out + .println( + new StringBuilder() + .append("Number of elastic pools : ") + .append(sqlServer.elasticPools().list().size()) + .toString()); + } +} diff --git a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java index fdf62b3c0de1..f0d9816d8828 100644 --- a/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager/src/test/java/com/azure/resourcemanager/TestTrafficManager.java @@ -1,410 +1,410 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. -//package com.azure.resourcemanager; -// -//import com.azure.resourcemanager.network.models.PublicIpAddress; -//import com.azure.resourcemanager.network.models.PublicIpAddresses; -//import com.azure.core.management.Region; -//import com.azure.resourcemanager.resources.models.ResourceGroup; -//import com.azure.resourcemanager.trafficmanager.models.EndpointType; -//import com.azure.resourcemanager.trafficmanager.models.TargetAzureResourceType; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerAzureEndpoint; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerExternalEndpoint; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; -//import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfiles; -//import java.util.Map; -//import org.junit.jupiter.api.Assertions; -// -///** Test of traffic manager management. */ -//public class TestTrafficManager extends TestTemplate { -// -// private final PublicIpAddresses publicIpAddresses; -// -// private final String externalEndpointName21 = "external-ep-1"; -// private final String externalEndpointName22 = "external-ep-2"; -// private final String externalEndpointName23 = "external-ep-3"; -// -// private final String externalFqdn21 = "www.azure.com"; -// private final String externalFqdn22 = "www.bing.com"; -// private final String externalFqdn23 = "www.github.com"; -// -// private final String azureEndpointName = "azure-ep-1"; -// private final String nestedProfileEndpointName = "nested-profile-ep-1"; -// -// public TestTrafficManager(PublicIpAddresses publicIpAddresses) { -// this.publicIpAddresses = publicIpAddresses; -// } -// -// @Override -// public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) throws Exception { -// final Region region = Region.US_EAST; -// final String groupName = profiles.manager().resourceManager().internalContext().randomResourceName("rg", 10); -// -// final String pipName = profiles.manager().resourceManager().internalContext().randomResourceName("pip", 10); -// final String pipDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("contoso", 15); -// -// final String tmProfileName = profiles.manager().resourceManager().internalContext().randomResourceName("tm", 10); -// final String nestedTmProfileName = "nested" + tmProfileName; -// -// final String tmProfileDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("tmdns", 10); -// final String nestedTmProfileDnsLabel = "nested" + tmProfileDnsLabel; -// -// ResourceGroup.DefinitionStages.WithCreate rgCreatable = -// profiles.manager().resourceManager().resourceGroups().define(groupName).withRegion(region); -// -// // Creates a TM profile that will be used as a nested profile endpoint in parent TM profile -// // -// TrafficManagerProfile nestedProfile = -// profiles -// .define(nestedTmProfileName) -// .withNewResourceGroup(rgCreatable) -// .withLeafDomainLabel(nestedTmProfileDnsLabel) -// .withPriorityBasedRouting() -// .defineExternalTargetEndpoint(externalEndpointName21) -// .toFqdn("www.gitbook.com") -// .fromRegion(Region.INDIA_CENTRAL) -// .attach() -// .withHttpsMonitoring() -// .withTimeToLive(500) -// .create(); -// -// Assertions.assertTrue(nestedProfile.isEnabled()); -// Assertions.assertNotNull(nestedProfile.monitorStatus()); -// Assertions.assertEquals(nestedProfile.monitoringPort(), 443); -// Assertions.assertEquals(nestedProfile.monitoringPath(), "/"); -// Assertions.assertEquals(nestedProfile.azureEndpoints().size(), 0); -// Assertions.assertEquals(nestedProfile.nestedProfileEndpoints().size(), 0); -// Assertions.assertEquals(nestedProfile.externalEndpoints().size(), 1); -// Assertions.assertEquals(nestedProfile.fqdn(), nestedTmProfileDnsLabel + ".trafficmanager.net"); -// Assertions.assertEquals(nestedProfile.timeToLive(), 500); -// -// // Creates a public ip to be used as an Azure endpoint -// // -// PublicIpAddress publicIPAddress = -// this -// .publicIpAddresses -// .define(pipName) -// .withRegion(region) -// .withNewResourceGroup(rgCreatable) -// .withLeafDomainLabel(pipDnsLabel) -// .create(); -// -// Assertions.assertNotNull(publicIPAddress.fqdn()); -// // Creates a TM profile -// // -// -// // bugfix -// TrafficManagerProfile updatedProfile = -// nestedProfile -// .update() -// .defineAzureTargetEndpoint(azureEndpointName) -// .toResourceId(publicIPAddress.id()) -// .withTrafficDisabled() -// .withRoutingPriority(11) -// .attach() -// .apply(); -// -// Assertions.assertEquals(1, updatedProfile.azureEndpoints().size()); -// Assertions.assertTrue(updatedProfile.azureEndpoints().containsKey(azureEndpointName)); -// Assertions.assertEquals(1, updatedProfile.externalEndpoints().size()); -// Assertions.assertTrue(updatedProfile.externalEndpoints().containsKey(externalEndpointName21)); -// -// TrafficManagerProfile updatedProfileFromGet = profiles.getById(updatedProfile.id()); -// -// Assertions.assertEquals(1, updatedProfileFromGet.azureEndpoints().size()); -// Assertions.assertTrue(updatedProfileFromGet.azureEndpoints().containsKey(azureEndpointName)); -// Assertions.assertEquals(1, updatedProfileFromGet.externalEndpoints().size()); -// Assertions.assertTrue(updatedProfileFromGet.externalEndpoints().containsKey(externalEndpointName21)); -// -// nestedProfile.update().withoutEndpoint(azureEndpointName).apply(); -// -// Assertions.assertEquals(0, nestedProfile.azureEndpoints().size()); -// Assertions.assertEquals(1, nestedProfile.externalEndpoints().size()); -// Assertions.assertTrue(nestedProfile.externalEndpoints().containsKey(externalEndpointName21)); -// -// updatedProfileFromGet = profiles.getById(updatedProfile.id()); -// Assertions.assertEquals(0, updatedProfileFromGet.azureEndpoints().size()); -// Assertions.assertEquals(nestedProfile.azureEndpoints().size(), updatedProfileFromGet.azureEndpoints().size()); -// Assertions.assertEquals(1, updatedProfileFromGet.externalEndpoints().size()); -// Assertions.assertTrue(updatedProfileFromGet.externalEndpoints().containsKey(externalEndpointName21)); -// // end of bugfix -// -// TrafficManagerProfile profile = -// profiles -// .define(tmProfileName) -// .withNewResourceGroup(rgCreatable) -// .withLeafDomainLabel(tmProfileDnsLabel) -// .withWeightBasedRouting() -// .defineExternalTargetEndpoint(externalEndpointName21) -// .toFqdn(externalFqdn21) -// .fromRegion(Region.US_EAST) -// .withRoutingPriority(1) -// .withRoutingWeight(1) -// .attach() -// .defineExternalTargetEndpoint(externalEndpointName22) -// .toFqdn(externalFqdn22) -// .fromRegion(Region.US_EAST2) -// .withRoutingPriority(2) -// .withRoutingWeight(1) -// .withTrafficDisabled() -// .attach() -// .defineAzureTargetEndpoint(azureEndpointName) -// .toResourceId(publicIPAddress.id()) -// .withRoutingPriority(3) -// .attach() -// .defineNestedTargetEndpoint(nestedProfileEndpointName) -// .toProfile(nestedProfile) -// .fromRegion(Region.INDIA_CENTRAL) -// .withMinimumEndpointsToEnableTraffic(1) -// .withRoutingPriority(4) -// .attach() -// .withHttpMonitoring() -// .create(); -// -// Assertions.assertTrue(profile.isEnabled()); -// Assertions.assertNotNull(profile.monitorStatus()); -// Assertions.assertEquals(profile.monitoringPort(), 80); -// Assertions.assertEquals(profile.monitoringPath(), "/"); -// Assertions.assertEquals(profile.azureEndpoints().size(), 1); -// Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); -// Assertions.assertEquals(profile.externalEndpoints().size(), 2); -// Assertions.assertEquals(profile.fqdn(), tmProfileDnsLabel + ".trafficmanager.net"); -// Assertions.assertEquals(profile.timeToLive(), 300); // Default -// -// profile = profile.refresh(); -// Assertions.assertEquals(profile.azureEndpoints().size(), 1); -// Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); -// Assertions.assertEquals(profile.externalEndpoints().size(), 2); -// -// int c = 0; -// for (TrafficManagerExternalEndpoint endpoint : profile.externalEndpoints().values()) { -// Assertions.assertEquals(endpoint.endpointType(), EndpointType.EXTERNAL); -// if (endpoint.name().equalsIgnoreCase(externalEndpointName21)) { -// Assertions.assertEquals(endpoint.routingPriority(), 1); -// Assertions.assertEquals(endpoint.fqdn(), externalFqdn21); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST); -// c++; -// } else if (endpoint.name().equalsIgnoreCase(externalEndpointName22)) { -// Assertions.assertEquals(endpoint.routingPriority(), 2); -// Assertions.assertEquals(endpoint.fqdn(), externalFqdn22); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST2); -// c++; -// } -// } -// Assertions.assertEquals(c, 2); -// -// c = 0; -// for (TrafficManagerAzureEndpoint endpoint : profile.azureEndpoints().values()) { -// Assertions.assertEquals(endpoint.endpointType(), EndpointType.AZURE); -// if (endpoint.name().equalsIgnoreCase(azureEndpointName)) { -// Assertions.assertEquals(endpoint.routingPriority(), 3); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// Assertions.assertEquals(endpoint.targetAzureResourceId(), publicIPAddress.id()); -// Assertions.assertEquals(endpoint.targetResourceType(), TargetAzureResourceType.PUBLICIP); -// c++; -// } -// } -// Assertions.assertEquals(c, 1); -// -// c = 0; -// for (TrafficManagerNestedProfileEndpoint endpoint : profile.nestedProfileEndpoints().values()) { -// Assertions.assertEquals(endpoint.endpointType(), EndpointType.NESTED_PROFILE); -// if (endpoint.name().equalsIgnoreCase(nestedProfileEndpointName)) { -// Assertions.assertEquals(endpoint.routingPriority(), 4); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// Assertions.assertEquals(endpoint.minimumChildEndpointCount(), 1); -// Assertions.assertEquals(endpoint.nestedProfileId(), nestedProfile.id()); -// Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.INDIA_CENTRAL); -// c++; -// } -// } -// Assertions.assertEquals(c, 1); -// return profile; -// } -// -// @Override -// public TrafficManagerProfile updateResource(TrafficManagerProfile profile) throws Exception { -// // Remove an endpoint, update two endpoints and add new one -// // -// profile -// .update() -// .withTimeToLive(600) -// .withHttpMonitoring(8080, "/") -// .withPerformanceBasedRouting() -// .withoutEndpoint(externalEndpointName21) -// .updateAzureTargetEndpoint(azureEndpointName) -// .withRoutingPriority(5) -// .withRoutingWeight(2) -// .parent() -// .updateNestedProfileTargetEndpoint(nestedProfileEndpointName) -// .withTrafficDisabled() -// .parent() -// .defineExternalTargetEndpoint(externalEndpointName23) -// .toFqdn(externalFqdn23) -// .fromRegion(Region.US_CENTRAL) -// .withRoutingPriority(6) -// .attach() -// .apply(); -// -// Assertions.assertEquals(profile.monitoringPort(), 8080); -// Assertions.assertEquals(profile.monitoringPath(), "/"); -// Assertions.assertEquals(profile.azureEndpoints().size(), 1); -// Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); -// Assertions.assertEquals(profile.externalEndpoints().size(), 2); -// Assertions.assertEquals(profile.timeToLive(), 600); -// -// int c = 0; -// for (TrafficManagerExternalEndpoint endpoint : profile.externalEndpoints().values()) { -// Assertions.assertEquals(endpoint.endpointType(), EndpointType.EXTERNAL); -// if (endpoint.name().equalsIgnoreCase(externalEndpointName22)) { -// Assertions.assertEquals(endpoint.routingPriority(), 2); -// Assertions.assertEquals(endpoint.fqdn(), externalFqdn22); -// Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST2); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// c++; -// } else if (endpoint.name().equalsIgnoreCase(externalEndpointName23)) { -// Assertions.assertEquals(endpoint.routingPriority(), 6); -// Assertions.assertEquals(endpoint.fqdn(), externalFqdn23); -// Assertions.assertNotNull(endpoint.monitorStatus()); -// Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_CENTRAL); -// c++; -// } else { -// c++; -// } -// } -// Assertions.assertEquals(c, 2); -// -// c = 0; -// for (TrafficManagerAzureEndpoint endpoint : profile.azureEndpoints().values()) { -// Assertions.assertEquals(endpoint.endpointType(), EndpointType.AZURE); -// if (endpoint.name().equalsIgnoreCase(azureEndpointName)) { -// Assertions.assertEquals(endpoint.routingPriority(), 5); -// Assertions.assertEquals(endpoint.routingWeight(), 2); -// Assertions.assertEquals(endpoint.targetResourceType(), TargetAzureResourceType.PUBLICIP); -// c++; -// } -// } -// Assertions.assertEquals(c, 1); -// return profile; -// } -// -// @Override -// public 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()); -// } -//} +package com.azure.resourcemanager; + +import com.azure.resourcemanager.network.models.PublicIpAddress; +import com.azure.resourcemanager.network.models.PublicIpAddresses; +import com.azure.core.management.Region; +import com.azure.resourcemanager.resources.models.ResourceGroup; +import com.azure.resourcemanager.trafficmanager.models.EndpointType; +import com.azure.resourcemanager.trafficmanager.models.TargetAzureResourceType; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerAzureEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerExternalEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerNestedProfileEndpoint; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfile; +import com.azure.resourcemanager.trafficmanager.models.TrafficManagerProfiles; +import java.util.Map; +import org.junit.jupiter.api.Assertions; + +/** Test of traffic manager management. */ +public class TestTrafficManager extends TestTemplate { + + private final PublicIpAddresses publicIpAddresses; + + private final String externalEndpointName21 = "external-ep-1"; + private final String externalEndpointName22 = "external-ep-2"; + private final String externalEndpointName23 = "external-ep-3"; + + private final String externalFqdn21 = "www.azure.com"; + private final String externalFqdn22 = "www.bing.com"; + private final String externalFqdn23 = "www.github.com"; + + private final String azureEndpointName = "azure-ep-1"; + private final String nestedProfileEndpointName = "nested-profile-ep-1"; + + public TestTrafficManager(PublicIpAddresses publicIpAddresses) { + this.publicIpAddresses = publicIpAddresses; + } + + @Override + public TrafficManagerProfile createResource(TrafficManagerProfiles profiles) throws Exception { + final Region region = Region.US_EAST; + final String groupName = profiles.manager().resourceManager().internalContext().randomResourceName("rg", 10); + + final String pipName = profiles.manager().resourceManager().internalContext().randomResourceName("pip", 10); + final String pipDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("contoso", 15); + + final String tmProfileName = profiles.manager().resourceManager().internalContext().randomResourceName("tm", 10); + final String nestedTmProfileName = "nested" + tmProfileName; + + final String tmProfileDnsLabel = profiles.manager().resourceManager().internalContext().randomResourceName("tmdns", 10); + final String nestedTmProfileDnsLabel = "nested" + tmProfileDnsLabel; + + ResourceGroup.DefinitionStages.WithCreate rgCreatable = + profiles.manager().resourceManager().resourceGroups().define(groupName).withRegion(region); + + // Creates a TM profile that will be used as a nested profile endpoint in parent TM profile + // + TrafficManagerProfile nestedProfile = + profiles + .define(nestedTmProfileName) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(nestedTmProfileDnsLabel) + .withPriorityBasedRouting() + .defineExternalTargetEndpoint(externalEndpointName21) + .toFqdn("www.gitbook.com") + .fromRegion(Region.INDIA_CENTRAL) + .attach() + .withHttpsMonitoring() + .withTimeToLive(500) + .create(); + + Assertions.assertTrue(nestedProfile.isEnabled()); + Assertions.assertNotNull(nestedProfile.monitorStatus()); + Assertions.assertEquals(nestedProfile.monitoringPort(), 443); + Assertions.assertEquals(nestedProfile.monitoringPath(), "/"); + Assertions.assertEquals(nestedProfile.azureEndpoints().size(), 0); + Assertions.assertEquals(nestedProfile.nestedProfileEndpoints().size(), 0); + Assertions.assertEquals(nestedProfile.externalEndpoints().size(), 1); + Assertions.assertEquals(nestedProfile.fqdn(), nestedTmProfileDnsLabel + ".trafficmanager.net"); + Assertions.assertEquals(nestedProfile.timeToLive(), 500); + + // Creates a public ip to be used as an Azure endpoint + // + PublicIpAddress publicIPAddress = + this + .publicIpAddresses + .define(pipName) + .withRegion(region) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(pipDnsLabel) + .create(); + + Assertions.assertNotNull(publicIPAddress.fqdn()); + // Creates a TM profile + // + + // bugfix + TrafficManagerProfile updatedProfile = + nestedProfile + .update() + .defineAzureTargetEndpoint(azureEndpointName) + .toResourceId(publicIPAddress.id()) + .withTrafficDisabled() + .withRoutingPriority(11) + .attach() + .apply(); + + Assertions.assertEquals(1, updatedProfile.azureEndpoints().size()); + Assertions.assertTrue(updatedProfile.azureEndpoints().containsKey(azureEndpointName)); + Assertions.assertEquals(1, updatedProfile.externalEndpoints().size()); + Assertions.assertTrue(updatedProfile.externalEndpoints().containsKey(externalEndpointName21)); + + TrafficManagerProfile updatedProfileFromGet = profiles.getById(updatedProfile.id()); + + Assertions.assertEquals(1, updatedProfileFromGet.azureEndpoints().size()); + Assertions.assertTrue(updatedProfileFromGet.azureEndpoints().containsKey(azureEndpointName)); + Assertions.assertEquals(1, updatedProfileFromGet.externalEndpoints().size()); + Assertions.assertTrue(updatedProfileFromGet.externalEndpoints().containsKey(externalEndpointName21)); + + nestedProfile.update().withoutEndpoint(azureEndpointName).apply(); + + Assertions.assertEquals(0, nestedProfile.azureEndpoints().size()); + Assertions.assertEquals(1, nestedProfile.externalEndpoints().size()); + Assertions.assertTrue(nestedProfile.externalEndpoints().containsKey(externalEndpointName21)); + + updatedProfileFromGet = profiles.getById(updatedProfile.id()); + Assertions.assertEquals(0, updatedProfileFromGet.azureEndpoints().size()); + Assertions.assertEquals(nestedProfile.azureEndpoints().size(), updatedProfileFromGet.azureEndpoints().size()); + Assertions.assertEquals(1, updatedProfileFromGet.externalEndpoints().size()); + Assertions.assertTrue(updatedProfileFromGet.externalEndpoints().containsKey(externalEndpointName21)); + // end of bugfix + + TrafficManagerProfile profile = + profiles + .define(tmProfileName) + .withNewResourceGroup(rgCreatable) + .withLeafDomainLabel(tmProfileDnsLabel) + .withWeightBasedRouting() + .defineExternalTargetEndpoint(externalEndpointName21) + .toFqdn(externalFqdn21) + .fromRegion(Region.US_EAST) + .withRoutingPriority(1) + .withRoutingWeight(1) + .attach() + .defineExternalTargetEndpoint(externalEndpointName22) + .toFqdn(externalFqdn22) + .fromRegion(Region.US_EAST2) + .withRoutingPriority(2) + .withRoutingWeight(1) + .withTrafficDisabled() + .attach() + .defineAzureTargetEndpoint(azureEndpointName) + .toResourceId(publicIPAddress.id()) + .withRoutingPriority(3) + .attach() + .defineNestedTargetEndpoint(nestedProfileEndpointName) + .toProfile(nestedProfile) + .fromRegion(Region.INDIA_CENTRAL) + .withMinimumEndpointsToEnableTraffic(1) + .withRoutingPriority(4) + .attach() + .withHttpMonitoring() + .create(); + + Assertions.assertTrue(profile.isEnabled()); + Assertions.assertNotNull(profile.monitorStatus()); + Assertions.assertEquals(profile.monitoringPort(), 80); + Assertions.assertEquals(profile.monitoringPath(), "/"); + Assertions.assertEquals(profile.azureEndpoints().size(), 1); + Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); + Assertions.assertEquals(profile.externalEndpoints().size(), 2); + Assertions.assertEquals(profile.fqdn(), tmProfileDnsLabel + ".trafficmanager.net"); + Assertions.assertEquals(profile.timeToLive(), 300); // Default + + profile = profile.refresh(); + Assertions.assertEquals(profile.azureEndpoints().size(), 1); + Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); + Assertions.assertEquals(profile.externalEndpoints().size(), 2); + + int c = 0; + for (TrafficManagerExternalEndpoint endpoint : profile.externalEndpoints().values()) { + Assertions.assertEquals(endpoint.endpointType(), EndpointType.EXTERNAL); + if (endpoint.name().equalsIgnoreCase(externalEndpointName21)) { + Assertions.assertEquals(endpoint.routingPriority(), 1); + Assertions.assertEquals(endpoint.fqdn(), externalFqdn21); + Assertions.assertNotNull(endpoint.monitorStatus()); + Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST); + c++; + } else if (endpoint.name().equalsIgnoreCase(externalEndpointName22)) { + Assertions.assertEquals(endpoint.routingPriority(), 2); + Assertions.assertEquals(endpoint.fqdn(), externalFqdn22); + Assertions.assertNotNull(endpoint.monitorStatus()); + Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST2); + c++; + } + } + Assertions.assertEquals(c, 2); + + c = 0; + for (TrafficManagerAzureEndpoint endpoint : profile.azureEndpoints().values()) { + Assertions.assertEquals(endpoint.endpointType(), EndpointType.AZURE); + if (endpoint.name().equalsIgnoreCase(azureEndpointName)) { + Assertions.assertEquals(endpoint.routingPriority(), 3); + Assertions.assertNotNull(endpoint.monitorStatus()); + Assertions.assertEquals(endpoint.targetAzureResourceId(), publicIPAddress.id()); + Assertions.assertEquals(endpoint.targetResourceType(), TargetAzureResourceType.PUBLICIP); + c++; + } + } + Assertions.assertEquals(c, 1); + + c = 0; + for (TrafficManagerNestedProfileEndpoint endpoint : profile.nestedProfileEndpoints().values()) { + Assertions.assertEquals(endpoint.endpointType(), EndpointType.NESTED_PROFILE); + if (endpoint.name().equalsIgnoreCase(nestedProfileEndpointName)) { + Assertions.assertEquals(endpoint.routingPriority(), 4); + Assertions.assertNotNull(endpoint.monitorStatus()); + Assertions.assertEquals(endpoint.minimumChildEndpointCount(), 1); + Assertions.assertEquals(endpoint.nestedProfileId(), nestedProfile.id()); + Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.INDIA_CENTRAL); + c++; + } + } + Assertions.assertEquals(c, 1); + return profile; + } + + @Override + public TrafficManagerProfile updateResource(TrafficManagerProfile profile) throws Exception { + // Remove an endpoint, update two endpoints and add new one + // + profile + .update() + .withTimeToLive(600) + .withHttpMonitoring(8080, "/") + .withPerformanceBasedRouting() + .withoutEndpoint(externalEndpointName21) + .updateAzureTargetEndpoint(azureEndpointName) + .withRoutingPriority(5) + .withRoutingWeight(2) + .parent() + .updateNestedProfileTargetEndpoint(nestedProfileEndpointName) + .withTrafficDisabled() + .parent() + .defineExternalTargetEndpoint(externalEndpointName23) + .toFqdn(externalFqdn23) + .fromRegion(Region.US_CENTRAL) + .withRoutingPriority(6) + .attach() + .apply(); + + Assertions.assertEquals(profile.monitoringPort(), 8080); + Assertions.assertEquals(profile.monitoringPath(), "/"); + Assertions.assertEquals(profile.azureEndpoints().size(), 1); + Assertions.assertEquals(profile.nestedProfileEndpoints().size(), 1); + Assertions.assertEquals(profile.externalEndpoints().size(), 2); + Assertions.assertEquals(profile.timeToLive(), 600); + + int c = 0; + for (TrafficManagerExternalEndpoint endpoint : profile.externalEndpoints().values()) { + Assertions.assertEquals(endpoint.endpointType(), EndpointType.EXTERNAL); + if (endpoint.name().equalsIgnoreCase(externalEndpointName22)) { + Assertions.assertEquals(endpoint.routingPriority(), 2); + Assertions.assertEquals(endpoint.fqdn(), externalFqdn22); + Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_EAST2); + Assertions.assertNotNull(endpoint.monitorStatus()); + c++; + } else if (endpoint.name().equalsIgnoreCase(externalEndpointName23)) { + Assertions.assertEquals(endpoint.routingPriority(), 6); + Assertions.assertEquals(endpoint.fqdn(), externalFqdn23); + Assertions.assertNotNull(endpoint.monitorStatus()); + Assertions.assertEquals(endpoint.sourceTrafficLocation(), Region.US_CENTRAL); + c++; + } else { + c++; + } + } + Assertions.assertEquals(c, 2); + + c = 0; + for (TrafficManagerAzureEndpoint endpoint : profile.azureEndpoints().values()) { + Assertions.assertEquals(endpoint.endpointType(), EndpointType.AZURE); + if (endpoint.name().equalsIgnoreCase(azureEndpointName)) { + Assertions.assertEquals(endpoint.routingPriority(), 5); + Assertions.assertEquals(endpoint.routingWeight(), 2); + Assertions.assertEquals(endpoint.targetResourceType(), TargetAzureResourceType.PUBLICIP); + c++; + } + } + Assertions.assertEquals(c, 1); + return profile; + } + + @Override + public 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()); + } +} From 29e503dc59ad08c16ba7d868f8ab817c0978e6cb Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Tue, 17 Nov 2020 14:36:47 +0800 Subject: [PATCH 2/7] fix spring cloud --- .../samples/ManageSpringCloud.java | 50 +++++++++++++------ 1 file changed, 34 insertions(+), 16 deletions(-) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index 9f4608d3fb54..7bbfd7e6f790 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -6,22 +6,20 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.management.AzureEnvironment; +import com.azure.core.management.Region; +import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Configuration; import com.azure.identity.DefaultAzureCredentialBuilder; import com.azure.resourcemanager.AzureResourceManager; import com.azure.resourcemanager.appplatform.models.SpringApp; import com.azure.resourcemanager.appplatform.models.SpringService; -import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrder; import com.azure.resourcemanager.appservice.models.AppServiceDomain; import com.azure.resourcemanager.dns.models.DnsZone; import com.azure.resourcemanager.keyvault.models.CertificatePermissions; -import com.azure.resourcemanager.keyvault.models.Secret; import com.azure.resourcemanager.keyvault.models.SecretPermissions; import com.azure.resourcemanager.keyvault.models.Vault; import com.azure.resourcemanager.resources.fluentcore.arm.CountryIsoCode; import com.azure.resourcemanager.resources.fluentcore.arm.CountryPhoneCode; -import com.azure.core.management.Region; -import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.samples.Utils; import com.azure.security.keyvault.certificates.CertificateClient; import com.azure.security.keyvault.certificates.CertificateClientBuilder; @@ -31,21 +29,28 @@ import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.compress.utils.IOUtils; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; import javax.xml.bind.DatatypeConverter; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; +import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; +import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.security.SecureRandom; import java.security.cert.CertificateException; -import java.util.Base64; import java.util.Collections; /** @@ -71,7 +76,7 @@ public class ManageSpringCloud { * @return true if sample runs successfully * @throws IllegalStateException unexcepted state */ - public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException { + public static boolean runSample(AzureResourceManager azureResourceManager, String clientId) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, KeyManagementException { final String rgName = Utils.randomResourceName(azureResourceManager, "rg", 24); final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); final Region region = Region.US_EAST; @@ -190,13 +195,20 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin // Please use a trusted certificate for actual use System.out.printf("Generate a self-signed certificate for ssl.%s %n", domainName); allowAllSSL(); - String cerPassword = password(); + String cerPassword = Utils.password(); String cerPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".cer"; String pfxPath = ManageSpringCloud.class.getClass().getResource("/").getPath() + domainName + ".pfx"; - createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); + Utils.createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); + KeyStore store = KeyStore.getInstance("PKCS12"); + store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); + String alias = Collections.list(store.aliases()).get(0); + String thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); + + System.out.printf("Certificate Thumbprint: %s%n", thumbprint); + System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); vault.update() @@ -214,14 +226,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.printf("Created key vault %s%n", vault.name()); Utils.print(vault); - KeyStore store = KeyStore.getInstance("PKCS12"); - store.load(new ByteArrayInputStream(certificate), cerPassword.toCharArray()); - String alias = Collections.list(store.aliases()).get(0); - thumbprint = DatatypeConverter.printHexBinary(MessageDigest.getInstance("SHA-1").digest(store.getCertificate(alias).getEncoded())); - - System.out.printf("Get certificate: %s%n", secret.getValue()); - System.out.printf("Certificate Thumbprint: %s%n", thumbprint); - // upload certificate CertificateClient certificateClient = new CertificateClientBuilder() .vaultUrl(vault.vaultUri()) @@ -316,6 +320,20 @@ public static void extraTarGzSource(File folder, URL url) throws IOException { } } + private static byte[] readAllBytes(InputStream inputStream) throws IOException { + try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { + byte[] data = new byte[4096]; + while (true) { + int size = inputStream.read(data); + if (size > 0) { + outputStream.write(data, 0, size); + } else { + return outputStream.toByteArray(); + } + } + } + } + private static void allowAllSSL() throws NoSuchAlgorithmException, KeyManagementException { TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { From 4a002cae6794b10444e349e801c016390f7af3e5 Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Tue, 17 Nov 2020 16:38:13 +0800 Subject: [PATCH 3/7] fix compile error --- .../appplatform/samples/ManageSpringCloud.java | 9 +++++---- .../samples/ManageLinuxWebAppWithTrafficManager.java | 2 +- .../samples/ManageWebAppWithTrafficManager.java | 2 +- .../trafficmanager/samples/ManageTrafficManager.java | 2 +- .../samples/AppPlatformLiveOnlyTests.java | 3 ++- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index 7bbfd7e6f790..ed1653431e5f 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -197,7 +197,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin allowAllSSL(); String cerPassword = Utils.password(); String cerPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".cer"; - String pfxPath = ManageSpringCloud.class.getClass().getResource("/").getPath() + domainName + ".pfx"; + String pfxPath = ManageSpringCloud.class.getResource("/").getPath() + domainName + ".pfx"; Utils.createCertificate(cerPath, pfxPath, domainName, cerPassword, "ssl." + domainName, "ssl." + domainName); byte[] certificate = readAllBytes(new FileInputStream(pfxPath)); @@ -210,8 +210,9 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin System.out.printf("Certificate Thumbprint: %s%n", thumbprint); System.out.printf("Creating key vault %s with access from %s, %s%n", vaultName, clientId, SPRING_CLOUD_SERVICE_PRINCIPAL); - Vault vault = azureResourceManager.vaults().getByResourceGroup(rgName, vaultName); - vault.update() + Vault vault = azureResourceManager.vaults().define(vaultName) + .withRegion(region) + .withExistingResourceGroup(rgName) .defineAccessPolicy() .forServicePrincipal(clientId) .allowSecretAllPermissions() @@ -222,7 +223,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST) .allowSecretPermissions(SecretPermissions.GET, SecretPermissions.LIST) .attach() - .apply(); + .create(); System.out.printf("Created key vault %s%n", vault.name()); Utils.print(vault); diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java index 5e55edc6db9a..ce98bfa3422a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageLinuxWebAppWithTrafficManager.java @@ -107,7 +107,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a self-signed certificate " + pfxPath + "..."); - Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); + Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName, null); //============================================================ // Create 3 app service plans in 3 regions diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java index 4874462cbc86..7da4c820cfc0 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appservice/samples/ManageWebAppWithTrafficManager.java @@ -106,7 +106,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a self-signed certificate " + pfxPath + "..."); - Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName); + Utils.createCertificate(cerPath, pfxPath, domainName, CERT_PASSWORD, "*." + domainName, null); //============================================================ // Create 3 app service plans in 3 regions diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java index 77dfaa7d7eff..f1bba3cbba6b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/trafficmanager/samples/ManageTrafficManager.java @@ -101,7 +101,7 @@ public static boolean runSample(AzureResourceManager azureResourceManager) throw System.out.println("Creating a self-signed certificate " + pfxPath + "..."); - Utils.createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName); + Utils.createCertificate(cerPath, pfxPath, domainName, certPassword, "*." + domainName, null); //============================================================ // Creates app service in 5 different region diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java index 6ffb40772f97..aa40781247ce 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/java/com/azure/resourcemanager/samples/AppPlatformLiveOnlyTests.java @@ -9,6 +9,7 @@ import org.junit.jupiter.api.Test; import java.io.IOException; +import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; @@ -17,7 +18,7 @@ public class AppPlatformLiveOnlyTests extends SamplesTestBase { @Test @DoNotRecord - public void testSpringCloud() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException { + public void testSpringCloud() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { if (skipInPlayback()) { return; } From fbe700d464835b81fcb7791e8aeb7688f840c0f2 Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Wed, 18 Nov 2020 09:44:55 +0800 Subject: [PATCH 4/7] update version --- .../azure-resourcemanager/pom.xml | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index 7a6fd5e1b7fb..a7c34c0574aa 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -83,7 +83,7 @@ com.azure.resourcemanager azure-resourcemanager-sql - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager @@ -113,7 +113,7 @@ com.azure.resourcemanager azure-resourcemanager-containerregistry - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager @@ -123,42 +123,42 @@ com.azure.resourcemanager azure-resourcemanager-appplatform - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-containerinstance - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-privatedns - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-redis - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-eventhubs - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-trafficmanager - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-servicebus - 2.0.0-beta.5 + 2.0.0-beta.6 com.azure.resourcemanager azure-resourcemanager-cdn - 2.0.0-beta.5 + 2.0.0-beta.6 org.junit.jupiter From 14f462f8f202f3c2332b07ca2cc2c0ebe80b9d8c Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Wed, 18 Nov 2020 10:33:30 +0800 Subject: [PATCH 5/7] fix spotbugs --- .../appplatform/samples/ManageSpringCloud.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java index ed1653431e5f..386bcbad3c0a 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/main/java/com/azure/resourcemanager/appplatform/samples/ManageSpringCloud.java @@ -51,6 +51,7 @@ import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; import java.util.Collections; /** @@ -81,7 +82,6 @@ public static boolean runSample(AzureResourceManager azureResourceManager, Strin final String serviceName = Utils.randomResourceName(azureResourceManager, "service", 24); final Region region = Region.US_EAST; final String domainName = Utils.randomResourceName(azureResourceManager, "jsdkdemo-", 20) + ".com"; - final String certOrderName = Utils.randomResourceName(azureResourceManager, "cert", 15); final String vaultName = Utils.randomResourceName(azureResourceManager, "vault", 15); final String certName = Utils.randomResourceName(azureResourceManager, "cert", 15); @@ -339,7 +339,7 @@ private static void allowAllSSL() throws NoSuchAlgorithmException, KeyManagement TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return null; + return new X509Certificate[0]; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { From 791070077e4afeaf14c3ec4fa7034104613213d5 Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Wed, 18 Nov 2020 10:39:21 +0800 Subject: [PATCH 6/7] session record --- ....testManageCdnProfileWithCustomDomain.json | 949 +++++++++--------- 1 file changed, 483 insertions(+), 466 deletions(-) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/resources/session-records/CdnSampleTests.testManageCdnProfileWithCustomDomain.json b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/resources/session-records/CdnSampleTests.testManageCdnProfileWithCustomDomain.json index 653f9912dd3a..779b8599ae00 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/src/test/resources/session-records/CdnSampleTests.testManageCdnProfileWithCustomDomain.json +++ b/sdk/resourcemanager/azure-resourcemanager-samples/src/test/resources/session-records/CdnSampleTests.testManageCdnProfileWithCustomDomain.json @@ -1,53 +1,55 @@ { "networkCallRecords" : [ { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399?api-version=2020-06-01", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d?api-version=2020-06-01", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "f913219c-6665-45ec-95e1-5d95942b9e2b", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "390e5310-c566-4f5b-9998-949d0ee68b13", "Content-Type" : "application/json" }, "Response" : { "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "x-ms-ratelimit-remaining-subscription-writes" : "1199", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:30:14 GMT", - "x-ms-correlation-request-id" : "93aebab5-32c4-4e75-830a-26898b32d748", + "Date" : "Wed, 18 Nov 2020 02:33:26 GMT", + "x-ms-correlation-request-id" : "349972f3-e33b-4632-8cb9-3128aa1a8402", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043015Z:93aebab5-32c4-4e75-830a-26898b32d748", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023327Z:349972f3-e33b-4632-8cb9-3128aa1a8402", "Expires" : "-1", "Content-Length" : "231", - "x-ms-request-id" : "93aebab5-32c4-4e75-830a-26898b32d748", - "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399\",\"name\":\"rgnemv64403679399\",\"type\":\"Microsoft.Resources/resourceGroups\",\"location\":\"westus\",\"properties\":{\"provisioningState\":\"Succeeded\"}}", + "x-ms-request-id" : "349972f3-e33b-4632-8cb9-3128aa1a8402", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d\",\"name\":\"rgnemv953463e239d\",\"type\":\"Microsoft.Resources/resourceGroups\",\"location\":\"westus\",\"properties\":{\"provisioningState\":\"Succeeded\"}}", "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Network/dnsZones/jsdkcdn935008.com?api-version=2018-03-01-preview", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Network/dnsZones/jsdkcdn298084.com?api-version=2018-03-01-preview", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "78f3d12e-4202-41a7-aa86-769278732c19", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "9c0105ab-3e9a-48c1-a60b-513e177c9abd", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "retry-after" : "0", "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:30:24 GMT", - "x-ms-correlation-request-id" : "c30839aa-036d-418f-916c-2eab70d94485", + "Date" : "Wed, 18 Nov 2020 02:33:36 GMT", + "x-ms-correlation-request-id" : "9bad3266-faf8-457d-974f-14d676bad258", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "11999", "Cache-Control" : "private", - "ETag" : "00000002-0000-0000-031f-9743f487d601", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043025Z:c30839aa-036d-418f-916c-2eab70d94485", + "ETag" : "00000002-0000-0000-13f1-9b3653bdd601", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023337Z:9bad3266-faf8-457d-974f-14d676bad258", "Content-Length" : "535", - "x-ms-request-id" : "78f3d12e-4202-41a7-aa86-769278732c19", - "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv64403679399\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn935008.com\",\"name\":\"jsdkcdn935008.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000002-0000-0000-031f-9743f487d601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-04.azure-dns.com.\",\"ns2-04.azure-dns.net.\",\"ns3-04.azure-dns.org.\",\"ns4-04.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", + "x-ms-request-id" : "9c0105ab-3e9a-48c1-a60b-513e177c9abd", + "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv953463e239d\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn298084.com\",\"name\":\"jsdkcdn298084.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000002-0000-0000-13f1-9b3653bdd601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-01.azure-dns.com.\",\"ns2-01.azure-dns.net.\",\"ns3-01.azure-dns.org.\",\"ns4-01.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json; charset=utf-8" }, @@ -56,932 +58,947 @@ "Method" : "POST", "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/providers/Microsoft.DomainRegistration/topLevelDomains/com/listAgreements?api-version=2019-08-01", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.appservice/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "98fb4a3a-4e03-4e7a-8731-cc796dfa761f", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.appservice/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "90e3f13d-b785-49e4-8980-0b98976f53cb", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "x-ms-ratelimit-remaining-subscription-writes" : "1199", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:30:25 GMT", - "x-ms-correlation-request-id" : "63eadd2b-7e16-456a-b12d-c81ab4f266d7", + "Date" : "Wed, 18 Nov 2020 02:33:37 GMT", + "x-ms-correlation-request-id" : "b9ec636e-3283-413d-a93d-e54dfab3808c", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043026Z:63eadd2b-7e16-456a-b12d-c81ab4f266d7", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023338Z:b9ec636e-3283-413d-a93d-e54dfab3808c", "X-AspNet-Version" : "4.0.30319", "Expires" : "-1", - "Content-Length" : "94535", - "x-ms-request-id" : "ca5b7bbb-f6e1-4c09-a2db-ff8e006b8fff", - "Body" : "{\"value\":[{\"agreementKey\":\"DNRA\",\"title\":\"Domain Registration Agreement\",\"content\":\"\\r\\n\\r\\n\",\"url\":\"http://www.secureserver.net/agreements/ShowDoc.aspx?pageid=reg_sa&pl_id=510456\"}],\"nextLink\":null,\"id\":null}", + "Content-Length" : "94206", + "x-ms-request-id" : "38f9b692-75a3-4699-9dab-70f25fa41609", + "Body" : "{\"value\":[{\"agreementKey\":\"DNRA\",\"title\":\"Domain Registration Agreement\",\"content\":\"\\r\\n\\r\\n\",\"url\":\"REDACTED\"}],\"nextLink\":null,\"id\":null}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.DomainRegistration/domains/jsdkcdn935008.com?api-version=2019-08-01", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com?api-version=2019-08-01", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.appservice/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "03b62a94-ca5b-4220-95bd-c617f2634203", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.appservice/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "ba93bfe0-0bd7-4705-865d-417c2b23c0ee", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "x-ms-ratelimit-remaining-subscription-writes" : "1198", "Pragma" : "no-cache", "StatusCode" : "202", - "Date" : "Fri, 11 Sep 2020 04:30:32 GMT", - "x-ms-correlation-request-id" : "74954de7-b566-4a3b-9dd9-10c2fadbf2c1", + "Date" : "Wed, 18 Nov 2020 02:33:45 GMT", + "x-ms-correlation-request-id" : "1cc2a92f-3fad-4b9d-9459-1d84f4cd7bdd", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Retry-After" : "0", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043032Z:74954de7-b566-4a3b-9dd9-10c2fadbf2c1", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023346Z:1cc2a92f-3fad-4b9d-9459-1d84f4cd7bdd", "X-AspNet-Version" : "4.0.30319", "Expires" : "-1", "Content-Length" : "0", - "x-ms-request-id" : "74954de7-b566-4a3b-9dd9-10c2fadbf2c1", + "x-ms-request-id" : "1cc2a92f-3fad-4b9d-9459-1d84f4cd7bdd", "X-Powered-By" : "ASP.NET", - "Location" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.DomainRegistration/domains/jsdkcdn935008.com/operationresults/c8c052a8-b026-45fe-83f5-8f82994c3cc3?api-version=2019-08-01" + "Location" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com/operationresults/7cc88366-509c-4f6c-8b09-3337caae3f28?api-version=2019-08-01" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.DomainRegistration/domains/jsdkcdn935008.com/operationresults/c8c052a8-b026-45fe-83f5-8f82994c3cc3?api-version=2019-08-01", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com/operationresults/7cc88366-509c-4f6c-8b09-3337caae3f28?api-version=2019-08-01", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "ffab9422-d543-4e1a-a6de-a6497811d47a" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "e23f151b-b6a1-4ed3-857e-505d8c987948" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", - "retry-after" : "0", "x-ms-ratelimit-remaining-subscription-reads" : "11999", + "StatusCode" : "202", + "Date" : "Wed, 18 Nov 2020 02:35:13 GMT", + "x-ms-correlation-request-id" : "e7076eba-7ec5-47f8-81c7-daf300aed6d3", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", + "Retry-After" : "0", + "Cache-Control" : "no-cache", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023513Z:e7076eba-7ec5-47f8-81c7-daf300aed6d3", + "X-AspNet-Version" : "4.0.30319", + "Expires" : "-1", + "Content-Length" : "0", + "x-ms-request-id" : "e7076eba-7ec5-47f8-81c7-daf300aed6d3", + "X-Powered-By" : "ASP.NET", + "Location" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com/operationresults/7cc88366-509c-4f6c-8b09-3337caae3f28?api-version=2019-08-01" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com/operationresults/7cc88366-509c-4f6c-8b09-3337caae3f28?api-version=2019-08-01", + "Headers" : { + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "43cb98cb-a7cc-4301-925f-2250ab8b4f4d" + }, + "Response" : { + "Server" : "Microsoft-IIS/10.0", + "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", + "Pragma" : "no-cache", + "retry-after" : "0", + "x-ms-ratelimit-remaining-subscription-reads" : "11998", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:31:59 GMT", - "x-ms-correlation-request-id" : "2cc7e053-f1b7-43f4-b16f-b42ab7f76df0", + "Date" : "Wed, 18 Nov 2020 02:35:43 GMT", + "x-ms-correlation-request-id" : "0840731d-719b-4de3-8a1b-c541a67a3c30", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043200Z:2cc7e053-f1b7-43f4-b16f-b42ab7f76df0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023544Z:0840731d-719b-4de3-8a1b-c541a67a3c30", "X-AspNet-Version" : "4.0.30319", "Expires" : "-1", "Content-Length" : "850", - "x-ms-request-id" : "23122a98-18a1-4c22-a6df-b755ce98a194", - "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.DomainRegistration/domains/jsdkcdn935008.com\",\"name\":\"jsdkcdn935008.com\",\"type\":\"Microsoft.DomainRegistration/domains\",\"location\":\"global\",\"tags\":{},\"properties\":{\"registrationStatus\":\"Active\",\"provisioningState\":\"Succeeded\",\"nameServers\":[\"ns1-04.azure-dns.com\",\"ns2-04.azure-dns.net\",\"ns3-04.azure-dns.org\",\"ns4-04.azure-dns.info\"],\"privacy\":true,\"createdTime\":\"2020-09-10T23:30:36\",\"expirationTime\":\"2021-09-10T23:30:36\",\"autoRenew\":true,\"readyForDnsRecordManagement\":true,\"managedHostNames\":[],\"domainNotRenewableReasons\":[\"ExpirationNotInRenewalTimeRange\"],\"dnsType\":\"AzureDns\",\"dnsZoneId\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Network/dnszones/jsdkcdn935008.com\"}}", + "x-ms-request-id" : "c2766ea0-c726-4675-93cd-b177e7cf21ea", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.DomainRegistration/domains/jsdkcdn298084.com\",\"name\":\"jsdkcdn298084.com\",\"type\":\"Microsoft.DomainRegistration/domains\",\"location\":\"global\",\"tags\":{},\"properties\":{\"registrationStatus\":\"Active\",\"provisioningState\":\"Succeeded\",\"nameServers\":[\"ns1-01.azure-dns.com\",\"ns2-01.azure-dns.net\",\"ns3-01.azure-dns.org\",\"ns4-01.azure-dns.info\"],\"privacy\":true,\"createdTime\":\"2020-11-17T21:33:55\",\"expirationTime\":\"2021-11-17T21:33:55\",\"autoRenew\":true,\"readyForDnsRecordManagement\":true,\"managedHostNames\":[],\"domainNotRenewableReasons\":[\"ExpirationNotInRenewalTimeRange\"],\"dnsType\":\"AzureDns\",\"dnsZoneId\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Network/dnszones/jsdkcdn298084.com\"}}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Network/dnsZones/jsdkcdn935008.com?api-version=2018-03-01-preview", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Network/dnsZones/jsdkcdn298084.com?api-version=2018-03-01-preview", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "36fe4ecf-539b-40e4-a64e-aff399ef1686", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "a712fa7e-c588-4fa0-93c5-adb45630770c", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:01 GMT", - "x-ms-correlation-request-id" : "5ec47c56-d9d6-4e35-bcff-8751e5532a7e", + "Date" : "Wed, 18 Nov 2020 02:35:45 GMT", + "x-ms-correlation-request-id" : "d0df132a-2ce7-4530-8a3b-1eafb9f1a9bd", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "11998", "Cache-Control" : "private", - "ETag" : "00000003-0000-0000-031f-9743f487d601", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043202Z:5ec47c56-d9d6-4e35-bcff-8751e5532a7e", + "ETag" : "00000003-0000-0000-13f1-9b3653bdd601", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023546Z:d0df132a-2ce7-4530-8a3b-1eafb9f1a9bd", "Content-Length" : "535", - "x-ms-request-id" : "36fe4ecf-539b-40e4-a64e-aff399ef1686", - "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv64403679399\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn935008.com\",\"name\":\"jsdkcdn935008.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000003-0000-0000-031f-9743f487d601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-04.azure-dns.com.\",\"ns2-04.azure-dns.net.\",\"ns3-04.azure-dns.org.\",\"ns4-04.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", + "x-ms-request-id" : "a712fa7e-c588-4fa0-93c5-adb45630770c", + "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv953463e239d\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn298084.com\",\"name\":\"jsdkcdn298084.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000003-0000-0000-13f1-9b3653bdd601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-01.azure-dns.com.\",\"ns2-01.azure-dns.net.\",\"ns3-01.azure-dns.org.\",\"ns4-01.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Network/dnsZones/jsdkcdn935008.com?api-version=2018-03-01-preview", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Network/dnsZones/jsdkcdn298084.com?api-version=2018-03-01-preview", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "e3587d7d-51e8-4427-826f-b48794f541da", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "929e0249-b8d4-438d-86f1-e18c6f0701a7", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:04 GMT", - "x-ms-correlation-request-id" : "387f0457-fac6-47ab-bd37-2e5cb0f585b0", + "Date" : "Wed, 18 Nov 2020 02:35:47 GMT", + "x-ms-correlation-request-id" : "37f54c4c-76e3-4a95-8e82-e14bd34b3737", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "11997", "Cache-Control" : "private", - "ETag" : "00000004-0000-0000-031f-9743f487d601", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043205Z:387f0457-fac6-47ab-bd37-2e5cb0f585b0", + "ETag" : "00000004-0000-0000-13f1-9b3653bdd601", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023548Z:37f54c4c-76e3-4a95-8e82-e14bd34b3737", "Content-Length" : "535", - "x-ms-request-id" : "e3587d7d-51e8-4427-826f-b48794f541da", - "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv64403679399\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn935008.com\",\"name\":\"jsdkcdn935008.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000004-0000-0000-031f-9743f487d601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-04.azure-dns.com.\",\"ns2-04.azure-dns.net.\",\"ns3-04.azure-dns.org.\",\"ns4-04.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", + "x-ms-request-id" : "929e0249-b8d4-438d-86f1-e18c6f0701a7", + "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv953463e239d\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn298084.com\",\"name\":\"jsdkcdn298084.com\",\"type\":\"Microsoft.Network\\/dnszones\",\"etag\":\"00000004-0000-0000-13f1-9b3653bdd601\",\"location\":\"global\",\"tags\":{},\"properties\":{\"maxNumberOfRecordSets\":10000,\"maxNumberOfRecordsPerRecordSet\":null,\"nameServers\":[\"ns1-01.azure-dns.com.\",\"ns2-01.azure-dns.net.\",\"ns3-01.azure-dns.org.\",\"ns4-01.azure-dns.info.\"],\"numberOfRecordSets\":2,\"zoneType\":\"Public\"}}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Network/dnsZones/jsdkcdn935008.com/CNAME/sample?api-version=2018-03-01-preview", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Network/dnsZones/jsdkcdn298084.com/CNAME/sample?api-version=2018-03-01-preview", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "bc1ecd81-e4b0-4472-994e-7cf1439cab1b", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.dns/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "3b70c1ee-b621-41a8-9778-5c77477c9f09", "Content-Type" : "application/json" }, "Response" : { "Server" : "Microsoft-IIS/10.0", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "retry-after" : "0", "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:32:05 GMT", - "x-ms-correlation-request-id" : "48d44e99-cb4b-4ec9-a90d-bfd7152f1a4a", + "Date" : "Wed, 18 Nov 2020 02:35:49 GMT", + "x-ms-correlation-request-id" : "42ce7892-fbfb-4302-a455-6c0e758abc5d", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "11999", "Cache-Control" : "private", - "ETag" : "9b4cc6f0-2cd1-41b4-ae2c-48c454fc2471", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043206Z:48d44e99-cb4b-4ec9-a90d-bfd7152f1a4a", + "ETag" : "9d6eb958-c540-4b84-a73c-94b9c6c07966", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023549Z:42ce7892-fbfb-4302-a455-6c0e758abc5d", "Content-Length" : "397", - "x-ms-request-id" : "bc1ecd81-e4b0-4472-994e-7cf1439cab1b", - "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv64403679399\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn935008.com\\/CNAME\\/sample\",\"name\":\"sample\",\"type\":\"Microsoft.Network\\/dnszones\\/CNAME\",\"etag\":\"9b4cc6f0-2cd1-41b4-ae2c-48c454fc2471\",\"properties\":{\"fqdn\":\"sample.jsdkcdn935008.com.\",\"TTL\":3600,\"CNAMERecord\":{\"cname\":\"jsdkcdne44223f237c.azureedge.net\"}}}", + "x-ms-request-id" : "3b70c1ee-b621-41a8-9778-5c77477c9f09", + "Body" : "{\"id\":\"\\/subscriptions\\/00000000-0000-0000-0000-000000000000\\/resourceGroups\\/rgnemv953463e239d\\/providers\\/Microsoft.Network\\/dnszones\\/jsdkcdn298084.com\\/CNAME\\/sample\",\"name\":\"sample\",\"type\":\"Microsoft.Network\\/dnszones\\/CNAME\",\"etag\":\"9d6eb958-c540-4b84-a73c-94b9c6c07966\",\"properties\":{\"fqdn\":\"sample.jsdkcdn298084.com.\",\"TTL\":3600,\"CNAMERecord\":{\"cname\":\"jsdkcdne15830981af.azureedge.net\"}}}", "X-Powered-By" : "ASP.NET", "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "ebbee3ab-503b-406c-8ef5-79e011005bca", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "8424dfb4-0897-4df7-8f5d-06edfd805f97", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:32:17 GMT", - "x-ms-correlation-request-id" : "5bd56389-5bf0-46a7-b2d3-ed0e3016a349", + "Date" : "Wed, 18 Nov 2020 02:35:57 GMT", + "x-ms-correlation-request-id" : "c0e0fcb9-8d4a-4ed7-a2c4-0778e85f72bc", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Retry-After" : "0", "x-ms-ratelimit-remaining-subscription-resource-requests" : "24", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043217Z:5bd56389-5bf0-46a7-b2d3-ed0e3016a349", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023558Z:c0e0fcb9-8d4a-4ed7-a2c4-0778e85f72bc", "Expires" : "-1", - "Content-Length" : "377", - "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/f1c18dcb-55b7-4ff5-8331-d9e189c866f7?api-version=2017-10-12", - "x-ms-request-id" : "867f54ac-91e2-48ec-ad00-4f431e2c5fb1", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Creating\",\"resourceState\":\"Creating\"\r\n }\r\n}", - "x-ms-client-request-id" : "ebbee3ab-503b-406c-8ef5-79e011005bca", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "341", + "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/820fbc8e-40a8-44bd-b745-2b3cad8a72a4?api-version=2020-04-15", + "x-ms-request-id" : "2a34f7f6-8cdf-4b2d-ac50-cdae68228bbb", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Creating\",\"provisioningState\":\"Creating\"}}", + "x-ms-client-request-id" : "8424dfb4-0897-4df7-8f5d-06edfd805f97", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/f1c18dcb-55b7-4ff5-8331-d9e189c866f7?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/820fbc8e-40a8-44bd-b745-2b3cad8a72a4?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "2e7eb847-f3ad-4724-a447-8150ede3986d" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "5f4b2dd1-cb7e-4e02-84c5-569e0eab7881" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11998", + "x-ms-ratelimit-remaining-subscription-reads" : "11997", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:28 GMT", - "x-ms-correlation-request-id" : "2773623f-4d2f-40a4-bfa1-f11f37514a95", + "Date" : "Wed, 18 Nov 2020 02:36:08 GMT", + "x-ms-correlation-request-id" : "a8c414d6-1e90-4a51-8dd9-a3fe2c461f63", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043228Z:2773623f-4d2f-40a4-bfa1-f11f37514a95", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023609Z:a8c414d6-1e90-4a51-8dd9-a3fe2c461f63", "Expires" : "-1", - "Content-Length" : "77", - "x-ms-request-id" : "12f9b727-09bd-4b35-97ec-8e4c7e638ccc", - "Body" : "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", - "x-ms-client-request-id" : "2e7eb847-f3ad-4724-a447-8150ede3986d", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "62", + "x-ms-request-id" : "b08ef874-548c-4d8a-ae2d-7e0436569f99", + "Body" : "{\"status\":\"InProgress\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "5f4b2dd1-cb7e-4e02-84c5-569e0eab7881", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/820fbc8e-40a8-44bd-b745-2b3cad8a72a4?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "186bf167-7f51-4da3-a559-1a909d682f24" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "6fbc8247-7569-4afa-8171-196c76b44b50" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", + "x-ms-ratelimit-remaining-subscription-reads" : "11996", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:30 GMT", - "x-ms-correlation-request-id" : "de8316ae-08fb-4c43-95bf-5a9d74bb8764", + "Date" : "Wed, 18 Nov 2020 02:36:38 GMT", + "x-ms-correlation-request-id" : "d5aa38dd-aee1-4b1f-92de-ee6224bd0096", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", + "Cache-Control" : "no-cache", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023639Z:d5aa38dd-aee1-4b1f-92de-ee6224bd0096", + "Expires" : "-1", + "Content-Length" : "61", + "x-ms-request-id" : "b54d3e69-e303-43df-b78b-c8d5bae5ed12", + "Body" : "{\"status\":\"Succeeded\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "6fbc8247-7569-4afa-8171-196c76b44b50", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", + "Headers" : { + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "dfd827e9-c1fd-4504-83c1-f0e055299314" + }, + "Response" : { + "Server" : "Kestrel", + "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", + "Pragma" : "no-cache", + "retry-after" : "0", + "StatusCode" : "200", + "Date" : "Wed, 18 Nov 2020 02:36:39 GMT", + "x-ms-correlation-request-id" : "b7acf1d5-5615-4d63-92de-9e37688f0f20", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "49", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043230Z:de8316ae-08fb-4c43-95bf-5a9d74bb8764", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023640Z:b7acf1d5-5615-4d63-92de-9e37688f0f20", "Expires" : "-1", - "Content-Length" : "376", - "x-ms-request-id" : "cfc95554-fe5a-4b16-acb3-b76370d069de", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", - "x-ms-client-request-id" : "186bf167-7f51-4da3-a559-1a909d682f24", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "340", + "x-ms-request-id" : "88db3ce9-f7d0-4eb9-ac17-e1895ce6c604", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Active\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "dfd827e9-c1fd-4504-83c1-f0e055299314", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PATCH", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "f232125d-ccaa-4532-801a-e390165d4961", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "8e603957-4335-400d-be07-a7058cf62387", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:34 GMT", - "x-ms-correlation-request-id" : "acee844c-4078-47b9-ab44-b32d5137a6e8", + "Date" : "Wed, 18 Nov 2020 02:36:50 GMT", + "x-ms-correlation-request-id" : "9626fc82-650c-4b30-80a5-ea92e610e423", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "23", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043234Z:acee844c-4078-47b9-ab44-b32d5137a6e8", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023651Z:9626fc82-650c-4b30-80a5-ea92e610e423", "Expires" : "-1", - "Content-Length" : "376", - "x-ms-request-id" : "71180128-4f41-47e7-85c3-787133c6b68e", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", - "x-ms-client-request-id" : "f232125d-ccaa-4532-801a-e390165d4961", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "340", + "x-ms-request-id" : "89437f3b-4fa4-44c8-893a-512f5d91abb0", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Active\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "8e603957-4335-400d-be07-a7058cf62387", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "efd1e99f-226d-4f5c-85bf-b27dca769ef8", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "cca8418f-70bb-4349-b52d-e17a93c0c957", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:32:45 GMT", - "x-ms-correlation-request-id" : "0ad71b9a-906e-4ece-b965-d41ed56d3ca1", + "Date" : "Wed, 18 Nov 2020 02:37:02 GMT", + "x-ms-correlation-request-id" : "2bf88a8f-3188-4578-8894-e2f053aa4ff4", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Retry-After" : "0", "x-ms-ratelimit-remaining-subscription-resource-requests" : "99", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043245Z:0ad71b9a-906e-4ece-b965-d41ed56d3ca1", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023702Z:2bf88a8f-3188-4578-8894-e2f053aa4ff4", "Expires" : "-1", - "Content-Length" : "915", - "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/6e5aac96-c8d2-4e58-b665-8ed1d7656096?api-version=2017-10-12", - "x-ms-request-id" : "d7cd9d20-58b1-4e0c-85bb-3341e51f2a1c", - "Body" : "{\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Creating\",\"resourceState\":\"Creating\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n \r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n}", - "x-ms-client-request-id" : "efd1e99f-226d-4f5c-85bf-b27dca769ef8", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1111", + "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f54a3a7d-891e-4e7e-8fc4-0d8f4b55a35e?api-version=2020-04-15", + "x-ms-request-id" : "42ba8c23-2766-4a35-8fc7-5ea632e864fe", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":null,\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Creating\",\"provisioningState\":\"Creating\"}}", + "x-ms-client-request-id" : "cca8418f-70bb-4349-b52d-e17a93c0c957", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/6e5aac96-c8d2-4e58-b665-8ed1d7656096?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f54a3a7d-891e-4e7e-8fc4-0d8f4b55a35e?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "c53ae09d-c99f-4f12-b2b0-e01b12eda4e8" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "804b44b0-f414-487b-b8eb-40aae5aec999" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11997", + "x-ms-ratelimit-remaining-subscription-reads" : "11995", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:32:55 GMT", - "x-ms-correlation-request-id" : "cb21f140-4fba-4cce-a5ca-6edc0bbe803b", + "Date" : "Wed, 18 Nov 2020 02:37:12 GMT", + "x-ms-correlation-request-id" : "c84e5a38-a19d-43e2-96b1-8b34ec9a7120", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043256Z:cb21f140-4fba-4cce-a5ca-6edc0bbe803b", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023712Z:c84e5a38-a19d-43e2-96b1-8b34ec9a7120", "Expires" : "-1", - "Content-Length" : "78", - "x-ms-request-id" : "4ba6ffa1-491d-4e33-9a08-eb91418c97d3", - "Body" : "{\r\n \"status\":\"InProgress\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", - "x-ms-client-request-id" : "c53ae09d-c99f-4f12-b2b0-e01b12eda4e8", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "62", + "x-ms-request-id" : "9a4d8c65-3a20-4915-81eb-e3cb2ac6837e", + "Body" : "{\"status\":\"InProgress\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "804b44b0-f414-487b-b8eb-40aae5aec999", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/6e5aac96-c8d2-4e58-b665-8ed1d7656096?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f54a3a7d-891e-4e7e-8fc4-0d8f4b55a35e?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "be1de30f-9878-44bd-bc24-e07eb0b287f4" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "0b287036-0f5a-4767-ac91-9a76947fbc3a" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11996", + "x-ms-ratelimit-remaining-subscription-reads" : "11994", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:26 GMT", - "x-ms-correlation-request-id" : "171b6c8b-5959-4845-a548-505961c2d47d", + "Date" : "Wed, 18 Nov 2020 02:37:42 GMT", + "x-ms-correlation-request-id" : "585b040c-a43f-4854-9c77-527ce1e66033", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043326Z:171b6c8b-5959-4845-a548-505961c2d47d", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023743Z:585b040c-a43f-4854-9c77-527ce1e66033", "Expires" : "-1", - "Content-Length" : "77", - "x-ms-request-id" : "2a80fd22-501f-4397-bf6f-90b7f715d610", - "Body" : "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", - "x-ms-client-request-id" : "be1de30f-9878-44bd-bc24-e07eb0b287f4", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "61", + "x-ms-request-id" : "82866fc2-b9dd-4d8e-b4d0-db2fd1ac7c9b", + "Body" : "{\"status\":\"Succeeded\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "0b287036-0f5a-4767-ac91-9a76947fbc3a", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "6f24b57f-66fd-462c-bf4a-0e08569e89a7" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "ab4346d8-eeba-46ac-b404-5005d6ccb071" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:27 GMT", - "x-ms-correlation-request-id" : "efa86a6d-a287-4769-849a-202486c913eb", + "Date" : "Wed, 18 Nov 2020 02:37:43 GMT", + "x-ms-correlation-request-id" : "ec94acc0-1986-46bc-9eed-40fd847a6dc4", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "49", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043328Z:efa86a6d-a287-4769-849a-202486c913eb", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023743Z:ec94acc0-1986-46bc-9eed-40fd847a6dc4", "Expires" : "-1", - "Content-Length" : "915", - "x-ms-request-id" : "794acccd-b657-4ddb-86f8-81cbc7ae50e8", - "Body" : "{\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Succeeded\",\"resourceState\":\"Running\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n \r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n}", - "x-ms-client-request-id" : "6f24b57f-66fd-462c-bf4a-0e08569e89a7", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1109", + "x-ms-request-id" : "4b875999-9b21-4206-8df1-4a3367dbc713", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":[],\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Running\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "ab4346d8-eeba-46ac-b404-5005d6ccb071", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "dea16e9d-6eb4-4623-bba1-79278d87b768", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "4de0a778-9e70-4dd8-b1e4-d80866fba83e", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11995", + "x-ms-ratelimit-remaining-subscription-reads" : "11993", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:28 GMT", - "x-ms-correlation-request-id" : "8bbd6a43-ae8c-4c60-82f4-4c6b4e1612d1", + "Date" : "Wed, 18 Nov 2020 02:37:44 GMT", + "x-ms-correlation-request-id" : "04509c8e-40d1-4010-b6e6-e25592aaf8e1", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043329Z:8bbd6a43-ae8c-4c60-82f4-4c6b4e1612d1", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023744Z:04509c8e-40d1-4010-b6e6-e25592aaf8e1", "Expires" : "-1", - "Content-Length" : "28", - "x-ms-request-id" : "7d49e87f-1062-4dde-af50-4a82fea24120", - "Body" : "{\r\n \"value\":[\r\n \r\n ]\r\n}", - "x-ms-client-request-id" : "dea16e9d-6eb4-4623-bba1-79278d87b768", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "12", + "x-ms-request-id" : "708d7e84-f30e-41e3-9c91-b1463e62b349", + "Body" : "{\"value\":[]}", + "x-ms-client-request-id" : "4de0a778-9e70-4dd8-b1e4-d80866fba83e", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "61bc1038-ab42-4fb1-825a-8a1681fee6b1", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "4c77ece9-aa6e-408e-9e86-6d908b476a90", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:30 GMT", - "x-ms-correlation-request-id" : "e3fd7bcd-04cb-4997-b762-79090f583b67", + "Date" : "Wed, 18 Nov 2020 02:37:44 GMT", + "x-ms-correlation-request-id" : "cc8e3d08-db9c-49b6-b694-725a915282c0", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "48", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043330Z:e3fd7bcd-04cb-4997-b762-79090f583b67", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023745Z:cc8e3d08-db9c-49b6-b694-725a915282c0", "Expires" : "-1", - "Content-Length" : "376", - "x-ms-request-id" : "a33100df-03f0-4adb-b8df-0b975f8906ce", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", - "x-ms-client-request-id" : "61bc1038-ab42-4fb1-825a-8a1681fee6b1", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "340", + "x-ms-request-id" : "4b75ce0e-82e0-4e34-9b44-a3de5f81b549", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Active\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "4c77ece9-aa6e-408e-9e86-6d908b476a90", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "cded865e-b6a0-490d-8c54-59cabd84c203", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "b52eda77-126b-4b07-992d-96060faf8ef9", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:31 GMT", - "x-ms-correlation-request-id" : "6b8d7825-6822-4876-b68a-8f01768f88c3", + "Date" : "Wed, 18 Nov 2020 02:37:45 GMT", + "x-ms-correlation-request-id" : "aab0ec46-2433-4a0a-af75-14653ea2b2a6", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "48", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043332Z:6b8d7825-6822-4876-b68a-8f01768f88c3", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023745Z:aab0ec46-2433-4a0a-af75-14653ea2b2a6", "Expires" : "-1", - "Content-Length" : "1015", - "x-ms-request-id" : "625af005-e7c4-4e24-9a07-3cc5183580f5", - "Body" : "{\r\n \"value\":[\r\n {\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Succeeded\",\"resourceState\":\"Running\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n \r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n }\r\n ]\r\n}", - "x-ms-client-request-id" : "cded865e-b6a0-490d-8c54-59cabd84c203", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1121", + "x-ms-request-id" : "93135a70-fe80-4b5f-a1f8-313a91cc99a1", + "Body" : "{\"value\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":[],\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Running\",\"provisioningState\":\"Succeeded\"}}]}", + "x-ms-client-request-id" : "b52eda77-126b-4b07-992d-96060faf8ef9", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "6a050e98-fc4d-4aae-a259-c1dc53035a6c", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "99c09e13-90d0-4e3a-9ae7-b129abc3c874", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11994", + "x-ms-ratelimit-remaining-subscription-reads" : "11992", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:32 GMT", - "x-ms-correlation-request-id" : "8fdbecda-0ac2-43dc-b4a9-c4d96ca2b8ed", + "Date" : "Wed, 18 Nov 2020 02:37:46 GMT", + "x-ms-correlation-request-id" : "8da36aa0-f711-4419-ade2-d818cff6faf2", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043333Z:8fdbecda-0ac2-43dc-b4a9-c4d96ca2b8ed", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023746Z:8da36aa0-f711-4419-ade2-d818cff6faf2", "Expires" : "-1", - "Content-Length" : "28", - "x-ms-request-id" : "3f519ee6-0c57-4756-9be6-67dbc9c3ab93", - "Body" : "{\r\n \"value\":[\r\n \r\n ]\r\n}", - "x-ms-client-request-id" : "6a050e98-fc4d-4aae-a259-c1dc53035a6c", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "12", + "x-ms-request-id" : "b5410408-687a-48fe-af2d-4d4fdf95f3d2", + "Body" : "{\"value\":[]}", + "x-ms-client-request-id" : "99c09e13-90d0-4e3a-9ae7-b129abc3c874", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "e2f01a51-c508-49b0-b2c3-74d75f36ffe7", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "68ab88ab-8706-43c2-9267-a68f4581255d", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:34 GMT", - "x-ms-correlation-request-id" : "3127c9ca-b486-45ed-ab95-cc3a54ef4c0f", + "Date" : "Wed, 18 Nov 2020 02:37:47 GMT", + "x-ms-correlation-request-id" : "3c55cdfc-f4cd-4f34-997b-47995de7c17a", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "47", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043334Z:3127c9ca-b486-45ed-ab95-cc3a54ef4c0f", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023747Z:3c55cdfc-f4cd-4f34-997b-47995de7c17a", "Expires" : "-1", - "Content-Length" : "915", - "x-ms-request-id" : "292d8b03-0b29-4ec0-87dc-72c67053ba37", - "Body" : "{\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Succeeded\",\"resourceState\":\"Running\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n \r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n}", - "x-ms-client-request-id" : "e2f01a51-c508-49b0-b2c3-74d75f36ffe7", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1109", + "x-ms-request-id" : "37ad36ea-ed5a-4f66-b61b-925725bda7bc", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":[],\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Running\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "68ab88ab-8706-43c2-9267-a68f4581255d", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "PATCH", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "558ded3c-000b-462c-bb47-9dbb28e5ed0c", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "4af233c9-3a04-4ed9-8e58-b635a8bf2493", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:41 GMT", - "x-ms-correlation-request-id" : "87615927-ab48-4f66-9efd-9577032286cb", + "Date" : "Wed, 18 Nov 2020 02:37:50 GMT", + "x-ms-correlation-request-id" : "ece5fdc3-4b41-4237-a33f-5a57c0b47e4f", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "22", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043341Z:87615927-ab48-4f66-9efd-9577032286cb", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023750Z:ece5fdc3-4b41-4237-a33f-5a57c0b47e4f", "Expires" : "-1", - "Content-Length" : "376", - "x-ms-request-id" : "fe29b29c-7610-4ef1-952b-1d665da669a5", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", - "x-ms-client-request-id" : "558ded3c-000b-462c-bb47-9dbb28e5ed0c", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "340", + "x-ms-request-id" : "9e1a637a-dd85-455c-9dbc-6d1bf6e9a569", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Active\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "4af233c9-3a04-4ed9-8e58-b635a8bf2493", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { - "Method" : "PUT", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains/customdomaintestmanagecdnprofilea5e65263ef0da?api-version=2017-10-12", + "Method" : "PATCH", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/origins/origin1?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "18db1bff-4385-4da8-98e0-e146d8bf9043", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "ebea7da8-66e9-4d1a-8713-da49c50298ed", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", - "x-ms-ratelimit-remaining-subscription-writes" : "1197", + "Connection" : "keep-alive", + "x-ms-ratelimit-remaining-subscription-writes" : "1199", "Pragma" : "no-cache", - "StatusCode" : "201", - "Date" : "Fri, 11 Sep 2020 04:33:46 GMT", - "x-ms-correlation-request-id" : "9b48112f-e5a5-4f0e-919f-b6ef15feb906", + "retry-after" : "0", + "StatusCode" : "200", + "Date" : "Wed, 18 Nov 2020 02:37:53 GMT", + "x-ms-correlation-request-id" : "48b50829-0e3f-4395-b438-9064e3be40af", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", - "Retry-After" : "0", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043346Z:9b48112f-e5a5-4f0e-919f-b6ef15feb906", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023753Z:48b50829-0e3f-4395-b438-9064e3be40af", "Expires" : "-1", - "Content-Length" : "577", - "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/ffe3d262-6d33-4d73-bbbe-481ede2c7b1a?api-version=2017-10-12", - "x-ms-request-id" : "1343c018-f233-41ef-9dc3-a684dbd11da8", - "Body" : "{\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customdomains/customdomaintestmanagecdnprofilea5e65263ef0da\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"properties\":{\r\n \"provisioningState\":\"Creating\",\"resourceState\":\"Creating\",\"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null,\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\"\r\n }\r\n}", - "x-ms-client-request-id" : "18db1bff-4385-4da8-98e0-e146d8bf9043", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "606", + "x-ms-request-id" : "e8ce2271-5e0e-46d1-93e9-f40fdd1dc8d5", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/origins/origin1\",\"type\":\"Microsoft.Cdn/profiles/endpoints/origins\",\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"resourceState\":\"Active\",\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null,\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "ebea7da8-66e9-4d1a-8713-da49c50298ed", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { - "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/ffe3d262-6d33-4d73-bbbe-481ede2c7b1a?api-version=2017-10-12", + "Method" : "PUT", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains/customdomain73618cf5c830ee9794064?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "be9f24ec-a38a-40e0-bc3b-76b060a9c1c4" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "dd6577ea-0c04-4973-b36a-82d667072364", + "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", + "x-ms-ratelimit-remaining-subscription-writes" : "1197", "Pragma" : "no-cache", - "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11993", - "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:33:56 GMT", - "x-ms-correlation-request-id" : "676ed9a8-9acd-49f6-a7c1-b8a259e794eb", + "StatusCode" : "201", + "Date" : "Wed, 18 Nov 2020 02:37:54 GMT", + "x-ms-correlation-request-id" : "8cbc7965-c7c8-4df0-8c63-320eab980a31", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", + "Retry-After" : "0", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043357Z:676ed9a8-9acd-49f6-a7c1-b8a259e794eb", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023755Z:8cbc7965-c7c8-4df0-8c63-320eab980a31", "Expires" : "-1", - "Content-Length" : "78", - "x-ms-request-id" : "6c7d42f5-b6fe-467f-ad87-49a9fb4692f9", - "Body" : "{\r\n \"status\":\"InProgress\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", - "x-ms-client-request-id" : "be9f24ec-a38a-40e0-bc3b-76b060a9c1c4", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "566", + "Azure-AsyncOperation" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f85b1664-dd4e-4eae-b76b-c48edfc73a5a?api-version=2020-04-15", + "x-ms-request-id" : "37842a08-3697-4832-8e07-bb376f6161e0", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customdomains/customdomain73618cf5c830ee9794064\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null,\"resourceState\":\"Creating\",\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\",\"customHttpsParameters\":null,\"provisioningState\":\"Creating\"}}", + "x-ms-client-request-id" : "dd6577ea-0c04-4973-b36a-82d667072364", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { - "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/operationresults/ffe3d262-6d33-4d73-bbbe-481ede2c7b1a?api-version=2017-10-12", + "Method" : "PATCH", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "9688b28e-3be5-4e48-9903-ddd34c08ad4f" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "e027d39e-e4cf-4b24-8a95-b5bb16ba585c", + "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11992", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:26 GMT", - "x-ms-correlation-request-id" : "af5915bd-a89b-4444-8ce1-f899b3345e8b", + "Date" : "Wed, 18 Nov 2020 02:38:00 GMT", + "x-ms-correlation-request-id" : "15fe73bf-b617-4bac-a84a-649914ba8e55", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", + "x-ms-ratelimit-remaining-subscription-resource-requests" : "99", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043427Z:af5915bd-a89b-4444-8ce1-f899b3345e8b", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023801Z:15fe73bf-b617-4bac-a84a-649914ba8e55", "Expires" : "-1", - "Content-Length" : "77", - "x-ms-request-id" : "0e32c41a-9e6a-4835-b37f-dd915ca79c7d", - "Body" : "{\r\n \"status\":\"Succeeded\",\"error\":{\r\n \"code\":\"None\",\"message\":null\r\n }\r\n}", - "x-ms-client-request-id" : "9688b28e-3be5-4e48-9903-ddd34c08ad4f", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1228", + "x-ms-request-id" : "00dbb81b-15d5-498f-91b3-85c29fee15b5", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[{\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null}}],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":[],\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Running\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "e027d39e-e4cf-4b24-8a95-b5bb16ba585c", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains/customdomaintestmanagecdnprofilea5e65263ef0da?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f85b1664-dd4e-4eae-b76b-c48edfc73a5a?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "0b402ba3-ed79-4d9d-81c8-26bb7a42a5ad" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "97dc5f5f-e0be-4ca3-b2f6-58dbc78b3a16" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11991", + "x-ms-ratelimit-remaining-subscription-reads" : "11999", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:28 GMT", - "x-ms-correlation-request-id" : "80f709cd-3c87-4730-a403-29c55c6cab0d", + "Date" : "Wed, 18 Nov 2020 02:38:06 GMT", + "x-ms-correlation-request-id" : "5b3a2e30-d493-4d4b-8b29-f0564f1dc7dd", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043429Z:80f709cd-3c87-4730-a403-29c55c6cab0d", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023806Z:5b3a2e30-d493-4d4b-8b29-f0564f1dc7dd", "Expires" : "-1", - "Content-Length" : "576", - "x-ms-request-id" : "8c08c135-6916-411a-9983-624fbd961c43", - "Body" : "{\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customdomains/customdomaintestmanagecdnprofilea5e65263ef0da\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\",\"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null,\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\"\r\n }\r\n}", - "x-ms-client-request-id" : "0b402ba3-ed79-4d9d-81c8-26bb7a42a5ad", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "62", + "x-ms-request-id" : "5dd21588-c401-400b-8ef9-8056a137dfd6", + "Body" : "{\"status\":\"InProgress\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "97dc5f5f-e0be-4ca3-b2f6-58dbc78b3a16", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { - "Method" : "PATCH", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/origins/origin1?api-version=2017-10-12", + "Method" : "GET", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/operationresults/f85b1664-dd4e-4eae-b76b-c48edfc73a5a?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "a5d16856-f9fe-4455-bf17-8db3d9a49e2d", - "Content-Type" : "application/json" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "a57f99c5-8b0a-400c-b2df-5376c3c44a4d" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", - "x-ms-ratelimit-remaining-subscription-writes" : "1196", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", + "x-ms-ratelimit-remaining-subscription-reads" : "11991", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:30 GMT", - "x-ms-correlation-request-id" : "4850f07e-66d6-4376-a653-0dd6a150585d", + "Date" : "Wed, 18 Nov 2020 02:38:36 GMT", + "x-ms-correlation-request-id" : "6f71a53d-c3e8-400d-b53d-a31225b9014d", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043431Z:4850f07e-66d6-4376-a653-0dd6a150585d", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023837Z:6f71a53d-c3e8-400d-b53d-a31225b9014d", "Expires" : "-1", - "Content-Length" : "410", - "x-ms-request-id" : "3fe8ba60-11dd-41bd-982b-d3c19b63114d", - "Body" : "{\r\n \"name\":\"origin1\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/origins/origin1\",\"type\":\"Microsoft.Cdn/profiles/endpoints/origins\",\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\",\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n}", - "x-ms-client-request-id" : "a5d16856-f9fe-4455-bf17-8db3d9a49e2d", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "61", + "x-ms-request-id" : "2e0f6260-41a6-4714-878d-8d6832bf0d34", + "Body" : "{\"status\":\"Succeeded\",\"error\":{\"code\":\"None\",\"message\":null}}", + "x-ms-client-request-id" : "a57f99c5-8b0a-400c-b2df-5376c3c44a4d", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { - "Method" : "PATCH", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c?api-version=2017-10-12", + "Method" : "GET", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains/customdomain73618cf5c830ee9794064?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "aa2e73dc-a7b6-4251-8cd2-18e3171a67ec", - "Content-Type" : "application/json" + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources.fluentcore.policy/null (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "9eeba346-410f-4183-99e0-baaeceeecdfd" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", + "x-ms-ratelimit-remaining-subscription-reads" : "11998", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:37 GMT", - "x-ms-correlation-request-id" : "f8e0a6ad-86eb-455a-ab1d-d10ace189cac", + "Date" : "Wed, 18 Nov 2020 02:38:38 GMT", + "x-ms-correlation-request-id" : "d862cff6-a373-4f20-822f-3b07f317a8be", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", - "x-ms-ratelimit-remaining-subscription-resource-requests" : "98", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043438Z:f8e0a6ad-86eb-455a-ab1d-d10ace189cac", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023839Z:d862cff6-a373-4f20-822f-3b07f317a8be", "Expires" : "-1", - "Content-Length" : "1086", - "x-ms-request-id" : "aadfce86-fa04-4239-9716-3aa2fbd204bb", - "Body" : "{\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Succeeded\",\"resourceState\":\"Running\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n {\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"properties\":{\r\n \"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null\r\n }\r\n }\r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n}", - "x-ms-client-request-id" : "aa2e73dc-a7b6-4251-8cd2-18e3171a67ec", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "565", + "x-ms-request-id" : "ecb007c7-0e99-4021-a954-b1b2542cdf4f", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customdomains/customdomain73618cf5c830ee9794064\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null,\"resourceState\":\"Active\",\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\",\"customHttpsParameters\":null,\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "9eeba346-410f-4183-99e0-baaeceeecdfd", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "d40ac918-c26f-4e34-88b1-1eea9f489342", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "57d8d4c1-f83b-4526-ae52-a10f43276123", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:39 GMT", - "x-ms-correlation-request-id" : "88165bb1-f2c3-47ec-9981-ace3e4967af6", + "Date" : "Wed, 18 Nov 2020 02:38:39 GMT", + "x-ms-correlation-request-id" : "071a5afe-0933-4889-b96d-5e4a10756eb1", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", - "x-ms-ratelimit-remaining-subscription-resource-requests" : "47", + "x-ms-ratelimit-remaining-subscription-resource-requests" : "49", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043440Z:88165bb1-f2c3-47ec-9981-ace3e4967af6", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023839Z:071a5afe-0933-4889-b96d-5e4a10756eb1", "Expires" : "-1", - "Content-Length" : "376", - "x-ms-request-id" : "413a57d9-1ed5-4e97-8c5e-92f8facbc32e", - "Body" : "{\r\n \"name\":\"jsdkcdnp345771cea4\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4\",\"type\":\"Microsoft.Cdn/profiles\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"sku\":{\r\n \"name\":\"Standard_Akamai\"\r\n },\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\"\r\n }\r\n}", - "x-ms-client-request-id" : "d40ac918-c26f-4e34-88b1-1eea9f489342", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "340", + "x-ms-request-id" : "ee640aa6-efb4-40e3-ab55-d6c5e31d97d6", + "Body" : "{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c\",\"type\":\"Microsoft.Cdn/profiles\",\"name\":\"jsdkcdnp14975d1d7c\",\"location\":\"WestUs\",\"tags\":{},\"sku\":{\"name\":\"Standard_Akamai\"},\"properties\":{\"resourceState\":\"Active\",\"provisioningState\":\"Succeeded\"}}", + "x-ms-client-request-id" : "57d8d4c1-f83b-4526-ae52-a10f43276123", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "0471382f-b6dd-40e1-b64a-292acb2c0bcf", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "1f8a5ec9-fbef-4dbc-a0bc-45be98bfcaa5", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:40 GMT", - "x-ms-correlation-request-id" : "9f3e92c5-89f6-4411-baa6-bb0975ca879d", + "Date" : "Wed, 18 Nov 2020 02:38:40 GMT", + "x-ms-correlation-request-id" : "96dbab04-caa5-4384-a6c5-a9d5c1bd60be", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "x-ms-ratelimit-remaining-subscription-resource-requests" : "46", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043441Z:9f3e92c5-89f6-4411-baa6-bb0975ca879d", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023840Z:96dbab04-caa5-4384-a6c5-a9d5c1bd60be", "Expires" : "-1", - "Content-Length" : "1202", - "x-ms-request-id" : "f4a5d107-ee57-4dac-93cb-3323709b1d5c", - "Body" : "{\r\n \"value\":[\r\n {\r\n \"name\":\"jsdkcdne44223f237c\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"tags\":{\r\n \r\n },\"location\":\"WestUs\",\"properties\":{\r\n \"hostName\":\"jsdkcdne44223f237c.azureedge.net\",\"originHostHeader\":null,\"provisioningState\":\"Succeeded\",\"resourceState\":\"Running\",\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"originPath\":null,\"origins\":[\r\n {\r\n \"name\":\"origin1\",\"properties\":{\r\n \"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null\r\n }\r\n }\r\n ],\"customDomains\":[\r\n {\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"properties\":{\r\n \"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null\r\n }\r\n }\r\n ],\"contentTypesToCompress\":[\r\n \r\n ],\"isCompressionEnabled\":false,\"optimizationType\":null,\"probePath\":null,\"geoFilters\":[\r\n \r\n ],\"deliveryPolicy\":null\r\n }\r\n }\r\n ]\r\n}", - "x-ms-client-request-id" : "0471382f-b6dd-40e1-b64a-292acb2c0bcf", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "1240", + "x-ms-request-id" : "9d915d8f-0846-4672-bf81-ac6af15bd100", + "Body" : "{\"value\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af\",\"type\":\"Microsoft.Cdn/profiles/endpoints\",\"name\":\"jsdkcdne15830981af\",\"location\":\"WestUs\",\"tags\":{},\"properties\":{\"hostName\":\"jsdkcdne15830981af.azureedge.net\",\"originHostHeader\":null,\"originPath\":null,\"contentTypesToCompress\":[],\"isCompressionEnabled\":false,\"isHttpAllowed\":true,\"isHttpsAllowed\":true,\"queryStringCachingBehavior\":\"IgnoreQueryString\",\"optimizationType\":null,\"probePath\":null,\"origins\":[{\"name\":\"origin1\",\"properties\":{\"hostName\":\"www.someDomain.net\",\"httpPort\":null,\"httpsPort\":null,\"originHostHeader\":null,\"priority\":null,\"weight\":null,\"enabled\":true,\"privateLinkAlias\":null,\"privateLinkResourceId\":null,\"privateLinkLocation\":null,\"privateEndpointStatus\":null,\"privateLinkApprovalMessage\":null}}],\"originGroups\":[],\"defaultOriginGroup\":null,\"customDomains\":[{\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null}}],\"geoFilters\":[],\"deliveryPolicy\":null,\"urlSigningKeys\":[],\"webApplicationFirewallPolicyLink\":null,\"resourceState\":\"Running\",\"provisioningState\":\"Succeeded\"}}]}", + "x-ms-client-request-id" : "1f8a5ec9-fbef-4dbc-a0bc-45be98bfcaa5", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "8cc20a77-18c9-4150-849d-704880d77696", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "936a6c96-b11f-47fa-bf2f-b4caac2fb4cf", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11990", + "x-ms-ratelimit-remaining-subscription-reads" : "11997", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:43 GMT", - "x-ms-correlation-request-id" : "674a6653-78cb-4817-9afb-78c1ae8d662c", + "Date" : "Wed, 18 Nov 2020 02:38:41 GMT", + "x-ms-correlation-request-id" : "869bb00c-5783-498a-ae08-7376ef9394f5", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043443Z:674a6653-78cb-4817-9afb-78c1ae8d662c", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023842Z:869bb00c-5783-498a-ae08-7376ef9394f5", "Expires" : "-1", - "Content-Length" : "620", - "x-ms-request-id" : "b8a67ff3-e514-490d-9ace-e39c2662e237", - "Body" : "{\r\n \"value\":[\r\n {\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customdomains/customdomaintestmanagecdnprofilea5e65263ef0da\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\",\"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null,\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\"\r\n }\r\n }\r\n ]\r\n}", - "x-ms-client-request-id" : "8cc20a77-18c9-4150-849d-704880d77696", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "577", + "x-ms-request-id" : "11489f03-4ba9-4a5c-939a-909fe0e46e20", + "Body" : "{\"value\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customdomains/customdomain73618cf5c830ee9794064\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null,\"resourceState\":\"Active\",\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\",\"customHttpsParameters\":null,\"provisioningState\":\"Succeeded\"}}]}", + "x-ms-client-request-id" : "936a6c96-b11f-47fa-bf2f-b4caac2fb4cf", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customDomains?api-version=2017-10-12", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customDomains?api-version=2020-04-15", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn.fluent/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "3d058ce3-fb9f-4696-9adb-a2b5edb1c72f", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.cdn/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "86f7f01c-3434-42de-9f02-907e35e7d885", "Content-Type" : "application/json" }, "Response" : { - "Server" : "Microsoft-IIS/10.0", + "Server" : "Kestrel", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "retry-after" : "0", - "x-ms-ratelimit-remaining-subscription-reads" : "11989", + "x-ms-ratelimit-remaining-subscription-reads" : "11996", "StatusCode" : "200", - "Date" : "Fri, 11 Sep 2020 04:34:44 GMT", - "x-ms-correlation-request-id" : "abed429f-441e-43c5-a4fb-7505b629e15e", + "Date" : "Wed, 18 Nov 2020 02:38:43 GMT", + "x-ms-correlation-request-id" : "7d9f3fa9-05e0-4171-9519-0c7774175ccb", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043444Z:abed429f-441e-43c5-a4fb-7505b629e15e", - "X-AspNet-Version" : "4.0.30319", - "OData-Version" : "4.0", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023843Z:7d9f3fa9-05e0-4171-9519-0c7774175ccb", "Expires" : "-1", - "Content-Length" : "620", - "x-ms-request-id" : "a87a86ff-0d2b-49c7-a96e-daca973c8398", - "Body" : "{\r\n \"value\":[\r\n {\r\n \"name\":\"customdomaintestmanagecdnprofilea5e65263ef0da\",\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399/providers/Microsoft.Cdn/profiles/jsdkcdnp345771cea4/endpoints/jsdkcdne44223f237c/customdomains/customdomaintestmanagecdnprofilea5e65263ef0da\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"properties\":{\r\n \"provisioningState\":\"Succeeded\",\"resourceState\":\"Active\",\"hostName\":\"sample.jsdkcdn935008.com\",\"validationData\":null,\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\"\r\n }\r\n }\r\n ]\r\n}", - "x-ms-client-request-id" : "3d058ce3-fb9f-4696-9adb-a2b5edb1c72f", - "X-Powered-By" : "ASP.NET", - "Content-Type" : "application/json; odata.metadata=minimal" + "Content-Length" : "577", + "x-ms-request-id" : "39c87686-e599-4854-8e5b-67c4cb6cd226", + "Body" : "{\"value\":[{\"id\":\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d/providers/Microsoft.Cdn/profiles/jsdkcdnp14975d1d7c/endpoints/jsdkcdne15830981af/customdomains/customdomain73618cf5c830ee9794064\",\"type\":\"Microsoft.Cdn/profiles/endpoints/customdomains\",\"name\":\"customdomain73618cf5c830ee9794064\",\"properties\":{\"hostName\":\"sample.jsdkcdn298084.com\",\"validationData\":null,\"resourceState\":\"Active\",\"customHttpsProvisioningState\":\"Disabled\",\"customHttpsProvisioningSubstate\":\"None\",\"customHttpsParameters\":null,\"provisioningState\":\"Succeeded\"}}]}", + "x-ms-client-request-id" : "86f7f01c-3434-42de-9f02-907e35e7d885", + "Content-Type" : "application/json; charset=utf-8" }, "Exception" : null }, { "Method" : "DELETE", - "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv64403679399?api-version=2020-06-01", + "Uri" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/rgnemv953463e239d?api-version=2020-06-01", "Headers" : { - "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources/2.0.0-beta.5 (11.0.8; Windows 10; 10.0)", - "x-ms-client-request-id" : "c92ee57e-86fd-4520-9f65-4e22e8cba26b", + "User-Agent" : "azsdk-java-com.azure.resourcemanager.resources/2.1.0-beta.1 (14.0.2; Linux; 5.4.0-52-generic)", + "x-ms-client-request-id" : "d92ce5aa-b0fb-463b-a9df-c5b5a233f89e", "Content-Type" : "application/json" }, "Response" : { "x-ms-ratelimit-remaining-subscription-deletes" : "14999", "X-Content-Type-Options" : "nosniff", + "Connection" : "keep-alive", "Pragma" : "no-cache", "StatusCode" : "202", - "Date" : "Fri, 11 Sep 2020 04:34:48 GMT", - "x-ms-correlation-request-id" : "9750e28e-6f6b-4fcf-8d04-c8ae9147d070", + "Date" : "Wed, 18 Nov 2020 02:38:46 GMT", + "x-ms-correlation-request-id" : "c8a7e813-a36c-403d-a399-c6dc26fde570", "Strict-Transport-Security" : "max-age=31536000; includeSubDomains", "Retry-After" : "0", "Cache-Control" : "no-cache", - "x-ms-routing-request-id" : "SOUTHEASTASIA:20200911T043448Z:9750e28e-6f6b-4fcf-8d04-c8ae9147d070", + "x-ms-routing-request-id" : "SOUTHEASTASIA:20201118T023847Z:c8a7e813-a36c-403d-a399-c6dc26fde570", "Expires" : "-1", "Content-Length" : "0", - "x-ms-request-id" : "9750e28e-6f6b-4fcf-8d04-c8ae9147d070", - "Location" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1SR05FTVY2NDQwMzY3OTM5OS1XRVNUVVMiLCJqb2JMb2NhdGlvbiI6Indlc3R1cyJ9?api-version=2020-06-01" + "x-ms-request-id" : "c8a7e813-a36c-403d-a399-c6dc26fde570", + "Location" : "http://localhost:1234/subscriptions/00000000-0000-0000-0000-000000000000/operationresults/eyJqb2JJZCI6IlJFU09VUkNFR1JPVVBERUxFVElPTkpPQi1SR05FTVY5NTM0NjNFMjM5RC1XRVNUVVMiLCJqb2JMb2NhdGlvbiI6Indlc3R1cyJ9?api-version=2020-06-01" }, "Exception" : null } ], - "variables" : [ "rgnemv64403679399", "jsdkcdn935008", "jsdkcdnp345771cea4", "jsdkcdne44223f237c", "customdomaintestmanagecdnprofilea5e65263ef0da" ] + "variables" : [ "rgnemv953463e239d", "jsdkcdn298084", "jsdkcdnp14975d1d7c", "jsdkcdne15830981af", "customdomain73618cf5c830ee9794064" ] } \ No newline at end of file From 398febfe2680f17c515c7bccbf27d2ed6c978bd6 Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Wed, 18 Nov 2020 13:38:01 +0800 Subject: [PATCH 7/7] update readme version --- sdk/resourcemanager/README.md | 2 +- sdk/resourcemanager/azure-resourcemanager-samples/README.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/sdk/resourcemanager/README.md b/sdk/resourcemanager/README.md index 6612202a1f55..373b8460efde 100644 --- a/sdk/resourcemanager/README.md +++ b/sdk/resourcemanager/README.md @@ -28,7 +28,7 @@ If you are an existing user of the older version of Azure management library for com.azure.resourcemanager azure-resourcemanager - 2.0.0-beta.5 + 2.0.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/README.md b/sdk/resourcemanager/azure-resourcemanager-samples/README.md index d927a16ffd87..a4947dc6a68b 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/README.md +++ b/sdk/resourcemanager/azure-resourcemanager-samples/README.md @@ -17,7 +17,7 @@ For documentation on how to use this package, please see [Azure Management Libra com.azure.resourcemanager azure-resourcemanager - 2.0.0-beta.5 + 2.0.0 ``` [//]: # ({x-version-update-end})