com.microsoft.azure.management.resources.fluentcore.utils.SdkContext Java Examples

The following examples show how to use com.microsoft.azure.management.resources.fluentcore.utils.SdkContext. 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: ContainerGroupImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public ContainerGroupImpl withNewAzureFileShareVolume(String volumeName, String shareName) {
    if (this.newFileShares == null || this.creatableStorageAccountKey == null) {
        StorageAccount.DefinitionStages.WithGroup definitionWithGroup = this.storageManager
                .storageAccounts()
                .define(SdkContext.randomResourceName("fs", 24))
                .withRegion(this.regionName());
        Creatable<StorageAccount> creatable;
        if (this.creatableGroup != null) {
            creatable = definitionWithGroup.withNewResourceGroup(this.creatableGroup);
        } else {
            creatable = definitionWithGroup.withExistingResourceGroup(this.resourceGroupName());
        }
        this.creatableStorageAccountKey = this.addDependency(creatable);
        this.newFileShares = new HashMap<>();
    }
    this.newFileShares.put(volumeName, shareName);

    return this;
}
 
Example #2
Source File: RoleAssignmentTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Test
public void canCRUDRoleAssignment() throws Exception {
    String roleAssignmentName = SdkContext.randomUuid();
    String spName = SdkContext.randomResourceName("sp", 20);

    ServicePrincipal sp = graphRbacManager.servicePrincipals().define(spName)
            .withNewApplication("http://" + spName)
            .create();

    SdkContext.sleep(15000);

    RoleAssignment roleAssignment = graphRbacManager.roleAssignments()
            .define(roleAssignmentName)
            .forServicePrincipal(sp)
            .withBuiltInRole(BuiltInRole.CONTRIBUTOR)
            .withSubscriptionScope(resourceManager.subscriptionId())
            .create();

    Assert.assertNotNull(roleAssignment);
}
 
Example #3
Source File: DdosProtectionPlanTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Test
public void canCRUDDdosProtectionPlan() throws Exception {
    String ppName = SdkContext.randomResourceName("ddosplan", 15);

    DdosProtectionPlan pPlan = networkManager.ddosProtectionPlans().define(ppName)
            .withRegion(Region.US_SOUTH_CENTRAL)
            .withNewResourceGroup(RG_NAME)
            .withTag("tag1", "value1")
            .create();
    Assert.assertEquals("value1", pPlan.tags().get("tag1"));

    List<DdosProtectionPlan> ppList = networkManager.ddosProtectionPlans().list();
    Assert.assertTrue(ppList.size() > 0);

    ppList = networkManager.ddosProtectionPlans().listByResourceGroup(RG_NAME);
    Assert.assertTrue(ppList.size() > 0);

    networkManager.ddosProtectionPlans().deleteById(pPlan.id());
    ppList = networkManager.ddosProtectionPlans().listByResourceGroup(RG_NAME);
    Assert.assertTrue(ppList.isEmpty());
}
 
Example #4
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Tests ARM template deployments.
 * @throws IOException
 * @throws CloudException
 */
@Test
public void testDeployments() throws Exception {
    String testId = SdkContext.randomResourceName("", 8);
    List<Deployment> deployments = azure.deployments().list();
    System.out.println("Deployments: " + deployments.size());
    Deployment deployment = azure.deployments()
        .define("depl" + testId)
        .withNewResourceGroup("rg" + testId, Region.US_WEST)
        .withTemplateLink(
                "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vnet-two-subnets/azuredeploy.json",
                "1.0.0.0")
        .withParametersLink(
                "https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-vnet-two-subnets/azuredeploy.parameters.json",
                "1.0.0.0")
        .withMode(DeploymentMode.COMPLETE)
        .create();
    System.out.println("Created deployment: " + deployment.correlationId());

    azure.resourceGroups().beginDeleteByName("rg" + testId);
}
 
Example #5
Source File: AzureTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
/**
 * Tests basic generic resources retrieval.
 * @throws Exception
 */
