Java Code Examples for com.microsoft.azure.management.resources.fluentcore.utils.SdkContext#randomResourceName()

The following examples show how to use com.microsoft.azure.management.resources.fluentcore.utils.SdkContext#randomResourceName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ApplicationGatewayBackendHttpConfigurationImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public ApplicationGatewayBackendHttpConfigurationImpl withAuthenticationCertificateFromBase64(String base64Data) {
    if (base64Data == null) {
        return this;
    }

    String certName = null;
    for (ApplicationGatewayAuthenticationCertificate cert : this.parent().authenticationCertificates().values()) {
        if (cert.data().contentEquals(base64Data)) {
            certName = cert.name();
            break;
        }
    }

    // If matching cert reference not found, create a new one
    if (certName == null) {
        certName = SdkContext.randomResourceName("cert", 20);
        this.parent().defineAuthenticationCertificate(certName)
            .fromBase64(base64Data)
            .attach();
    }

    return this.withAuthenticationCertificate(certName).withHttps();
}
 
Example 2
Source File: DeployUsingARMTemplateWithTags.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private static String getTemplate() throws IllegalAccessException, JsonProcessingException, IOException {
    final String hostingPlanName = SdkContext.randomResourceName("hpRSAT", 24);
    final String webappName = SdkContext.randomResourceName("wnRSAT", 24);
    final InputStream embeddedTemplate;
    embeddedTemplate = DeployUsingARMTemplate.class.getResourceAsStream("/templateValue.json");

    final ObjectMapper mapper = new ObjectMapper();
    final JsonNode tmp = mapper.readTree(embeddedTemplate);

    validateAndAddFieldValue("string", hostingPlanName, "hostingPlanName", null, tmp);
    validateAndAddFieldValue("string", webappName, "webSiteName", null, tmp);
    validateAndAddFieldValue("string", "B1", "skuName", null, tmp);
    validateAndAddFieldValue("int", "1", "skuCapacity", null, tmp);

    return tmp.toString();
}
 
Example 3
Source File: KeyTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private Vault createVault() throws Exception {
    String vaultName = SdkContext.randomResourceName("vault", 20);

    ApplicationTokenCredentials credentials = ApplicationTokenCredentials.fromFile(new File(System.getenv("AZURE_AUTH_LOCATION")));

    Vault vault = keyVaultManager.vaults().define(vaultName)
            .withRegion(Region.US_WEST)
            .withNewResourceGroup(RG_NAME)
            .defineAccessPolicy()
                .forServicePrincipal(credentials.clientId())
                .allowKeyAllPermissions()
                .attach()
            .create();

    Assert.assertNotNull(vault);

    SdkContext.sleep(10000);

    return vault;
}
 
Example 4
Source File: WebAppUtils.java    From azure-gradle-plugins with MIT License 5 votes vote down vote up
public static AppServicePlan createOrGetAppServicePlan(DeployTask task, OperatingSystem os)
        throws Exception {
    AzureWebAppExtension extension = task.getAzureWebAppExtension();
    AppServicePlan plan = null;
    final String servicePlanResGrp = isNotEmpty(extension.getAppServicePlanResourceGroup())
            ? extension.getAppServicePlanResourceGroup() : extension.getResourceGroup();

    String servicePlanName = extension.getAppServicePlanName();
    if (isNotEmpty(servicePlanName)) {
        plan = task.getAzureClient().appServices().appServicePlans()
                .getByResourceGroup(servicePlanResGrp, servicePlanName);
    } else {
        servicePlanName = SdkContext.randomResourceName("ServicePlan", 18);
    }

    final Azure azure = task.getAzureClient();
    if (plan == null) {
        task.getLogger().quiet(String.format(CREATE_SERVICE_PLAN, servicePlanName));

        final AppServicePlan.DefinitionStages.WithGroup withGroup = azure.appServices().appServicePlans()
                .define(servicePlanName)
                .withRegion(extension.getRegion());

        final AppServicePlan.DefinitionStages.WithPricingTier withPricingTier
                = azure.resourceGroups().contain(servicePlanResGrp) ?
                withGroup.withExistingResourceGroup(servicePlanResGrp) :
                withGroup.withNewResourceGroup(servicePlanResGrp);

        plan = withPricingTier.withPricingTier(extension.getPricingTier())
                .withOperatingSystem(os).create();

        task.getLogger().quiet(SERVICE_PLAN_CREATED);
    } else {
        task.getLogger().quiet(String.format(SERVICE_PLAN_EXIST, servicePlanName, servicePlanResGrp));
    }

    return plan;
}
 
