Search in sources :

Example 1 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class VirtualMachineExtensionOperationsTests method canEnableDiagnosticsExtension.

@Test
public void canEnableDiagnosticsExtension() throws Exception {
    final String STORAGEACCOUNTNAME = generateRandomResourceName("stg", 15);
    final String VMNAME = "javavm1";
    // Creates a storage account
    StorageAccount storageAccount = storageManager.storageAccounts().define(STORAGEACCOUNTNAME).withRegion(REGION).withNewResourceGroup(RG_NAME).create();
    // Create a Linux VM
    //
    VirtualMachine vm = computeManager.virtualMachines().define(VMNAME).withRegion(REGION).withExistingResourceGroup(RG_NAME).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withoutPrimaryPublicIPAddress().withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_14_04_LTS).withRootUsername("Foo12").withRootPassword("BaR@12abc!").withSize(VirtualMachineSizeTypes.STANDARD_D3).withExistingStorageAccount(storageAccount).create();
    final InputStream embeddedJsonConfig = VirtualMachineExtensionOperationsTests.class.getResourceAsStream("/linux_diagnostics_public_config.json");
    String jsonConfig = ((new ObjectMapper()).readTree(embeddedJsonConfig)).toString();
    jsonConfig = jsonConfig.replace("%VirtualMachineResourceId%", vm.id());
    // Update Linux VM to enable Diagnostics
    vm.update().defineNewExtension("LinuxDiagnostic").withPublisher("Microsoft.OSTCExtensions").withType("LinuxDiagnostic").withVersion("2.3").withPublicSetting("ladCfg", new String(Base64.encodeBase64(jsonConfig.getBytes()))).withPublicSetting("storageAccount", storageAccount.name()).withProtectedSetting("storageAccountName", storageAccount.name()).withProtectedSetting("storageAccountKey", storageAccount.getKeys().get(0).value()).withProtectedSetting("storageAccountEndPoint", "https://core.windows.net:443/").attach().apply();
}
Also used : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) InputStream(java.io.InputStream) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 2 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class ManageLinuxWebAppStorageAccountConnection method runSample.