@Test
public void testGenericResources() throws Exception {
    // Create some resources
    NetworkSecurityGroup nsg = azure.networkSecurityGroups().define(SdkContext.randomResourceName("nsg", 13))
        .withRegion(Region.US_EAST)
        .withNewResourceGroup()
        .create();
    azure.publicIPAddresses().define(SdkContext.randomResourceName("pip", 13))
        .withRegion(Region.US_EAST)
        .withExistingResourceGroup(nsg.resourceGroupName())
        .create();

    PagedList<GenericResource> resources = azure.genericResources().listByResourceGroup(nsg.resourceGroupName());
    Assert.assertEquals(2, resources.size());
    GenericResource firstResource = resources.get(0);

    GenericResource resourceById = azure.genericResources().getById(firstResource.id());
    GenericResource resourceByDetails = azure.genericResources().get(
            firstResource.resourceGroupName(),
            firstResource.resourceProviderNamespace(),
            firstResource.resourceType(),
            firstResource.name());
    Assert.assertTrue(resourceById.id().equalsIgnoreCase(resourceByDetails.id()));
    azure.resourceGroups().beginDeleteByName(nsg.resourceGroupName());
}
 
Example #6
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 #7
Source File: VirtualMachineBootDiagnosticsTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Test
public void canEnableBootDiagnosticsWithCreatableStorageOnManagedVMCreation() {
    final String storageName = SdkContext.randomResourceName("st", 14);
    Creatable<StorageAccount> creatableStorageAccount = storageManager.storageAccounts()
            .define(storageName)
            .withRegion(REGION)
            .withNewResourceGroup(RG_NAME);

    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")
            .withBootDiagnostics(creatableStorageAccount)
            .create();
    Assert.assertNotNull(virtualMachine);
    Assert.assertTrue(virtualMachine.isBootDiagnosticsEnabled());
    Assert.assertNotNull(virtualMachine.bootDiagnosticsStorageUri());
    Assert.assertTrue(virtualMachine.bootDiagnosticsStorageUri().contains(storageName));
}
 
Example #8
Source File: EventHubImpl.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
private Observable<Boolean> createContainerIfNotExistsAsync(final StorageAccount storageAccount,
                                                            final String containerName) {
    return getCloudStorageAsync(storageAccount)
            .flatMap(new Func1<CloudStorageAccount, Observable<Boolean>>() {
                @Override
                public Observable<Boolean> call(final CloudStorageAccount cloudStorageAccount) {
                    return Observable.fromCallable(new Callable<Boolean>() {
                        @Override
                        public Boolean call() {
                            CloudBlobClient blobClient = cloudStorageAccount.createCloudBlobClient();
                            try {
                                return blobClient.getContainerReference(containerName).createIfNotExists();
                            } catch (StorageException stgException) {
                                throw Exceptions.propagate(stgException);
                            } catch (URISyntaxException syntaxException) {
                                throw Exceptions.propagate(syntaxException);
                            }
                        }
                    }).subscribeOn(SdkContext.getRxScheduler());
                }
            });
}
 
Example #9
Source File: DeployUsingARMTemplateWithProgress.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 = DeployUsingARMTemplateWithProgress.class.getResourceAsStream("/templateValue.json");

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

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

    return tmp.toString();
}
 
Example #10
Source File: CosmosDBTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Test
public void CanCreateCosmosDbAzureTableAccount() {
    final String cosmosDbAccountName = SdkContext.randomResourceName("cosmosdb", 22);

    CosmosDBAccount cosmosDBAccount = cosmosDBManager.databaseAccounts()
        .define(cosmosDbAccountName)
        .withRegion(Region.US_WEST_CENTRAL)
        .withNewResourceGroup(RG_NAME)
        .withDataModelAzureTable()
        .withEventualConsistency()
        .withWriteReplication(Region.US_EAST)
        .withReadReplication(Region.US_CENTRAL)
        .withIpRangeFilter("")
        .withTag("tag1", "value1")
        .create();

    Assert.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase());
    Assert.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.GLOBAL_DOCUMENT_DB);
    Assert.assertEquals(cosmosDBAccount.capabilities().get(0).name(), "EnableTable");
    Assert.assertEquals(cosmosDBAccount.writableReplications().size(), 1);
    Assert.assertEquals(cosmosDBAccount.readableReplications().size(), 2);
    Assert.assertEquals(cosmosDBAccount.defaultConsistencyLevel(), DefaultConsistencyLevel.EVENTUAL);
}
 