Example 5
Source File: DeploymentsTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
protected void initializeClients(RestClient restClient, String defaultSubscription, String domain) {
    super.initializeClients(restClient, defaultSubscription, domain);
    testId = SdkContext.randomResourceName("", 9);
    resourceGroups = resourceClient.resourceGroups();
    rgName = "rg" + testId;
    resourceGroup = resourceGroups.define(rgName)
            .withRegion(Region.US_SOUTH_CENTRAL)
            .create();
}
 
Example 6
Source File: KeyTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Ignore("Mock framework doesn't support data plane")
public void canEncryptAndDecrypt() throws Exception {
    Vault vault = createVault();
    String keyName = SdkContext.randomResourceName("key", 20);

    KeyPair keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();

    Key key = vault.keys().define(keyName)
            .withLocalKeyToImport(JsonWebKey.fromRSA(keyPair))
            .create();

    Assert.assertNotNull(key);

    String s = "the quick brown fox jumps over the lazy dog";
    byte[] data = s.getBytes();

    // Remote encryption
    byte[] encrypted = key.encrypt(JsonWebKeyEncryptionAlgorithm.RSA1_5, data);
    Assert.assertNotNull(encrypted);

    byte[] decrypted = key.decrypt(JsonWebKeyEncryptionAlgorithm.RSA1_5, encrypted);
    Assert.assertEquals(s, new String(decrypted));

    // Local encryption
    Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-1AndMGF1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
    encrypted = cipher.doFinal(data);

    decrypted = key.decrypt(JsonWebKeyEncryptionAlgorithm.RSA_OAEP, encrypted);
    Assert.assertEquals(s, new String(decrypted));
}
 
Example 7
Source File: ManageManagedDisks.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static VirtualMachine prepareSpecializedManagedVirtualMachine(Azure azure, Region region, String rgName) {
    final String userName = "tirekicker";
    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
    final String password = "12NewPA$$w0rd!";
    final String linuxVMName1 = SdkContext.randomResourceName("vm" + "-", 10);
    final String publicIPDnsLabel = SdkContext.randomResourceName("pip" + "-", 20);

    VirtualMachine linuxVM = azure.virtualMachines().define(linuxVMName1)
            .withRegion(region)
            .withNewResourceGroup(rgName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withNewPrimaryPublicIPAddress(publicIPDnsLabel)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername(userName)
            .withRootPassword(password)
            .withNewDataDisk(100)
            .withNewDataDisk(200)
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .create();

    // De-provision the virtual machine
    deprovisionAgentInLinuxVM(linuxVM.getPrimaryPublicIPAddress().fqdn(), 22, userName, password);
    System.out.println("Deallocate VM: " + linuxVM.id());
    linuxVM.deallocate();
    System.out.println("Deallocated VM: " + linuxVM.id() + "; state = " + linuxVM.powerState());
    System.out.println("Generalize VM: " + linuxVM.id());
    linuxVM.generalize();
    System.out.println("Generalized VM: " + linuxVM.id());
    return linuxVM;
}
 
Example 8
Source File: VirtualMachineBootDiagnosticsTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void bootDiagnosticsShouldUseUnManagedDisksExplicitStorage() {
    final String storageName = SdkContext.randomResourceName("st", 14);
    StorageAccount storageAccount = storageManager.storageAccounts()
            .define(storageName)
            .withRegion(REGION)
            .withNewResourceGroup(RG_NAME)
            .create();

    VirtualMachine virtualMachine = computeManager.virtualMachines()
            .define(VMNAME)
            .withRegion(REGION)
            .withNewResourceGroup(RG_NAME)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withoutPrimaryPublicIPAddress()
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("Foo12")
            .withRootPassword("abc!@#F0orL")
            .withUnmanagedDisks()
            .withBootDiagnostics()
            .withExistingStorageAccount(storageAccount) // This storage account must be shared by disk and boot diagnostics
            .create();

    Assert.assertNotNull(virtualMachine);
    Assert.assertTrue(virtualMachine.isBootDiagnosticsEnabled());
    Assert.assertNotNull(virtualMachine.bootDiagnosticsStorageUri());
    Assert.assertTrue(virtualMachine.bootDiagnosticsStorageUri().contains(storageName));
}
 
Example 9
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void testManagedDiskVMUpdate() throws Exception {
    final String rgName = SdkContext.randomResourceName("rg", 13);
    final String linuxVM2Name = SdkContext.randomResourceName("vm" + "-", 10);
    final String linuxVM2Pip = SdkContext.randomResourceName("pip" + "-", 18);
    VirtualMachine linuxVM2 = azure.virtualMachines().define(linuxVM2Name)
            .withRegion(Region.US_EAST)
            .withNewResourceGroup(rgName)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withNewPrimaryPublicIPAddress(linuxVM2Pip)
            .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS)
            .withRootUsername("tester")
            .withRootPassword("Abcdef.123456!")
            // Begin: Managed data disks
            .withNewDataDisk(100)
            .withNewDataDisk(100, 1, CachingTypes.READ_WRITE)
            // End: Managed data disks
            .withSize(VirtualMachineSizeTypes.STANDARD_D3_V2)
            .create();

    linuxVM2.deallocate();
    linuxVM2.update()
            .withoutDataDisk(2)
            .withNewDataDisk(200)
            .apply();
    azure.resourceGroups().beginDeleteByName(rgName);
}
 
