From 2756f500460f587abbaa4209e43bbc1e82b0107b Mon Sep 17 00:00:00 2001 From: Tanyi Chen Date: Mon, 19 Oct 2020 15:26:47 +0800 Subject: [PATCH] Mgmt: GA azure, remove non-GA packages (#16499) * Remove non GA package in azure * update module-info * remove test * Remove samples * GA azure * update pom version * update README * add change log * add dns --- eng/jacoco-test-coverage/pom.xml | 2 +- eng/versioning/version_client.txt | 2 +- sdk/resourcemanager/README.md | 2 +- .../azure-resourcemanager-samples/README.md | 2 +- .../azure-resourcemanager-samples/pom.xml | 2 +- .../samples/ManageSpringCloud.java | 648 ++--- .../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 | 2088 ++++++++--------- ...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/CHANGELOG.md | 4 + .../azure-resourcemanager/README.md | 2 +- .../azure-resourcemanager/pom.xml | 52 +- .../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 +++---- 73 files changed, 11892 insertions(+), 12123 deletions(-) diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index e60bf30dacd5e..5462ac7143b86 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -275,7 +275,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.0.0-beta.5 + 2.0.0 com.azure.resourcemanager diff --git a/eng/versioning/version_client.txt b/eng/versioning/version_client.txt index 13c61cdf564e2..74b9804af9b0c 100644 --- a/eng/versioning/version_client.txt +++ b/eng/versioning/version_client.txt @@ -106,7 +106,7 @@ com.azure.spring:azure-spring-cloud-test-eventhubs;1.0.0;1.0.0 com.azure.spring:azure-spring-cloud-test-storage;1.0.0;1.0.0 com.microsoft.azure:spring-cloud-starter-azure-appconfiguration-config-test;1.2.8-beta.1;1.2.8-beta.1 com.azure:opentelemetry-exporters-azuremonitor;1.0.0-beta.1;1.0.0-beta.2 -com.azure.resourcemanager:azure-resourcemanager;2.0.0-beta.4;2.0.0-beta.5 +com.azure.resourcemanager:azure-resourcemanager;2.0.0-beta.4;2.0.0 com.azure.resourcemanager:azure-resourcemanager-appplatform;2.0.0-beta.4;2.0.0-beta.5 com.azure.resourcemanager:azure-resourcemanager-appservice;2.0.0-beta.4;2.0.0 com.azure.resourcemanager:azure-resourcemanager-authorization;2.0.0-beta.4;2.0.0 diff --git a/sdk/resourcemanager/README.md b/sdk/resourcemanager/README.md index 6b9fe2100f662..e78faafdbec4a 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 667bccfa17c91..ea16b839dbef5 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}) diff --git a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml index 6bca11c5b3297..c63b1a4f15e49 100644 --- a/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager-samples/pom.xml @@ -47,7 +47,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.0.0-beta.5 + 2.0.0 com.azure 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 78bbaeb56502f..4cce0601d20c5 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,326 +1,326 @@ // 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(); - - System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); - AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) - .withExistingResourceGroup(rgName) - .withHostName(String.format("*.%s", domainName)) - .withWildcardSku() - .withDomainVerification(domain) - .withNewKeyVault(vaultName, region) - .withAutoRenew(true) - .create(); - System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); - Utils.print(certificateOrder); - - System.out.printf("Updating 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("Updated key vault %s%n", vault.name()); - Utils.print(vault); - - Secret secret = vault.secrets().getByName(certOrderName); - - byte[] certificate = Base64.getDecoder().decode(secret.getValue()); - - String thumbprint = secret.tags().get("Thumbprint"); - if (thumbprint == null || thumbprint.isEmpty()) { - KeyStore store = KeyStore.getInstance("PKCS12"); - store.load(new ByteArrayInputStream(certificate), null); - 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) - .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(); - } - } -} +// +//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(); +// +// System.out.printf("Purchasing a certificate for *.%s and save to %s in key vault named %s ...%n", domainName, certOrderName, vaultName); +// AppServiceCertificateOrder certificateOrder = azureResourceManager.appServiceCertificateOrders().define(certOrderName) +// .withExistingResourceGroup(rgName) +// .withHostName(String.format("*.%s", domainName)) +// .withWildcardSku() +// .withDomainVerification(domain) +// .withNewKeyVault(vaultName, region) +// .withAutoRenew(true) +// .create(); +// System.out.printf("Purchased certificate: *.%s ...%n", domain.name()); +// Utils.print(certificateOrder); +// +// System.out.printf("Updating 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("Updated key vault %s%n", vault.name()); +// Utils.print(vault); +// +// Secret secret = vault.secrets().getByName(certOrderName); +// +// byte[] certificate = Base64.getDecoder().decode(secret.getValue()); +// +// String thumbprint = secret.tags().get("Thumbprint"); +// if (thumbprint == null || thumbprint.isEmpty()) { +// KeyStore store = KeyStore.getInstance("PKCS12"); +// store.load(new ByteArrayInputStream(certificate), null); +// 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) +// .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(); +// } +// } +//} 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 a0015b6863e69..f9946c5c2977a 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 1594bc31cf8c6..ec516ba797e27 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 503f313a6e43d..3da37a09d2d18 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 5e55edc6db9aa..d6b5ecc9b817b 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 a1b0be7a913a9..819c442e9f96b 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 4874462cbc868..98980c2e28292 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 3cd42d6abcf54..c70b8daf31cb4 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 93894d9ae1549..08e7392119bca 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 579db3534dc75..ea3435a9f5be1 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 5ee66d3c79b43..66acda1506490 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 04bdd63327c73..cbe3ba74c64e7 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 5c46613104440..1e792ace938c3 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 6c9c8799c6537..0d772b03415c3 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 daae7e6e38276..380cb19e1094b 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 4b864b7a212e2..f9837a513220c 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 3c9f79dff554e..afb48e0fd65f1 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 37a7697d4bc8c..ba0db7e0fb3a5 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 26411af8fc8b4..d84bedb7c2cbc 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 8830fd922ae4e..97f83eee19cb0 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 1d2547352fac9..345e691b5fa9f 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 c913261f2413e..f4e3e407c3e72 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,18 +21,13 @@ 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; @@ -59,15 +54,6 @@ 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; @@ -77,8 +63,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.MxRecordSet; import com.azure.resourcemanager.dns.models.MxRecord; +import com.azure.resourcemanager.dns.models.MxRecordSet; import com.azure.resourcemanager.dns.models.NsRecordSet; import com.azure.resourcemanager.dns.models.PtrRecordSet; import com.azure.resourcemanager.dns.models.SoaRecord; @@ -87,13 +73,6 @@ 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; @@ -161,45 +140,12 @@ 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; @@ -720,58 +666,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 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("', "); +// /** +// * 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()); +// } - System.out.println(redisKeys.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. @@ -1166,80 +1112,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. @@ -1375,156 +1321,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). @@ -1736,277 +1682,277 @@ 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 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 the passed firewall rule. + * Print an application gateway. * - * @param firewallRule firewall rule to be printed. + * @param resource an application gateway */ - 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()); + 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(); @@ -2290,215 +2236,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. @@ -2821,193 +2767,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()); +// } /** @@ -3249,83 +3195,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 44d3ea66a507a..253e0d36daede 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 804dc1f4d91e5..078c286373485 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 7a82ad27aec93..317422099d5a1 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 1584706ef1ecf..12733d812d93f 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 d6f1f5fa3605b..4b4bb3cb503d1 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 0e9c7de77bc58..457403b4dcd02 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 2028b0e936815..c1954d3f87a2f 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 4e954e90dfc25..50933ab1adbeb 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 5913b30e4ab82..458920d6c1274 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.STANDARD_D3_V2)); - } - - 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.STANDARD_D3_V2)); +// } +// +// 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 6e3be306b9657..3a05b860f9cc9 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 64a97ce582882..54285cf7fd435 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 e784b4bca0246..4939a4f19cb8f 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 86873a4a71d6d..54e27e46b893d 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 7adeb2c39ad28..9aa55ab08ec98 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 5e20ea526e6c0..1bacd29f8e3e9 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 fe86584c9ebc6..3a1416fe7f367 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 a290c6aa2c90b..04e5d5d62fb74 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 afe7e11321e89..54245f9710717 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.STANDARD_A1); - 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.STANDARD_A1); +// 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 77dfaa7d7effc..7ef555aaea4d4 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 6ffb40772f976..a9610b11b2bc2 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,25 +3,15 @@ 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 3932cac0f16e0..e652a35bbb32e 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,19 +15,15 @@ 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; @@ -76,15 +72,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 @@ -106,15 +102,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 @@ -199,15 +195,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 @@ -219,15 +215,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 8af2255cf8ffe..54f4d23b54e92 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,18 +5,13 @@ 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() { @@ -35,22 +30,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 5de7dfdc627a5..48f054d306180 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,20 +3,15 @@ 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 56c74adc50edc..7403afdfbf796 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,14 +3,10 @@ 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 dc68ba20b2028..73eea39cdde80 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,48 +3,38 @@ 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 41e704a21646d..dd18eeef4ee30 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,33 +3,25 @@ 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 16a0ae07982f8..3501e5614f3e3 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,25 +2,19 @@ // 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 940cc55005e7e..588634cfe5b08 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,7 +3,6 @@ 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; @@ -38,10 +37,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 56ac9790a2642..a712e86cfab0e 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,13 +2,9 @@ // 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 8bbe21fd08059..946715763146f 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,13 +3,9 @@ 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 acd2b60611e66..cf6c671c147db 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,58 +3,49 @@ 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 7e740d4a0609f..fe924e8dfc14f 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,117 +3,98 @@ 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 ef52aa6ab02f1..4cee8c0642b27 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,27 +3,19 @@ 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/CHANGELOG.md b/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md index e870ece594c98..c639d698990fe 100644 --- a/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md +++ b/sdk/resourcemanager/azure-resourcemanager/CHANGELOG.md @@ -1,5 +1,9 @@ # Release History +## 2.0.0 (2020-10-19) + +- Removed non-GA packages + ## 2.0.0-beta.5 (2020-10-19) - Renamed `Azure` to `AzureResourceManager` diff --git a/sdk/resourcemanager/azure-resourcemanager/README.md b/sdk/resourcemanager/azure-resourcemanager/README.md index 7d41c17eae22b..1735fa7af93c5 100644 --- a/sdk/resourcemanager/azure-resourcemanager/README.md +++ b/sdk/resourcemanager/azure-resourcemanager/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}) diff --git a/sdk/resourcemanager/azure-resourcemanager/pom.xml b/sdk/resourcemanager/azure-resourcemanager/pom.xml index f70996907c3d5..b222bb539eee2 100644 --- a/sdk/resourcemanager/azure-resourcemanager/pom.xml +++ b/sdk/resourcemanager/azure-resourcemanager/pom.xml @@ -15,7 +15,7 @@ com.azure.resourcemanager azure-resourcemanager - 2.0.0-beta.5 + 2.0.0 jar Microsoft Azure SDK for Management @@ -80,11 +80,6 @@ azure-resourcemanager-msi 2.0.0 - - com.azure.resourcemanager - azure-resourcemanager-sql - 2.0.0-beta.5 - com.azure.resourcemanager azure-resourcemanager-authorization @@ -110,56 +105,11 @@ azure-resourcemanager-monitor 2.0.0 - - com.azure.resourcemanager - azure-resourcemanager-containerregistry - 2.0.0-beta.5 - com.azure.resourcemanager azure-resourcemanager-dns 2.0.0 - - 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 d005c7a158941..ec5e29f5419ea 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,8 +6,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.http.HttpPipeline; import com.azure.core.management.AzureEnvironment; -import com.azure.resourcemanager.appplatform.AppPlatformManager; -import com.azure.resourcemanager.appplatform.models.SpringServices; +import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.appservice.AppServiceManager; import com.azure.resourcemanager.appservice.models.AppServiceCertificateOrders; import com.azure.resourcemanager.appservice.models.AppServiceCertificates; @@ -22,8 +21,6 @@ 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; @@ -37,22 +34,12 @@ 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; @@ -82,14 +69,9 @@ 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; @@ -102,10 +84,6 @@ 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; @@ -113,8 +91,6 @@ 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; @@ -126,24 +102,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; @@ -360,24 +336,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()) @@ -390,12 +366,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(); @@ -630,24 +606,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() { @@ -684,17 +660,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 @@ -708,25 +684,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() { @@ -781,26 +757,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() { @@ -832,13 +808,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 c19067d43344c..c1b7d9d692946 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 45ff14ad45769..69c0dbf86714c 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,8 +9,9 @@ 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.resourcemanager.authorization.models.BuiltInRole; +import com.azure.core.management.profile.AzureProfile; import com.azure.resourcemanager.compute.models.CachingTypes; import com.azure.resourcemanager.compute.models.KnownLinuxVirtualMachineImage; import com.azure.resourcemanager.compute.models.PowerState; @@ -20,12 +21,6 @@ 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; @@ -43,13 +38,8 @@ 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.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.arm.implementation.AzureConfigurableImpl; import com.azure.resourcemanager.resources.fluentcore.utils.HttpPipelineProvider; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import com.azure.resourcemanager.resources.models.Deployment; @@ -60,6 +50,15 @@ 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; @@ -69,18 +68,9 @@ 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; @@ -1095,16 +1085,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 { @@ -1117,15 +1107,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 { @@ -1137,145 +1127,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 72047f7a3e6ae..dc41815b244e4 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 435a4212f5314..b1ab2d4a95f5d 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 a33e1a9a117e9..934bee46149d9 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 c31fdd62a87eb..16b2a66df11bb 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 06afd627b6a9f..da502a1e267bf 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 42e663849d927..588beca79aa25 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 f0d9816d8828c..fdf62b3c0de11 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()); +// } +//}