/**
     * 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).withPublicDockerHubImage("tomcat:8-jre8").withStartUpCommand("/bin/bash -c \"sed -ie 's/appBase=\\\"webapps\\\"/appBase=\\\"\\\\/home\\\\/site\\\\/wwwroot\\\\/webapps\\\"/g' conf/server.xml && catalina.sh run\"").withConnectionString("storage.connectionString", connectionString, ConnectionStringType.CUSTOM).withAppSetting("storage.containerName", containerName).withAppSetting("PORT", "8080").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.uploadFileToFtp(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");
        Thread.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;
}
Also used : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) CloudStorageAccount(com.microsoft.azure.storage.CloudStorageAccount) CloudBlobContainer(com.microsoft.azure.storage.blob.CloudBlobContainer) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) StorageException(com.microsoft.azure.storage.StorageException) InvalidKeyException(java.security.InvalidKeyException) WebApp(com.microsoft.azure.management.appservice.WebApp)

Example 3 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class RedisCacheOperationsTests method canCRUDRedisCache.

@Test
public void canCRUDRedisCache() throws Exception {
    // Create
    Creatable<ResourceGroup> resourceGroups = resourceManager.resourceGroups().define(RG_NAME_SECOND).withRegion(Region.US_CENTRAL);
    Creatable<RedisCache> redisCacheDefinition1 = redisManager.redisCaches().define(RR_NAME).withRegion(Region.ASIA_EAST).withNewResourceGroup(RG_NAME).withBasicSku();
    Creatable<RedisCache> redisCacheDefinition2 = redisManager.redisCaches().define(RR_NAME_SECOND).withRegion(Region.US_CENTRAL).withNewResourceGroup(resourceGroups).withPremiumSku().withShardCount(10).withPatchSchedule(DayOfWeek.SUNDAY, 10, Period.minutes(302));
    Creatable<RedisCache> redisCacheDefinition3 = redisManager.redisCaches().define(RR_NAME_THIRD).withRegion(Region.US_CENTRAL).withNewResourceGroup(resourceGroups).withPremiumSku(2).withRedisConfiguration("maxclients", "2").withNonSslPort();
    CreatedResources<RedisCache> batchRedisCaches = redisManager.redisCaches().create(redisCacheDefinition1, redisCacheDefinition2, redisCacheDefinition3);
    StorageAccount storageAccount = storageManager.storageAccounts().define(SA_NAME).withRegion(Region.US_CENTRAL).withExistingResourceGroup(RG_NAME_SECOND).create();
    RedisCache redisCache = batchRedisCaches.get(redisCacheDefinition1.key());
    RedisCache redisCachePremium = batchRedisCaches.get(redisCacheDefinition3.key());
    Assert.assertEquals(RG_NAME, redisCache.resourceGroupName());
    Assert.assertEquals(SkuName.BASIC, redisCache.sku().name());
    // List by Resource Group
    List<RedisCache> redisCaches = redisManager.redisCaches().listByResourceGroup(RG_NAME);
    boolean found = false;
    for (RedisCache existingRedisCache : redisCaches) {
        if (existingRedisCache.name().equals(RR_NAME)) {
            found = true;
        }
    }
    Assert.assertTrue(found);
    Assert.assertEquals(1, redisCaches.size());
    // List all Redis resources
    redisCaches = redisManager.redisCaches().list();
    found = false;
    for (RedisCache existingRedisCache : redisCaches) {
        if (existingRedisCache.name().equals(RR_NAME)) {
            found = true;
        }
    }
    Assert.assertTrue(found);
    Assert.assertTrue(redisCaches.size() >= 3);
    // Get
    RedisCache redisCacheGet = redisManager.redisCaches().getByResourceGroup(RG_NAME, RR_NAME);
    Assert.assertNotNull(redisCacheGet);
    Assert.assertEquals(redisCache.id(), redisCacheGet.id());
    Assert.assertEquals(redisCache.provisioningState(), redisCacheGet.provisioningState());
    // Get Keys
    RedisAccessKeys redisKeys = redisCache.keys();
    Assert.assertNotNull(redisKeys);
    Assert.assertNotNull(redisKeys.primaryKey());
    Assert.assertNotNull(redisKeys.secondaryKey());
    // Regen key
    RedisAccessKeys oldKeys = redisCache.refreshKeys();
    RedisAccessKeys updatedPrimaryKey = redisCache.regenerateKey(RedisKeyType.PRIMARY);
    RedisAccessKeys updatedSecondaryKey = redisCache.regenerateKey(RedisKeyType.SECONDARY);
    Assert.assertNotNull(oldKeys);
    Assert.assertNotNull(updatedPrimaryKey);
    Assert.assertNotNull(updatedSecondaryKey);
    Assert.assertNotEquals(oldKeys.primaryKey(), updatedPrimaryKey.primaryKey());
    Assert.assertEquals(oldKeys.secondaryKey(), updatedPrimaryKey.secondaryKey());
    Assert.assertNotEquals(oldKeys.secondaryKey(), updatedSecondaryKey.secondaryKey());
    Assert.assertNotEquals(updatedPrimaryKey.secondaryKey(), updatedSecondaryKey.secondaryKey());
    Assert.assertEquals(updatedPrimaryKey.primaryKey(), updatedSecondaryKey.primaryKey());
    // Update to STANDARD Sku from BASIC SKU
    redisCache = redisCache.update().withStandardSku().apply();
    Assert.assertEquals(SkuName.STANDARD, redisCache.sku().name());
    Assert.assertEquals(SkuFamily.C, redisCache.sku().family());
    try {
        redisCache.update().withBasicSku(1).apply();
        fail();
    } catch (CloudException e) {
    // expected since Sku downgrade is not supported
    }
    // Refresh
    redisCache.refresh();
    // delete
    redisManager.redisCaches().deleteById(redisCache.id());
    // Premium SKU Functionality
    RedisCachePremium premiumCache = redisCachePremium.asPremium();
    Assert.assertEquals(SkuFamily.P, premiumCache.sku().family());
    // Redis configuration update
    premiumCache.update().withRedisConfiguration("maxclients", "3").apply();
    premiumCache.update().withoutRedisConfiguration("maxclients").apply();
    premiumCache.update().withoutRedisConfiguration().apply();
    premiumCache.update().withPatchSchedule(DayOfWeek.MONDAY, 1).withPatchSchedule(DayOfWeek.TUESDAY, 5).apply();
    // Reboot
    premiumCache.forceReboot(RebootType.ALL_NODES);
    // Patch Schedule
    List<ScheduleEntry> patchSchedule = premiumCache.listPatchSchedules();
    Assert.assertEquals(2, patchSchedule.size());
    premiumCache.deletePatchSchedule();
    patchSchedule = redisManager.redisCaches().getById(premiumCache.id()).asPremium().listPatchSchedules();
    Assert.assertNull(patchSchedule);
// currently throws because SAS url of the container should be provided as
// {"error":{
//      "code":"InvalidRequestBody",
//      "message": "One of the SAS URIs provided could not be used for the following reason:
//                  The SAS token is poorly formatted.\r\nRequestID=ed105089-b93b-427e-9cbb-d78ed80d23b0",
//      "target":null}}
// com.microsoft.azure.CloudException: One of the SAS URIs provided could not be used for the following reason: The SAS token is poorly formatted.
/*premiumCache.exportData(storageAccount.name(),"snapshot1");

        premiumCache.importData(Arrays.asList("snapshot1"));*/
}
Also used : CloudException(com.microsoft.azure.CloudException) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) Test(org.junit.Test)