Example 10
Source File: ManageManagedDisks.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static Network prepareNetwork(Azure azure, Region region, String rgName) {
    final String vnetName = SdkContext.randomResourceName("vnet", 24);

    Network network = azure.networks().define(vnetName)
            .withRegion(region)
            .withNewResourceGroup(rgName)
            .withAddressSpace("172.16.0.0/16")
            .defineSubnet("subnet1")
            .withAddressPrefix("172.16.1.0/24")
            .attach()
            .create();
    return network;
}
 
Example 11
Source File: ManageLinuxWebAppStorageAccountConnection.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    // New resources
    final String suffix         = ".azurewebsites.net";
    final String app1Name       = SdkContext.randomResourceName("webapp1-", 20);
    final String app1Url        = app1Name + suffix;
    final String storageName    = SdkContext.randomResourceName("jsdkstore", 20);
    final String containerName  = SdkContext.randomResourceName("jcontainer", 20);
    final String rgName         = SdkContext.randomResourceName("rg1NEMV_", 24);

    try {

        //============================================================
        // Create a storage account for the web app to use

        System.out.println("Creating storage account " + storageName + "...");

        StorageAccount storageAccount = azure.storageAccounts().define(storageName)
                .withRegion(Region.US_WEST)
                .withNewResourceGroup(rgName)
                .create();

        String accountKey = storageAccount.getKeys().get(0).value();

        String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s",
                storageAccount.name(), accountKey);

        System.out.println("Created storage account " + storageAccount.name());

        //============================================================
        // Upload a few files to the storage account blobs

        System.out.println("Uploading 2 blobs to container " + containerName + "...");

        CloudBlobContainer container = setUpStorageAccount(connectionString, containerName);
        uploadFileToContainer(container, "helloworld.war", ManageLinuxWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath());
        uploadFileToContainer(container, "install_apache.sh", ManageLinuxWebAppStorageAccountConnection.class.getResource("/install_apache.sh").getPath());

        System.out.println("Uploaded 2 blobs to container " + container.getName());

        //============================================================
        // Create a web app with a new app service plan

        System.out.println("Creating web app " + app1Name + "...");

        WebApp app1 = azure.webApps().define(app1Name)
                .withRegion(Region.US_WEST)
                .withExistingResourceGroup(rgName)
                .withNewLinuxPlan(PricingTier.STANDARD_S1)
                .withBuiltInImage(RuntimeStack.TOMCAT_8_5_JRE8)
                .withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM)
                .withAppSetting("storage.containerName", containerName)
                .create();

        System.out.println("Created web app " + app1.name());
        Utils.print(app1);

        //============================================================
        // Deploy a web app that connects to the storage account
        // Source code: https://github.com/jianghaolu/azure-samples-blob-explorer

        System.out.println("Deploying azure-samples-blob-traverser.war to " + app1Name + " through FTP...");

        Utils.uploadFileToWebApp(app1.getPublishingProfile(), "azure-samples-blob-traverser.war", ManageLinuxWebAppStorageAccountConnection.class.getResourceAsStream("/azure-samples-blob-traverser.war"));

        System.out.println("Deployment azure-samples-blob-traverser.war to web app " + app1.name() + " completed");
        Utils.print(app1);

        // warm up
        System.out.println("Warming up " + app1Url + "/azure-samples-blob-traverser...");
        curl("http://" + app1Url + "/azure-samples-blob-traverser");
        SdkContext.sleep(5000);
        System.out.println("CURLing " + app1Url + "/azure-samples-blob-traverser...");
        System.out.println(curl("http://" + app1Url + "/azure-samples-blob-traverser"));

        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.resourceGroups().beginDeleteByName(rgName);
            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();
        }
    }
    return false;
}
 