Example #11
Source File: CosmosDBTests.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Test
public void CanCreateCosmosDbSqlAccount() {
    final String cosmosDbAccountName = SdkContext.randomResourceName("cosmosdb", 22);

    CosmosDBAccount cosmosDBAccount = cosmosDBManager.databaseAccounts()
        .define(cosmosDbAccountName)
        .withRegion(Region.US_WEST_CENTRAL)
        .withNewResourceGroup(RG_NAME)
        .withDataModelSql()
        .withEventualConsistency()
        .withWriteReplication(Region.US_EAST)
        .withReadReplication(Region.US_CENTRAL)
        .withIpRangeFilter("")
        .withMultipleWriteLocationsEnabled(true)
        .withTag("tag1", "value1")
        .create();

    Assert.assertEquals(cosmosDBAccount.name(), cosmosDbAccountName.toLowerCase());
    Assert.assertEquals(cosmosDBAccount.kind(), DatabaseAccountKind.GLOBAL_DOCUMENT_DB);
    Assert.assertEquals(cosmosDBAccount.writableReplications().size(), 2);
    Assert.assertEquals(cosmosDBAccount.readableReplications().size(), 2);
    Assert.assertEquals(cosmosDBAccount.defaultConsistencyLevel(), DefaultConsistencyLevel.EVENTUAL);
    Assert.assertTrue(cosmosDBAccount.multipleWriteLocationsEnabled());


}
 
Example #12
Source File: ExecuteTask.java    From azure-libraries-for-java with MIT License 6 votes vote down vote up
@Override
public Observable<Indexable> invokeAsync(TaskGroup.InvocationContext context) {
    return this.executor.executeWorkAsync()
            .subscribeOn(SdkContext.getRxScheduler())
            .doOnNext(new Action1<ResultT>() {
                @Override
                public void call(ResultT resultT) {
                    result = resultT;
                }
            }).map(new Func1<ResultT, Indexable>() {
                @Override
                public Indexable call(ResultT resourceT) {
                    return resourceT;
                }
            });
}
 
Example #13
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 #14
Source File: ManageServicePrincipal.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static ActiveDirectoryApplication createActiveDirectoryApplication(Azure.Authenticated authenticated) throws Exception {
    String name = SdkContext.randomResourceName("adapp-sample", 20);
    //create a self-sighed certificate
    String domainName = name + ".com";
    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
    String certPassword = "StrongPass!12";
    Certificate certificate = Certificate.createSelfSigned(domainName, certPassword);

    // create Active Directory application
    ActiveDirectoryApplication activeDirectoryApplication = authenticated.activeDirectoryApplications()
            .define(name)
                .withSignOnUrl("https://github.com/Azure/azure-sdk-for-java/" + name)
                // password credentials definition
                .definePasswordCredential("password")
                    // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")]
                    .withPasswordValue("P@ssw0rd")
                    .withDuration(Duration.standardDays(700))
                    .attach()
                // certificate credentials definition
                .defineCertificateCredential("cert")
                    .withAsymmetricX509Certificate()
                    .withPublicKey(Files.readAllBytes(Paths.get(certificate.getCerPath())))
                    .withDuration(Duration.standardDays(100))
                    .attach()
                .create();
    System.out.println(activeDirectoryApplication.id() + " - " + activeDirectoryApplication.applicationId());
    return activeDirectoryApplication;
}
 
Example #15
Source File: ApplicationGatewayRequestRoutingRuleImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public ApplicationGatewayRequestRoutingRuleImpl toBackendHttpPort(int portNumber) {
    String name = SdkContext.randomResourceName("backcfg", 12);
    this.parent().defineBackendHttpConfiguration(name)
        .withPort(portNumber)
        .attach();
    return this.toBackendHttpConfiguration(name);
}
 
Example #16
Source File: VirtualMachineOperationsTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void canPerformSimulateEvictionOnSpotVirtualMachine() {
    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("firstuser")
            .withRootPassword("afh123RVS!")
            .withSpotPriority(VirtualMachineEvictionPolicyTypes.DEALLOCATE)
            .withSize(VirtualMachineSizeTypes.STANDARD_D2_V3)
            .create();

    Assert.assertNotNull(virtualMachine.osDiskStorageAccountType());
    Assert.assertTrue(virtualMachine.osDiskSize() > 0);
    Disk disk = computeManager.disks().getById(virtualMachine.osDiskId());
    Assert.assertNotNull(disk);
    Assert.assertEquals(DiskState.ATTACHED, disk.inner().diskState());

    // call simulate eviction
    virtualMachine.simulateEviction();
    SdkContext.sleep(30 * 60 * 1000);

    virtualMachine = computeManager.virtualMachines().getById(virtualMachine.id());
    Assert.assertNotNull(virtualMachine);
    Assert.assertNull(virtualMachine.osDiskStorageAccountType());
    Assert.assertTrue(virtualMachine.osDiskSize() == 0);
    disk = computeManager.disks().getById(virtualMachine.osDiskId());
    Assert.assertEquals(DiskState.RESERVED, disk.inner().diskState());
}
 
