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

The following examples show how to use com.microsoft.azure.management.resources.fluentcore.utils.SdkContext. These examples are extracted from open source projects. 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 Project: azure-libraries-for-java   Source File: ContainerGroupImpl.java    License: 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 Project: azure-libraries-for-java   Source File: ExecuteTask.java    License: 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 3
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 4
Source Project: azure-libraries-for-java   Source File: EventHubImpl.java    License: 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 5
Source Project: azure-libraries-for-java   Source File: CosmosDBTests.java    License: 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 6
@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 7
Source Project: azure-libraries-for-java   Source File: CosmosDBTests.java    License: 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 8
@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("[email protected]#F0orL")
            .withBootDiagnostics(creatableStorageAccount)
            .create();
    Assert.assertNotNull(virtualMachine);
    Assert.assertTrue(virtualMachine.isBootDiagnosticsEnabled());
    Assert.assertNotNull(virtualMachine.bootDiagnosticsStorageUri());
    Assert.assertTrue(virtualMachine.bootDiagnosticsStorageUri().contains(storageName));
}
 
Example 9
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 10
Source Project: azure-libraries-for-java   Source File: DdosProtectionPlanTests.java    License: 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 11
Source Project: azure-libraries-for-java   Source File: RoleAssignmentTests.java    License: 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 12
Source Project: azure-libraries-for-java   Source File: AzureTests.java    License: 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 13
Source Project: azure-libraries-for-java   Source File: AzureTests.java    License: 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 14
Source Project: azure-gradle-plugins   Source File: WebAppUtils.java    License: 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 15
Source Project: azure-libraries-for-java   Source File: IndexableTaskItem.java    License: MIT License 5 votes vote down vote up
@Override
public Observable<Indexable> invokeAsync(TaskGroup.InvocationContext context) {
    return this.invokeTaskAsync(context)
            .subscribeOn(SdkContext.getRxScheduler())
            .map(new Func1<Indexable, Indexable>() {
                @Override
                public Indexable call(Indexable result) {
                    taskResult = result;
                    return result;
                }
            });
}
 
Example 16
private VirtualNetworkGatewayIPConfigurationImpl ensureDefaultIPConfig() {
    VirtualNetworkGatewayIPConfigurationImpl ipConfig = (VirtualNetworkGatewayIPConfigurationImpl) defaultIPConfiguration();
    if (ipConfig == null) {
        String name = SdkContext.randomResourceName("ipcfg", 11);
        ipConfig = this.defineIPConfiguration(name);
        ipConfig.attach();
    }
    return ipConfig;
}
 
Example 17
Source Project: azure-libraries-for-java   Source File: ResourceGroupsTests.java    License: MIT License 5 votes vote down vote up
@Test
public void canCreateResourceGroup() throws Exception {
    final String rgName = SdkContext.randomResourceName("rg", 9);
    Region region = Region.US_SOUTH_CENTRAL;
    // Create
    resourceGroups.define(rgName)
            .withRegion(Region.US_SOUTH_CENTRAL)
            .withTag("department", "finance")
            .withTag("tagname", "tagvalue")
            .create();
    // List
    ResourceGroup groupResult = null;
    for (ResourceGroup rg : resourceGroups.listByTag("department", "finance")) {
        if (rg.name().equals(rgName)) {
            groupResult = rg;
            break;
        }
    }
    Assert.assertNotNull(groupResult);
    Assert.assertEquals("finance", groupResult.tags().get("department"));
    Assert.assertEquals("tagvalue", groupResult.tags().get("tagname"));
    Assert.assertTrue(region.name().equalsIgnoreCase(groupResult.regionName()));

    // Check existence
    Assert.assertTrue(resourceGroups.checkExistence(rgName));

    // Get
    ResourceGroup getGroup = resourceGroups.getByName(rgName);
    Assert.assertNotNull(getGroup);
    Assert.assertEquals(rgName, getGroup.name());
    // Update
    ResourceGroup updatedGroup = getGroup.update()
            .withTag("tag1", "value1")
            .apply();
    Assert.assertEquals("value1", updatedGroup.tags().get("tag1"));
    Assert.assertTrue(region.name().equalsIgnoreCase(getGroup.regionName()));
    // Delete
    resourceGroups.deleteByName(rgName);
    Assert.assertFalse(resourceGroups.checkExistence(rgName));
}
 
Example 18
Source Project: azure-libraries-for-java   Source File: DeploymentsTests.java    License: 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 19
Source Project: azure-libraries-for-java   Source File: WebAppsWebDeployTests.java    License: MIT License 5 votes vote down vote up
@Test
public void canDeployWarFile() throws Exception {
    // Create with new app service plan
    WebApp webApp1 = appServiceManager.webApps().define(WEBAPP_NAME_1)
            .withRegion(Region.US_WEST)
            .withNewResourceGroup(RG_NAME_1)
            .withNewWindowsPlan(PricingTier.BASIC_B1)
            .withJavaVersion(JavaVersion.JAVA_8_NEWEST)
            .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST)
            .create();
    Assert.assertNotNull(webApp1);
    Assert.assertEquals(Region.US_WEST, webApp1.region());
    AppServicePlan plan1 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId());
    Assert.assertNotNull(plan1);
    Assert.assertEquals(Region.US_WEST, plan1.region());
    Assert.assertEquals(PricingTier.BASIC_B1, plan1.pricingTier());

    WebDeployment deployment = webApp1.deploy()
            .withPackageUri("https://github.com/Azure/azure-libraries-for-java/raw/master/azure-mgmt-appservice/src/test/resources/webapps.zip")
            .withExistingDeploymentsDeleted(true)
            .execute();

    Assert.assertNotNull(deployment);
    if (!isPlaybackMode()) {
        SdkContext.sleep(10000);
        Response response = curl("http://" + webApp1.defaultHostName() + "/helloworld");
        Assert.assertEquals(200, response.code());
        String body = response.body().string();
        Assert.assertNotNull(body);
        Assert.assertTrue(body.contains("Current time:"));
    }
}
 
Example 20
Source Project: azure-libraries-for-java   Source File: ManageServicePrincipal.java    License: 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("[email protected]")
                    .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 21
@Override
public ApplicationGatewayRequestRoutingRuleImpl toBackendHttpPort(int portNumber) {
    String name = SdkContext.randomResourceName("backcfg", 12);
    this.parent().defineBackendHttpConfiguration(name)
        .withPort(portNumber)
        .attach();
    return this.toBackendHttpConfiguration(name);
}
 
Example 22
@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 23
Source Project: azure-libraries-for-java   Source File: ApplicationGatewayImpl.java    License: 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 24
Source Project: azure-libraries-for-java   Source File: TestNetwork.java    License: 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 25
Source Project: azure-libraries-for-java   Source File: NetworkInterfaceImpl.java    License: 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 26
Source Project: azure-libraries-for-java   Source File: KeyTests.java    License: 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 27
Source Project: azure-libraries-for-java   Source File: ApplicationGatewayTests.java    License: 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 28
Source Project: azure-libraries-for-java   Source File: NetworkImpl.java    License: 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 29
Source Project: azure-libraries-for-java   Source File: ApplicationsTests.java    License: 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("[email protected]")
                    .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 30
Source Project: azure-libraries-for-java   Source File: ApplicationGatewayTests.java    License: 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();
}