Example 12
Source File: TestTemplate.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
protected TestTemplate() {
    this.testId = SdkContext.randomResourceName("", 8);
}
 
Example 13
Source File: DeployVirtualMachineUsingARMTemplate.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    final String rgName = SdkContext.randomResourceName("rgRSAT", 24);
    final String deploymentName = SdkContext.randomResourceName("dpRSAT", 24);
    try {
        String templateJson = DeployVirtualMachineUsingARMTemplate.getTemplate();

        System.out.println(templateJson);

        //=============================================================
        // Create resource group.

        System.out.println("Creating a resource group with name: " + rgName);

        azure.resourceGroups().define(rgName)
                .withRegion(Region.US_WEST)
                .create();

        System.out.println("Created a resource group with name: " + rgName);


        //=============================================================
        // Create a deployment for an Azure App Service via an ARM
        // template.

        System.out.println("Starting a deployment for an Azure Virtual Machine with managed disks: " + deploymentName);

        azure.deployments().define(deploymentName)
                .withExistingResourceGroup(rgName)
                .withTemplate(templateJson)
                .withParameters("{}")
                .withMode(DeploymentMode.INCREMENTAL)
                .create();

        System.out.println("Started a deployment for an Azure Virtual Machine with managed disks: " + deploymentName);
        Deployment deployment = azure.deployments().getByResourceGroup(rgName, deploymentName);
        System.out.println("Current deployment status : " + deployment.provisioningState());

        while (!(deployment.provisioningState().equalsIgnoreCase("Succeeded")
                || deployment.provisioningState().equalsIgnoreCase("Failed")
                || deployment.provisioningState().equalsIgnoreCase("Cancelled"))) {
            SdkContext.sleep(10000);
            deployment = azure.deployments().getByResourceGroup(rgName, deploymentName);
            System.out.println("Current deployment status : " + deployment.provisioningState());
        }
        return true;
    } catch (Exception f) {

        System.out.println(f.getMessage());
        f.printStackTrace();

    } 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();
        }
    }
    return false;
}
 
Example 14
Source File: LoadBalancerInboundNatPoolImpl.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public LoadBalancerInboundNatPoolImpl fromNewPublicIPAddress(Creatable<PublicIPAddress> pipDefinition) {
    String frontendName = SdkContext.randomResourceName("fe", 20);
    this.parent().withNewPublicIPAddress(pipDefinition, frontendName);
    return fromFrontend(frontendName);
}
 