Example #17
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 #18
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 #19
Source File: ApplicationGatewayImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
protected ApplicationGatewayFrontendImpl ensureDefaultPublicFrontend() {
    ApplicationGatewayFrontendImpl frontend = (ApplicationGatewayFrontendImpl) defaultPublicFrontend();
    if (frontend != null) {
        return frontend;
    } else {
        String name = SdkContext.randomResourceName("frontend", 14);
        frontend = this.defineFrontend(name);
        frontend.attach();
        this.defaultPublicFrontend = frontend;
        return frontend;
    }
}
 
Example #20
Source File: TestNetwork.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Network createResource(Networks networks) throws Exception {
    Region region = Region.US_SOUTH_CENTRAL;
    String groupName = "rg" + this.testId;

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

    Network network = networks.define(networkName)
            .withRegion(region)
            .withNewResourceGroup(groupName)
            .withTag("tag1", "value1")
            .create();
    Assert.assertEquals("value1", network.tags().get("tag1"));
    return network;
}
 
Example #21
Source File: NetworkInterfaceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
NetworkInterfaceImpl(String name,
                     NetworkInterfaceInner innerModel,
                     final NetworkManager networkManager) {
    super(name, innerModel, networkManager);
    this.nicName = name;
    this.namer = SdkContext.getResourceNamerFactory().createResourceNamer(this.nicName);
    initializeChildrenFromInner();
}
 
Example #22
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 #23
Source File: ApplicationGatewayTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void testAppGatewaysStartStop() throws Exception {
    String rgName = SdkContext.randomResourceName("rg", 13);
    Region region = Region.US_EAST;
    String name = SdkContext.randomResourceName("ag", 15);
    ApplicationGateway appGateway = azure.applicationGateways().define(name)
            .withRegion(region)
            .withNewResourceGroup(rgName)

            // Request routing rules
            .defineRequestRoutingRule("rule1")
            .fromPrivateFrontend()
            .fromFrontendHttpPort(80)
            .toBackendHttpPort(8080)
            .toBackendIPAddress("11.1.1.1")
            .toBackendIPAddress("11.1.1.2")
            .attach()
            .create();

    // Test stop/start
    appGateway.stop();
    Assert.assertEquals(ApplicationGatewayOperationalState.STOPPED, appGateway.operationalState());
    appGateway.start();
    Assert.assertEquals(ApplicationGatewayOperationalState.RUNNING, appGateway.operationalState());

    azure.resourceGroups().beginDeleteByName(rgName);
}
 
Example #24
Source File: NetworkImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public NetworkImpl withNewDdosProtectionPlan() {
    inner().withEnableDdosProtection(true);
    DdosProtectionPlan.DefinitionStages.WithGroup ddosProtectionPlanWithGroup = manager().ddosProtectionPlans()
            .define(SdkContext.randomResourceName(name(), 20))
            .withRegion(region());
    if (super.creatableGroup != null && isInCreateMode()) {
        ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withNewResourceGroup(super.creatableGroup);
    } else {
        ddosProtectionPlanCreatable = ddosProtectionPlanWithGroup.withExistingResourceGroup(resourceGroupName());
    }
    this.addDependency(ddosProtectionPlanCreatable);
    return this;
}
 