Example 4 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class TestResourceStreaming method createResource.

@Override
public VirtualMachine createResource(VirtualMachines virtualMachines) throws Exception {
    final String vmName = "vm" + this.testId;
    System.out.println("In createResource \n\n\n");
    Creatable<ResourceGroup> rgCreatable = virtualMachines.manager().resourceManager().resourceGroups().define(SdkContext.randomResourceName("rg" + vmName, 20)).withRegion(Region.US_EAST);
    Creatable<StorageAccount> storageCreatable = this.storageAccounts.define(SdkContext.randomResourceName("stg", 20)).withRegion(Region.US_EAST).withNewResourceGroup(rgCreatable);
    final AtomicInteger resourceCount = new AtomicInteger(0);
    VirtualMachine virtualMachine = (VirtualMachine) virtualMachines.define(vmName).withRegion(Region.US_EAST).withNewResourceGroup(rgCreatable).withNewPrimaryNetwork("10.0.0.0/28").withPrimaryPrivateIPAddressDynamic().withNewPrimaryPublicIPAddress(SdkContext.randomResourceName("pip", 20)).withPopularWindowsImage(KnownWindowsVirtualMachineImage.WINDOWS_SERVER_2012_R2_DATACENTER).withAdminUsername("testuser").withAdminPassword("12NewPA$$w0rd!").withSize(VirtualMachineSizeTypes.STANDARD_D1_V2).withNewStorageAccount(storageCreatable).withNewAvailabilitySet(SdkContext.randomResourceName("avset", 10)).createAsync().map(new Func1<Indexable, Resource>() {

        @Override
        public Resource call(Indexable resource) {
            resourceCount.incrementAndGet();
            Resource createdResource = (Resource) resource;
            System.out.println("Created :" + createdResource.id());
            return createdResource;
        }
    }).toBlocking().last();
    Assert.assertTrue(resourceCount.get() == 7);
    return virtualMachine;
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Resource(com.microsoft.azure.management.resources.fluentcore.arm.models.Resource) Indexable(com.microsoft.azure.management.resources.fluentcore.model.Indexable) Func1(rx.functions.Func1) ResourceGroup(com.microsoft.azure.management.resources.ResourceGroup) VirtualMachine(com.microsoft.azure.management.compute.VirtualMachine)

Example 5 with StorageAccount

use of com.microsoft.azure.management.storage.StorageAccount in project azure-sdk-for-java by Azure.

the class AzureTests method createStorageAccount.

@Test
public void createStorageAccount() throws Exception {
    String storageAccountName = generateRandomResourceName("testsa", 12);
    StorageAccount storageAccount = azure.storageAccounts().define(storageAccountName).withRegion(Region.ASIA_EAST).withNewResourceGroup().withSku(SkuName.PREMIUM_LRS).create();
    Assert.assertEquals(storageAccount.name(), storageAccountName);
    azure.resourceGroups().beginDeleteByName(storageAccount.resourceGroupName());
}
Also used : StorageAccount(com.microsoft.azure.management.storage.StorageAccount) Test(org.junit.Test)

Aggregations

StorageAccount (com.microsoft.azure.management.storage.StorageAccount)29 ResourceGroup (com.microsoft.azure.management.resources.ResourceGroup)9 ArrayList (java.util.ArrayList)7 VirtualMachine (com.microsoft.azure.management.compute.VirtualMachine)5 Network (com.microsoft.azure.management.network.Network)5 Region (com.microsoft.azure.management.resources.fluentcore.arm.Region)5 Creatable (com.microsoft.azure.management.resources.fluentcore.model.Creatable)5 StorageAccountKey (com.microsoft.azure.management.storage.StorageAccountKey)5 Test (org.junit.Test)5 ClientStorageAccount (com.microsoft.tooling.msservices.model.storage.ClientStorageAccount)4 Func1 (rx.functions.Func1)4 Indexable (com.microsoft.azure.management.resources.fluentcore.model.Indexable)3 CloudStorageAccount (com.microsoft.azure.storage.CloudStorageAccount)3 CloudBlobContainer (com.microsoft.azure.storage.blob.CloudBlobContainer)3 StopWatch (org.apache.commons.lang3.time.StopWatch)3 CloudException (com.microsoft.azure.CloudException)2 WebApp (com.microsoft.azure.management.appservice.WebApp)2 PublicIPAddress (com.microsoft.azure.management.network.PublicIPAddress)2 Resource (com.microsoft.azure.management.resources.fluentcore.arm.models.Resource)2 StorageAccounts (com.microsoft.azure.management.storage.StorageAccounts)2