Example 15
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
@Ignore("Deprecated")
public void testBatchAIJob() throws Exception {
    final Region region = Region.US_EAST;
    final String groupName = SdkContext.randomResourceName("rg", 10);
    final String workspaceName = SdkContext.randomResourceName("ws", 10);
    final String clusterName = SdkContext.randomResourceName("cluster", 15);
    final String experimentName = SdkContext.randomResourceName("exp", 10);
    final String userName = "tirekicker";
    try {

        BatchAIWorkspace workspace = azure.batchAIWorkspaces().define(workspaceName)
                .withRegion(region)
                .withNewResourceGroup(groupName)
                .create();
        BatchAIExperiment experiment = workspace.experiments().define(experimentName).create();

        BatchAICluster cluster = workspace.clusters().define(clusterName)
                .withVMSize(VirtualMachineSizeTypes.STANDARD_D1_V2.toString())
                .withUserName(userName)
                .withPassword("MyPassword")
                .withAutoScale(1, 1)
                .create();
        Assert.assertEquals("resizing", cluster.allocationState().toString());
        Assert.assertEquals(userName, cluster.adminUserName());

        BatchAIJob job = experiment.jobs().define("myJob")
                .withExistingClusterId(cluster.id())
                .withNodeCount(1)
                .withStdOutErrPathPrefix("$AZ_BATCHAI_MOUNT_ROOT/azurefileshare")
                .defineCognitiveToolkit()
                    .withPythonScriptFile("$AZ_BATCHAI_INPUT_SAMPLE/ConvNet_MNIST.py")
                    .withCommandLineArgs("$AZ_BATCHAI_INPUT_SAMPLE $AZ_BATCHAI_OUTPUT_MODEL")
                    .attach()
                .withInputDirectory("SAMPLE", "$AZ_BATCHAI_MOUNT_ROOT/azurefileshare/mnistcntksample")
                .withOutputDirectory("MODEL", "$AZ_BATCHAI_MOUNT_ROOT/azurefileshare/model")
                .defineOutputDirectory("OUTPUT")
                    .withPathPrefix("$AZ_BATCHAI_MOUNT_ROOT/azurefileshare/output")
                    .withPathSuffix("suffix")
                    .attach()
                .withContainerImage("microsoft/cntk:2.1-gpu-python3.5-cuda8.0-cudnn6.0")
                .create();
        Assert.assertEquals(2,job.outputDirectories().size());
        OutputDirectory outputDirectory = null;
        for (OutputDirectory directory : job.outputDirectories()) {
            if ("OUTPUT".equalsIgnoreCase(directory.id())) {
                outputDirectory = directory;
            }
        }
        Assert.assertNotNull(outputDirectory);
        Assert.assertEquals("suffix", outputDirectory.pathSuffix().toLowerCase());

        experiment.jobs().list();

        BatchAIJob job2 = experiment.jobs().getById(job.id());
        Assert.assertEquals(cluster.id(), job2.cluster().id());

    } finally {
        azure.resourceGroups().beginDeleteByName(groupName);
    }
}
 
Example 16
Source File: TestLocalNetworkGateway.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
private void initializeResourceNames() {
    TEST_ID = SdkContext.randomResourceName("", 8);
    groupName = "rg" + TEST_ID;
    lngwName = "lngw" + TEST_ID;
}
 
Example 17
Source File: ServicePrincipalsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canCRUDServicePrincipal() throws Exception {
    String name = SdkContext.randomResourceName("ssp", 21);
    ServicePrincipal servicePrincipal = null;
    try {
        // Create
        servicePrincipal = graphRbacManager.servicePrincipals().define(name)
                .withNewApplication("http://easycreate.azure.com/" + name)
                .definePasswordCredential("sppass")
                    .withPasswordValue("StrongPass!12")
                    .attach()
                .create();
        System.out.println(servicePrincipal.id() + " - " + Joiner.on(", ").join(servicePrincipal.servicePrincipalNames()));
        Assert.assertNotNull(servicePrincipal.id());
        Assert.assertNotNull(servicePrincipal.applicationId());
        Assert.assertEquals(2, servicePrincipal.servicePrincipalNames().size());
        Assert.assertEquals(1, servicePrincipal.passwordCredentials().size());
        Assert.assertEquals(0, servicePrincipal.certificateCredentials().size());

        // Get
        servicePrincipal = graphRbacManager.servicePrincipals().getByName(name);
        Assert.assertNotNull(servicePrincipal);
        Assert.assertNotNull(servicePrincipal.applicationId());
        Assert.assertEquals(2, servicePrincipal.servicePrincipalNames().size());
        Assert.assertEquals(1, servicePrincipal.passwordCredentials().size());
        Assert.assertEquals(0, servicePrincipal.certificateCredentials().size());

        // Update
        servicePrincipal.update()
                .withoutCredential("sppass")
                .defineCertificateCredential("spcert")
                    .withAsymmetricX509Certificate()
                    .withPublicKey(ByteStreams.toByteArray(ServicePrincipalsTests.class.getResourceAsStream("/myTest.cer")))
                    .withDuration(Duration.standardDays(1))
                    .attach()
                .apply();
        Assert.assertNotNull(servicePrincipal);
        Assert.assertNotNull(servicePrincipal.applicationId());
        Assert.assertEquals(2, servicePrincipal.servicePrincipalNames().size());
        Assert.assertEquals(0, servicePrincipal.passwordCredentials().size());
        Assert.assertEquals(1, servicePrincipal.certificateCredentials().size());
    } finally {
        if (servicePrincipal != null) {
            graphRbacManager.servicePrincipals().deleteById(servicePrincipal.id());
            graphRbacManager.applications().deleteById(graphRbacManager.applications().getByName(servicePrincipal.applicationId()).id());
        }
    }
}
 