Example #25
Source File: ApplicationsTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Test
public void canCRUDApplication() throws Exception {
    String name = SdkContext.randomResourceName("javasdkapp", 20);

    ActiveDirectoryApplication application = null;
    try {
        application = graphRbacManager.applications().define(name)
                .withSignOnUrl("http://easycreate.azure.com/" + name)
                .definePasswordCredential("passwd")
                    .withPasswordValue("P@ssw0rd")
                    .withDuration(Duration.standardDays(700))
                    .attach()
                .defineCertificateCredential("cert")
                    .withAsymmetricX509Certificate()
                    .withPublicKey(ByteStreams.toByteArray(this.getClass().getResourceAsStream("/myTest.cer")))
                    .withDuration(Duration.standardDays(100))
                    .attach()
                .create();
        System.out.println(application.id() + " - " + application.applicationId());
        Assert.assertNotNull(application.id());
        Assert.assertNotNull(application.applicationId());
        Assert.assertEquals(name, application.name());
        Assert.assertEquals(1, application.certificateCredentials().size());
        Assert.assertEquals(1, application.passwordCredentials().size());
        Assert.assertEquals(1, application.replyUrls().size());
        Assert.assertEquals(1, application.identifierUris().size());
        Assert.assertEquals("http://easycreate.azure.com/" + name, application.signOnUrl().toString());

        application.update()
                .withoutCredential("passwd")
                .apply();
        System.out.println(application.id() + " - " + application.applicationId());
        Assert.assertEquals(0, application.passwordCredentials().size());
    } finally {
        if (application != null) {
            graphRbacManager.applications().deleteById(application.id());
        }
    }
}
 
Example #26
Source File: ApplicationGatewayTests.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception {
    String vaultName = SdkContext.randomResourceName("vlt", 10);
    String secretName = SdkContext.randomResourceName("srt", 10);
    String secretValue = Files.readFirstLine(new File(getClass().getClassLoader().getResource("test.certificate").getFile()), Charset.defaultCharset());

    Vault vault = keyVaultManager.vaults()
            .define(vaultName)
            .withRegion(Region.US_EAST)
            .withExistingResourceGroup(RG_NAME)
            .defineAccessPolicy()
                .forServicePrincipal(servicePrincipal)
                .allowSecretAllPermissions()
                .attach()
            .defineAccessPolicy()
                .forObjectId(identityPrincipal)
                .allowSecretAllPermissions()
                .attach()
            .withAccessFromAzureServices()
            .withDeploymentEnabled()
            // Important!! Only soft delete enabled key vault can be assigned to application gateway
            // See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382
            .withSoftDeleteEnabled()
            .create();

    return vault.secrets()
            .define(secretName)
            .withValue(secretValue)
            .create();
}
 
Example #27
Source File: ManageManagedDisks.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
private static VirtualMachine prepareSpecializedUnmanagedVirtualMachine(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)
            .withUnmanagedDisks()
            .defineUnmanagedDataDisk("disk-1")
                .withNewVhd(100)
                .withLun(1)
                .attach()
            .defineUnmanagedDataDisk("disk-2")
                .withNewVhd(50)
                .withLun(2)
                .attach()
            .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 #28
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 #29
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 #30
Source File: RoleAssignmentHelper.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Specifies that applications running on an Azure service with this identity requires
 * the given access role with scope of access limited to the ARM resource identified by
 * the resource ID specified in the scope parameter.
 *
 * @param scope scope of the access represented in ARM resource ID format
 * @param asRole access role to assigned to the identity
 * @return RoleAssignmentHelper
 */
public RoleAssignmentHelper withAccessTo(final String scope, final BuiltInRole asRole) {
    FunctionalTaskItem creator = new FunctionalTaskItem() {
        @Override
        public Observable<Indexable> call(final Context cxt) {
            final String principalId = idProvider.principalId();
            if (principalId == null) {
                return cxt.voidObservable();
            }
            final String roleAssignmentName = SdkContext.randomUuid();
            final String resourceScope;
            if (scope == CURRENT_RESOURCE_GROUP_SCOPE) {
                resourceScope = resourceGroupId(idProvider.resourceId());
            } else {
                resourceScope = scope;
            }
            return rbacManager
                    .roleAssignments()
                    .define(roleAssignmentName)
                    .forObjectId(principalId)
                    .withBuiltInRole(asRole)
                    .withScope(resourceScope)
                    .createAsync()
                    .last()
                    .onErrorResumeNext(new Func1<Throwable, Observable<Indexable>>() {
                        @Override
                        public Observable<Indexable> call(Throwable throwable) {
                            if (isRoleAssignmentExists(throwable)) {
                                return cxt.voidObservable();
                            }
                            return Observable.<Indexable>error(throwable);
                        }
                    });
        }
    };
    this.preRunTaskGroup.addPostRunDependent(creator);
    return this;
}