Example 18
Source File: ManageWebAppSlots.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    // New resources
    final String resourceGroupName     = SdkContext.randomResourceName("rg", 24);
    final String app1Name       = SdkContext.randomResourceName("webapp1-", 20);
    final String app2Name       = SdkContext.randomResourceName("webapp2-", 20);
    final String app3Name       = SdkContext.randomResourceName("webapp3-", 20);
    final String slotName       = "staging";

    try {

        azure.resourceGroups().define(resourceGroupName)
                .withRegion(Region.US_EAST)
                .create();

        //============================================================
        // Create 3 web apps with 3 new app service plans in different regions

        WebApp app1 = createWebApp(azure, app1Name, Region.US_EAST, resourceGroupName);
        WebApp app2 = createWebApp(azure, app2Name, Region.EUROPE_WEST, resourceGroupName);
        WebApp app3 = createWebApp(azure, app3Name, Region.ASIA_EAST, resourceGroupName);


        //============================================================
        // Create a deployment slot under each web app with auto swap

        DeploymentSlot slot1 = createSlot(slotName, app1);
        DeploymentSlot slot2 = createSlot(slotName, app2);
        DeploymentSlot slot3 = createSlot(slotName, app3);

        //============================================================
        // Deploy the staging branch to the slot

        deployToStaging(slot1);
        deployToStaging(slot2);
        deployToStaging(slot3);

        // swap back
        swapProductionBacktoSlot(slot1);
        swapProductionBacktoSlot(slot2);
        swapProductionBacktoSlot(slot3);

        return true;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } finally {
        try {
            System.out.println("Deleting Resource Group: " + resourceGroupName);
            azure.resourceGroups().beginDeleteByName(resourceGroupName);
            System.out.println("Deleted Resource Group: " + resourceGroupName);
        } catch (NullPointerException npe) {
            System.out.println("Did not create any resources in Azure. No clean up is necessary");
        } catch (Exception g) {
            g.printStackTrace();
        }
    }
    return false;
}
 
Example 19
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Override
public Network createResource(Networks networks) throws Exception {
    Region region = Region.US_EAST;
    String groupName = "rg" + this.testId;

    String networkName = SdkContext.randomResourceName("net", 15);
    String networkName2 = SdkContext.randomResourceName("net", 15);

    Creatable<Network> remoteNetworkDefinition = networks.define(networkName2)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withAddressSpace("10.1.0.0/27")
            .withSubnet("subnet3", "10.1.0.0/27");

    Creatable<Network> localNetworkDefinition = networks.define(networkName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withAddressSpace("10.0.0.0/27")
            .withSubnet("subnet1", "10.0.0.0/28")
            .withSubnet("subnet2", "10.0.0.16/28");

    CreatedResources<Network> createdNetworks = networks.create(Arrays.asList(remoteNetworkDefinition, localNetworkDefinition));
    Network localNetwork = createdNetworks.get(localNetworkDefinition.key());
    Network remoteNetwork = createdNetworks.get(remoteNetworkDefinition.key());
    Assert.assertNotNull(localNetwork);
    Assert.assertNotNull(remoteNetwork);

    // Create peering
    NetworkPeering localPeering = localNetwork.peerings().define("peer0")
        .withRemoteNetwork(remoteNetwork)

        // Optionals
        .withTrafficForwardingBetweenBothNetworks()
        .withoutAccessFromEitherNetwork()
        .withGatewayUseByRemoteNetworkAllowed()
        .create();

    // Verify local peering
    Assert.assertNotNull(localNetwork.peerings());
    Assert.assertEquals(1,  localNetwork.peerings().list().size());
    Assert.assertEquals(1, localPeering.remoteAddressSpaces().size());
    Assert.assertEquals("10.1.0.0/27", localPeering.remoteAddressSpaces().get(0));
    localPeering = localNetwork.peerings().list().get(0);
    Assert.assertNotNull(localPeering);
    Assert.assertTrue(localPeering.name().equalsIgnoreCase("peer0"));
    Assert.assertEquals(VirtualNetworkPeeringState.CONNECTED, localPeering.state());
    Assert.assertTrue(localPeering.isTrafficForwardingFromRemoteNetworkAllowed());
    Assert.assertFalse(localPeering.checkAccessBetweenNetworks());
    Assert.assertEquals(NetworkPeeringGatewayUse.BY_REMOTE_NETWORK, localPeering.gatewayUse());

    // Verify remote peering
    Assert.assertNotNull(remoteNetwork.peerings());
    Assert.assertEquals(1, remoteNetwork.peerings().list().size());
    NetworkPeering remotePeering = localPeering.getRemotePeering();
    Assert.assertNotNull(remotePeering);
    Assert.assertTrue(remotePeering.remoteNetworkId().equalsIgnoreCase(localNetwork.id()));
    Assert.assertEquals(VirtualNetworkPeeringState.CONNECTED, remotePeering.state());
    Assert.assertTrue(remotePeering.isTrafficForwardingFromRemoteNetworkAllowed());
    Assert.assertFalse(remotePeering.checkAccessBetweenNetworks());
    Assert.assertEquals(NetworkPeeringGatewayUse.NONE, remotePeering.gatewayUse());

    return localNetwork;
}
 
Example 20
Source File: ManageResourceGroup.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
/**
 * Main function which runs the actual sample.
 * @param azure instance of the azure client
 * @return true if sample runs successfully
 */
public static boolean runSample(Azure azure) {
    final String rgName = SdkContext.randomResourceName("rgRSMA", 24);
    final String rgName2 = SdkContext.randomResourceName("rgRSMA", 24);
    final String resourceTagName = SdkContext.randomResourceName("rgRSTN", 24);
    final String resourceTagValue = SdkContext.randomResourceName("rgRSTV", 24);
    try {


        //=============================================================
        // Create resource group.

        System.out.println("Creating a resource group with name: " + rgName);

        ResourceGroup resourceGroup = azure.resourceGroups().define(rgName)
                .withRegion(Region.US_WEST)
                .create();

        System.out.println("Created a resource group with name: " + rgName);


        //=============================================================
        // Update the resource group.

        System.out.println("Updating the resource group with name: " + rgName);

        resourceGroup.update()
                .withTag(resourceTagName, resourceTagValue)
                .apply();

        System.out.println("Updated the resource group with name: " + rgName);


        //=============================================================
        // Create another resource group.

        System.out.println("Creating another resource group with name: " + rgName2);

        azure.resourceGroups().define(rgName2)
                .withRegion(Region.US_WEST)
                .create();

        System.out.println("Created another resource group with name: " + rgName2);


        //=============================================================
        // List resource groups.

        System.out.println("Listing all resource groups");

        for (ResourceGroup rGroup : azure.resourceGroups().list()) {
            System.out.println("Resource group: " + rGroup.name());
        }


        //=============================================================
        // Delete a resource group.

        System.out.println("Deleting resource group: " + rgName2);

        azure.resourceGroups().beginDeleteByName(rgName2);
        return true;
    } catch (Exception f) {

        System.out.println(f.getMessage());
        f.printStackTrace();

    } finally {

        try {
            System.out.println("Deleting Resource Group: " + rgName);
            azure.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();
        }
    }
    return false;
}