Java Code Examples for com.microsoft.azure.management.resources.fluentcore.utils.SdkContext#sleep()
The following examples show how to use
com.microsoft.azure.management.resources.fluentcore.utils.SdkContext#sleep() .
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: KeyTests.java From azure-libraries-for-java with MIT License | 6 votes |
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 2
Source File: ProvidersTests.java From azure-libraries-for-java with MIT License | 6 votes |
@Test public void canUnregisterAndRegisterProvider() throws Exception { List<Provider> providers = resourceManager.providers().list(); int size = providers.size(); Assert.assertTrue(size > 0); Provider provider = providers.get(0); resourceManager.providers().unregister(provider.namespace()); provider = resourceManager.providers().getByName(provider.namespace()); while (provider.registrationState().equals("Unregistering")) { SdkContext.sleep(5000); provider = resourceManager.providers().getByName(provider.namespace()); } resourceManager.providers().register(provider.namespace()); while (provider.registrationState().equals("Unregistered") || provider.registrationState().equalsIgnoreCase("Registering")) { SdkContext.sleep(5 * 1000); provider = resourceManager.providers().getByName(provider.namespace()); } Assert.assertEquals("Registered", provider.registrationState()); List<ProviderResourceType> resourceTypes = provider.resourceTypes(); Assert.assertTrue(resourceTypes.size() > 0); }
Example 3
Source File: ZipDeployTests.java From azure-libraries-for-java with MIT License | 6 votes |
@Test public void canZipDeployFunction() { // Create function app FunctionApp functionApp = appServiceManager.functionApps().define(WEBAPP_NAME_4) .withRegion(Region.US_WEST) .withNewResourceGroup(RG_NAME) .create(); Assert.assertNotNull(functionApp); SdkContext.sleep(5000); functionApp.zipDeploy(new File(FunctionAppsTests.class.getResource("/square-function-app.zip").getPath())); SdkContext.sleep(5000); String response = post("http://" + WEBAPP_NAME_4 + ".azurewebsites.net" + "/api/square", "25"); Assert.assertNotNull(response); Assert.assertEquals("625", response); PagedList<FunctionEnvelope> envelopes = appServiceManager.functionApps().listFunctions(RG_NAME, functionApp.name()); Assert.assertNotNull(envelopes); Assert.assertEquals(1, envelopes.size()); Assert.assertEquals(envelopes.get(0).href(), "https://" + WEBAPP_NAME_4 +".scm.azurewebsites.net/api/functions/square"); }
Example 4
Source File: FunctionAppsTests.java From azure-libraries-for-java with MIT License | 5 votes |
@Test public void canCRUDLinuxFunctionAppPremium() { RG_NAME_2 = null; // function app with premium plan FunctionApp functionApp1 = appServiceManager.functionApps().define(WEBAPP_NAME_1) .withRegion(Region.US_EAST) .withNewResourceGroup(RG_NAME_1) .withNewLinuxAppServicePlan(new PricingTier(com.microsoft.azure.management.appservice.SkuName.ELASTIC_PREMIUM.toString(), "EP1")) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); Assert.assertNotNull(functionApp1); AppServicePlan plan1 = appServiceManager.appServicePlans().getById(functionApp1.appServicePlanId()); Assert.assertNotNull(plan1); Assert.assertEquals(new PricingTier(com.microsoft.azure.management.appservice.SkuName.ELASTIC_PREMIUM.toString(), "EP1"), plan1.pricingTier()); Assert.assertTrue(plan1.inner().reserved()); assertLinuxJava(functionApp1, FunctionRuntimeStack.JAVA_8.getLinuxFxVersionForDedicatedPlan()); // wait for deploy if (!isPlaybackMode()) { SdkContext.sleep(180000); } // verify deploy List<FunctionEnvelope> functions = appServiceManager.functionApps().listFunctions(functionApp1.resourceGroupName(), functionApp1.name()); Assert.assertEquals(1, functions.size()); }
Example 5
Source File: ManageServicePrincipal.java From azure-libraries-for-java with MIT License | 5 votes |
/** * Main function which runs the actual sample. * @param authenticated instance of Authenticated * @param defaultSubscriptionId default subscription id * @return true if sample runs successfully */ public static boolean runSample(Azure.Authenticated authenticated, String defaultSubscriptionId) { ActiveDirectoryApplication activeDirectoryApplication = null; try { String authFileName = "myAuthFile.azureauth"; String authFilePath = Paths.get(getBasePath(), authFileName).toString(); activeDirectoryApplication = createActiveDirectoryApplication(authenticated); ServicePrincipal servicePrincipal = createServicePrincipalWithRoleForApplicationAndExportToFile( authenticated, activeDirectoryApplication, BuiltInRole.CONTRIBUTOR, defaultSubscriptionId, authFilePath); SdkContext.sleep(15000); useAuthFile(authFilePath); manageApplication(authenticated, activeDirectoryApplication); manageServicePrincipal(authenticated, servicePrincipal); return true; } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } finally { if (activeDirectoryApplication != null) { // this will delete Service Principal as well authenticated.activeDirectoryApplications().deleteById(activeDirectoryApplication.id()); } } return false; }
Example 6
Source File: QueryMetricsAndActivityLogs.java From azure-libraries-for-java with MIT License | 4 votes |
private static void addBlobTransactions(String storageConnectionString) throws IOException, URISyntaxException, InvalidKeyException, StorageException { // Get the script to upload // InputStream scriptFileAsStream = QueryMetricsAndActivityLogs .class .getResourceAsStream("/install_apache.sh"); // Get the size of the stream // int fileSize; ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); byte[] buffer = new byte[256]; int bytesRead; while ((bytesRead = scriptFileAsStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } fileSize = outputStream.size(); outputStream.close(); // Upload the script file as block blob // CloudStorageAccount account = CloudStorageAccount.parse(storageConnectionString); CloudBlobClient cloudBlobClient = account.createCloudBlobClient(); CloudBlobContainer container = cloudBlobClient.getContainerReference("scripts"); container.createIfNotExists(); ServiceProperties serviceProps = cloudBlobClient.downloadServiceProperties(); // configure Storage logging and metrics LoggingProperties logProps = new LoggingProperties(); logProps.setLogOperationTypes(EnumSet.of(LoggingOperations.READ, LoggingOperations.WRITE)); logProps.setRetentionIntervalInDays(2); logProps.setVersion("1.0"); serviceProps.setLogging(logProps); MetricsProperties metricProps = new MetricsProperties(); metricProps.setMetricsLevel(MetricsLevel.SERVICE_AND_API); metricProps.setRetentionIntervalInDays(2); metricProps.setVersion("1.0"); serviceProps.setHourMetrics(metricProps); serviceProps.setMinuteMetrics(metricProps); // Set the default service version to be used for anonymous requests. serviceProps.setDefaultServiceVersion("2015-04-05"); // Set the service properties. cloudBlobClient.uploadServiceProperties(serviceProps); CloudBlockBlob blob = container.getBlockBlobReference("install_apache.sh"); blob.upload(scriptFileAsStream, fileSize); // give sometime for the infrastructure to process the records and fit into time grain. SdkContext.sleep(6 * 60000); }
Example 7
Source File: LinuxWebAppsTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Test // @Ignore("Pending ICM 39157077 & https://github.com/Azure-App-Service/kudu/issues/30") public void canCRUDLinuxWebApp() throws Exception { // Create with new app service plan WebApp webApp1 = appServiceManager.webApps().define(WEBAPP_NAME_1) .withRegion(Region.US_WEST) .withNewResourceGroup(RG_NAME_1) .withNewLinuxPlan(PricingTier.BASIC_B1) .withPublicDockerHubImage("wordpress") .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()); Assert.assertEquals(OperatingSystem.LINUX, plan1.operatingSystem()); Assert.assertEquals(OperatingSystem.LINUX, webApp1.operatingSystem()); // Create in a new group with existing app service plan WebApp webApp2 = appServiceManager.webApps().define(WEBAPP_NAME_2) .withExistingLinuxPlan(plan1) .withNewResourceGroup(RG_NAME_2) .withPublicDockerHubImage("tomcat") .withContainerLoggingEnabled() .create(); Assert.assertNotNull(webApp2); Assert.assertEquals(Region.US_WEST, webApp2.region()); Assert.assertEquals(OperatingSystem.LINUX, webApp2.operatingSystem()); // Get WebApp webApp = appServiceManager.webApps().getByResourceGroup(RG_NAME_1, webApp1.name()); Assert.assertEquals(OperatingSystem.LINUX, webApp.operatingSystem()); webApp = appServiceManager.webApps().getById(webApp2.id()); Assert.assertEquals(OperatingSystem.LINUX, webApp.operatingSystem()); // View logs if (!isPlaybackMode()) { // warm up curl("http://" + webApp.defaultHostName()); } byte[] logs = webApp.getContainerLogs(); Assert.assertTrue(logs.length > 0); byte[] logsZip = webApp.getContainerLogsZip(); if (!isPlaybackMode()) { ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(logsZip)); Assert.assertNotNull(zipInputStream.getNextEntry()); byte[] unzipped = ByteStreams.toByteArray(zipInputStream); Assert.assertTrue(unzipped.length > 0); } // Update webApp = webApp1.update() .withNewAppServicePlan(PricingTier.STANDARD_S2) .apply(); AppServicePlan plan2 = appServiceManager.appServicePlans().getById(webApp1.appServicePlanId()); Assert.assertNotNull(plan2); Assert.assertEquals(Region.US_WEST, plan2.region()); Assert.assertEquals(PricingTier.STANDARD_S2, plan2.pricingTier()); Assert.assertEquals(OperatingSystem.LINUX, plan2.operatingSystem()); webApp = webApp1.update() .withBuiltInImage(RuntimeStack.NODEJS_6_6) .defineSourceControl() .withPublicGitRepository("https://github.com/jianghaolu/azure-site-test.git") .withBranch("master") .attach() .apply(); Assert.assertNotNull(webApp); if (!isPlaybackMode()) { // maybe 2 minutes is enough? SdkContext.sleep(120000); Response response = curl("http://" + webApp1.defaultHostName()); Assert.assertEquals(200, response.code()); String body = response.body().string(); Assert.assertNotNull(body); Assert.assertTrue(body.contains("Hello world from linux 4")); //update to a java 11 image webApp = webApp1.update() .withBuiltInImage(RuntimeStack.TOMCAT_9_0_JAVA11) .apply(); Assert.assertNotNull(webApp); } }
Example 8
Source File: DockerUtils.java From azure-libraries-for-java with MIT License | 4 votes |
/** * It creates a new Azure virtual machine and it instantiate a Java Docker client. * @param azure - instance of Azure * @param rgName - name of the Azure resource group to be used when creating a virtual machine * @param region - region to be used when creating a virtual machine * @param registryServerUrl - address of the private container registry * @param username - user name to connect with to the private container registry * @param password - password to connect with to the private container registry * @return an instance of DockerClient * @throws Exception exception thrown */ public static DockerClient fromNewDockerVM(Azure azure, String rgName, Region region, String registryServerUrl, String username, String password) throws Exception { final String dockerVMName = SdkContext.randomResourceName("dockervm", 15); final String publicIPDnsLabel = SdkContext.randomResourceName("pip", 10); final String vmUserName = "dockerUser"; // [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Serves as an example, not for deployment. Please change when using this in your code.")] final String vmPassword = "12NewPA!!w0rd!"; // Could not find a Docker environment; presume that there is no local Docker engine running and // attempt to configure a Docker engine running inside a new Azure virtual machine System.out.println("Creating an Azure virtual machine running Docker"); Date t1 = new Date(); VirtualMachine dockerVM = azure.virtualMachines().define(dockerVMName) .withRegion(region) .withExistingResourceGroup(rgName) .withNewPrimaryNetwork("10.0.0.0/28") .withPrimaryPrivateIPAddressDynamic() .withNewPrimaryPublicIPAddress(publicIPDnsLabel) .withPopularLinuxImage(KnownLinuxVirtualMachineImage.UBUNTU_SERVER_16_04_LTS) .withRootUsername(vmUserName) .withRootPassword(vmPassword) .withSize(VirtualMachineSizeTypes.STANDARD_D2_V2) .create(); Date t2 = new Date(); System.out.println("Created Azure Virtual Machine: (took " + ((t2.getTime() - t1.getTime()) / 1000) + " seconds) " + dockerVM.id()); // Wait for a minute for PIP to be available SdkContext.sleep(60 * 1000); // Get the IP of the Docker host NicIPConfiguration nicIPConfiguration = dockerVM.getPrimaryNetworkInterface().primaryIPConfiguration(); PublicIPAddress publicIp = nicIPConfiguration.getPublicIPAddress(); String dockerHostIP = publicIp.ipAddress(); DockerClient dockerClient = installDocker(dockerHostIP, vmUserName, vmPassword, registryServerUrl, username, password); System.out.println("List Docker host info"); System.out.println("\tFound Docker version: " + dockerClient.versionCmd().exec().toString()); System.out.println("\tFound Docker info: " + dockerClient.infoCmd().exec().toString()); return dockerClient; }
Example 9
Source File: VaultTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Test public void canEnableSoftDeleteAndPurge() throws InterruptedException { String otherVaultName = VAULT_NAME + "other"; String sp = SdkContext.randomResourceName("sp", 20); String us = SdkContext.randomResourceName("us", 20); ServicePrincipal servicePrincipal = graphRbacManager.servicePrincipals() .define(sp) .withNewApplication("http://" + sp) .create(); ActiveDirectoryUser user = graphRbacManager.users() .define(us) .withEmailAlias(us) .withPassword("P@$$w0rd") .create(); try { Vault vault = keyVaultManager.vaults().define(otherVaultName) .withRegion(Region.US_WEST) .withNewResourceGroup(RG_NAME) .defineAccessPolicy() .forServicePrincipal("http://" + sp) .allowKeyPermissions(KeyPermissions.LIST) .allowSecretAllPermissions() .allowCertificatePermissions(CertificatePermissions.GET) .attach() .defineAccessPolicy() .forUser(us) .allowKeyAllPermissions() .allowSecretAllPermissions() .allowCertificatePermissions(CertificatePermissions.GET, CertificatePermissions.LIST, CertificatePermissions.CREATE) .attach() .withSoftDeleteEnabled() .create(); Assert.assertTrue(vault.softDeleteEnabled()); keyVaultManager.vaults().deleteByResourceGroup(RG_NAME, otherVaultName);; SdkContext.sleep(20000); //Can still see deleted vault. Assert.assertNotNull(keyVaultManager.vaults().getDeleted(otherVaultName, Region.US_WEST.toString())); keyVaultManager.vaults().purgeDeleted(otherVaultName, Region.US_WEST.toString()); SdkContext.sleep(20000); //Vault is purged Assert.assertNull(keyVaultManager.vaults().getDeleted(otherVaultName, Region.US_WEST.toString())); } finally { graphRbacManager.servicePrincipals().deleteById(servicePrincipal.id()); // graphRbacManager.users().deleteById(user.id()); } }
Example 10
Source File: ManageContainerInstanceWithMultipleContainerImages.java From azure-libraries-for-java with MIT License | 4 votes |
/** * 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("rgACI", 15); final String aciName = SdkContext.randomResourceName("acisample", 20); final String containerImageName1 = "microsoft/aci-helloworld"; final String containerImageName2 = "microsoft/aci-tutorial-sidecar"; try { //============================================================= // Create a container group with two container instances ContainerGroup containerGroup = azure.containerGroups().define(aciName) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withLinux() .withPublicImageRegistryOnly() .withoutVolume() .defineContainerInstance(aciName + "-1") .withImage(containerImageName1) .withExternalTcpPort(80) .withCpuCoreCount(.5) .withMemorySizeInGB(0.8) .attach() .defineContainerInstance(aciName + "-2") .withImage(containerImageName2) .withoutPorts() .withCpuCoreCount(.5) .withMemorySizeInGB(0.8) .attach() .withRestartPolicy(ContainerGroupRestartPolicy.NEVER) .withDnsPrefix(aciName) .create(); Utils.print(containerGroup); //============================================================= // Check that the container instance is up and running // warm up System.out.println("Warming up " + containerGroup.ipAddress()); Utils.curl("http://" + containerGroup.ipAddress()); SdkContext.sleep(15000); System.out.println("CURLing " + containerGroup.ipAddress()); System.out.println(Utils.curl("http://" + containerGroup.ipAddress())); //============================================================= // Check the container instance logs String logContent = containerGroup.getLogContent(aciName + "-1"); System.out.format("Logs for container instance: %s\n%s", aciName + "-1", logContent); logContent = containerGroup.getLogContent(aciName + "-2"); System.out.format("Logs for container instance: %s\n%s", aciName + "-2", logContent); //============================================================= // Remove the container group azure.containerGroups().deleteById(containerGroup.id()); 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 11
Source File: DeployUsingARMTemplateWithProgress.java From azure-libraries-for-java with MIT License | 4 votes |
/** * 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("rgRSAP", 24); final String deploymentName = SdkContext.randomResourceName("dpRSAP", 24); try { String templateJson = DeployUsingARMTemplateWithProgress.getTemplate(); //============================================================= // 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 App Service: " + deploymentName); azure.deployments().define(deploymentName) .withExistingResourceGroup(rgName) .withTemplate(templateJson) .withParameters("{}") .withMode(DeploymentMode.INCREMENTAL) .beginCreate(); System.out.println("Started a deployment for an Azure App Service: " + 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 12
Source File: ManageWebAppStorageAccountConnection.java From azure-libraries-for-java with MIT License | 4 votes |
/** * 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", ManageWebAppStorageAccountConnection.class.getResource("/helloworld.war").getPath()); uploadFileToContainer(container, "install_apache.sh", ManageWebAppStorageAccountConnection.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) .withNewWindowsPlan(PricingTier.STANDARD_S1) .withJavaVersion(JavaVersion.JAVA_8_NEWEST) .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) .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", ManageWebAppStorageAccountConnection.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 13
Source File: ManageLinuxWebAppStorageAccountConnection.java From azure-libraries-for-java with MIT License | 4 votes |
/** * 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 14
Source File: SecretTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Ignore("Mock framework doesn't support data plane") public void canCRUDSecret() throws Exception { String vaultName = SdkContext.randomResourceName("vault", 20); String secretName = SdkContext.randomResourceName("secret", 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()) .allowSecretAllPermissions() .attach() .create(); Assert.assertNotNull(vault); SdkContext.sleep(10000); Secret secret = vault.secrets().define(secretName) .withValue("Some secret value") .create(); Assert.assertNotNull(secret); Assert.assertNotNull(secret.id()); Assert.assertEquals("Some secret value", secret.value()); secret = secret.update() .withValue("Some updated value") .apply(); Assert.assertEquals("Some updated value", secret.value()); List<Secret> versions = secret.listVersions(); int count = 2; for (Secret version : versions) { if ("Some secret value".equals(version.value())) { count --; } if ("Some updated value".equals(version.value())) { count --; } } Assert.assertEquals(0, count); }
Example 15
Source File: TestApplicationGateway.java From azure-libraries-for-java with MIT License | 4 votes |
@Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { // Prepare a separate thread for resource creation Thread creationThread = new Thread(new Runnable() { @Override public void run() { // Create an application gateway try { resources.define(TestApplicationGateway.APP_GATEWAY_NAME) .withRegion(REGION) .withNewResourceGroup(GROUP_NAME) // Request routing rules .defineRequestRoutingRule("rule1") .fromPublicFrontend() .fromFrontendHttpsPort(443) .withSslCertificateFromPfxFile(new File(getClass().getClassLoader().getResource("myTest.pfx").getFile())) .withSslCertificatePassword("Abc123") .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .create(); } catch (IOException e) { e.printStackTrace(); } } }); // Start the creation... creationThread.start(); //...But bail out after 30 sec, as it is enough to test the results SdkContext.sleep(30 * 1000); // Get the resource as created so far String resourceId = createResourceId(resources.manager().subscriptionId()); ApplicationGateway appGateway = resources.manager().applicationGateways().getById(resourceId); Assert.assertTrue(appGateway != null); Assert.assertTrue(ApplicationGatewayTier.STANDARD.equals(appGateway.tier())); Assert.assertTrue(ApplicationGatewaySkuName.STANDARD_SMALL.equals(appGateway.size())); Assert.assertTrue(appGateway.instanceCount() == 1); // Verify frontend ports Assert.assertTrue(appGateway.frontendPorts().size() == 1); Assert.assertTrue(appGateway.frontendPortNameFromNumber(443) != null); // Verify frontends Assert.assertTrue(!appGateway.isPrivate()); Assert.assertTrue(appGateway.isPublic()); Assert.assertTrue(appGateway.frontends().size() == 1); // Verify listeners Assert.assertTrue(appGateway.listeners().size() == 1); Assert.assertTrue(appGateway.listenerByPortNumber(443) != null); // Verify backends Assert.assertTrue(appGateway.backends().size() == 1); // Verify backend HTTP configs Assert.assertTrue(appGateway.backendHttpConfigurations().size() == 1); // Verify rules Assert.assertTrue(appGateway.requestRoutingRules().size() == 1); ApplicationGatewayRequestRoutingRule rule = appGateway.requestRoutingRules().get("rule1"); Assert.assertTrue(rule != null); Assert.assertTrue(rule.frontendPort() == 443); Assert.assertTrue(ApplicationGatewayProtocol.HTTPS.equals(rule.frontendProtocol())); Assert.assertTrue(rule.listener() != null); Assert.assertTrue(rule.listener().frontend() != null); Assert.assertTrue(rule.listener().frontend().isPublic()); Assert.assertTrue(!rule.listener().frontend().isPrivate()); Assert.assertTrue(rule.backendPort() == 8080); Assert.assertTrue(rule.sslCertificate() != null); Assert.assertTrue(rule.backendAddresses().size() == 2); Assert.assertTrue(rule.backend().containsIPAddress("11.1.1.1")); Assert.assertTrue(rule.backend().containsIPAddress("11.1.1.2")); // Verify certificates Assert.assertTrue(appGateway.sslCertificates().size() == 1); creationThread.join(); return appGateway; }
Example 16
Source File: TestApplicationGateway.java From azure-libraries-for-java with MIT License | 4 votes |
@Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { // Prepare a separate thread for resource creation Thread creationThread = new Thread(new Runnable() { @Override public void run() { // Create an application gateway resources.define(TestApplicationGateway.APP_GATEWAY_NAME) .withRegion(REGION) .withNewResourceGroup(GROUP_NAME) .definePathBasedRoutingRule("pathMap") .fromListener("myListener") .toBackendHttpConfiguration("config1") .toBackend("backendPool") .definePathRule("pathRule") .toBackendHttpConfiguration("config1") .toBackend("backendPool") .withPath("/images/*") .attach() .attach() .defineListener("myListener") .withPublicFrontend() .withFrontendPort(80) .attach() .defineBackend("backendPool") .attach() .defineBackendHttpConfiguration("config1") .withCookieBasedAffinity() .withPort(8081) .withRequestTimeout(33) .attach() .create(); } }); // Start the creation... creationThread.start(); //...But bail out after 30 sec, as it is enough to test the results SdkContext.sleep(60 * 1000); // Get the resource as created so far String resourceId = createResourceId(resources.manager().subscriptionId()); ApplicationGateway appGateway = resources.manager().applicationGateways().getById(resourceId); Assert.assertNotNull(appGateway); Assert.assertEquals(ApplicationGatewayTier.STANDARD, appGateway.tier()); Assert.assertEquals(ApplicationGatewaySkuName.STANDARD_SMALL, appGateway.size()); Assert.assertEquals(1, appGateway.instanceCount()); // Verify frontend ports Assert.assertEquals(1, appGateway.frontendPorts().size()); Assert.assertNotNull(appGateway.frontendPortNameFromNumber(80)); // Verify frontends Assert.assertTrue(appGateway.isPublic()); Assert.assertEquals(1, appGateway.frontends().size()); // Verify listeners Assert.assertEquals(1, appGateway.listeners().size()); Assert.assertNotNull(appGateway.listenerByPortNumber(80)); // Verify backends Assert.assertEquals(1, appGateway.backends().size()); // Verify backend HTTP configs Assert.assertEquals(1, appGateway.backendHttpConfigurations().size()); // Verify rules Assert.assertEquals(1, appGateway.requestRoutingRules().size()); ApplicationGatewayRequestRoutingRule rule = appGateway.requestRoutingRules().get("pathMap"); Assert.assertNotNull(rule); Assert.assertEquals(80, rule.frontendPort()); Assert.assertEquals(ApplicationGatewayProtocol.HTTP, rule.frontendProtocol()); Assert.assertNotNull(rule.listener()); Assert.assertNotNull(rule.listener().frontend()); Assert.assertTrue(rule.listener().frontend().isPublic()); Assert.assertTrue(!rule.listener().frontend().isPrivate()); creationThread.join(); return appGateway; }
Example 17
Source File: TestApplicationGateway.java From azure-libraries-for-java with MIT License | 4 votes |
@Override public ApplicationGateway createResource(final ApplicationGateways resources) throws Exception { // Prepare a separate thread for resource creation Thread creationThread = new Thread(new Runnable() { @Override public void run() { // Create an application gateway resources.define(TestApplicationGateway.APP_GATEWAY_NAME) .withRegion(REGION) .withNewResourceGroup(GROUP_NAME) // Request routing rules .defineRequestRoutingRule("rule1") .fromPrivateFrontend() .fromFrontendHttpPort(80) .toBackendHttpPort(8080) .toBackendIPAddress("11.1.1.1") .toBackendIPAddress("11.1.1.2") .attach() .create(); } }); // Start the creation... creationThread.start(); //...But bail out after 30 sec, as it is enough to test the results SdkContext.sleep(30 * 1000); // Get the resource as created so far String resourceId = createResourceId(resources.manager().subscriptionId()); ApplicationGateway appGateway = resources.manager().applicationGateways().getById(resourceId); Assert.assertTrue(appGateway != null); Assert.assertTrue(ApplicationGatewayTier.STANDARD.equals(appGateway.tier())); Assert.assertTrue(ApplicationGatewaySkuName.STANDARD_SMALL.equals(appGateway.size())); Assert.assertTrue(appGateway.instanceCount() == 1); // Verify frontend ports Assert.assertTrue(appGateway.frontendPorts().size() == 1); Assert.assertTrue(appGateway.frontendPortNameFromNumber(80) != null); // Verify frontends Assert.assertTrue(appGateway.isPrivate()); Assert.assertTrue(!appGateway.isPublic()); Assert.assertTrue(appGateway.frontends().size() == 1); // Verify listeners Assert.assertTrue(appGateway.listeners().size() == 1); Assert.assertTrue(appGateway.listenerByPortNumber(80) != null); // Verify backends Assert.assertTrue(appGateway.backends().size() == 1); // Verify backend HTTP configs Assert.assertTrue(appGateway.backendHttpConfigurations().size() == 1); // Verify rules Assert.assertTrue(appGateway.requestRoutingRules().size() == 1); ApplicationGatewayRequestRoutingRule rule = appGateway.requestRoutingRules().get("rule1"); Assert.assertTrue(rule != null); Assert.assertTrue(rule.frontendPort() == 80); Assert.assertTrue(ApplicationGatewayProtocol.HTTP.equals(rule.frontendProtocol())); Assert.assertTrue(rule.listener() != null); Assert.assertTrue(rule.listener().frontend() != null); Assert.assertTrue(!rule.listener().frontend().isPublic()); Assert.assertTrue(rule.listener().frontend().isPrivate()); Assert.assertTrue(rule.listener().subnetName() != null); Assert.assertTrue(rule.listener().networkId() != null); Assert.assertTrue(rule.backendAddresses().size() == 2); Assert.assertTrue(rule.backend() != null); Assert.assertTrue(rule.backend().containsIPAddress("11.1.1.1")); Assert.assertTrue(rule.backend().containsIPAddress("11.1.1.2")); Assert.assertTrue(rule.backendPort() == 8080); creationThread.join(); return appGateway; }
Example 18
Source File: VirtualNetworkGatewayTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Test @Ignore("Service has bug that cause 'InternalServerError' - record this once service is fixed") // public void testNetworkWatcherTroubleshooting() throws Exception { String gatewayName = SdkContext.randomResourceName("vngw", 8); String connectionName = SdkContext.randomResourceName("vngwc", 8); TestNetworkWatcher tnw = new TestNetworkWatcher(); NetworkWatcher nw = tnw.createResource(azure.networkWatchers()); Region region = nw.region(); String resourceGroup = nw.resourceGroupName(); VirtualNetworkGateway vngw1 = azure.virtualNetworkGateways().define(gatewayName) .withRegion(region) .withExistingResourceGroup(resourceGroup) .withNewNetwork("10.11.0.0/16", "10.11.255.0/27") .withRouteBasedVpn() .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) .create(); VirtualNetworkGateway vngw2 = azure.virtualNetworkGateways().define(gatewayName + "2") .withRegion(region) .withExistingResourceGroup(resourceGroup) .withNewNetwork("10.41.0.0/16", "10.41.255.0/27") .withRouteBasedVpn() .withSku(VirtualNetworkGatewaySkuName.VPN_GW1) .create(); VirtualNetworkGatewayConnection connection1 = vngw1.connections() .define(connectionName) .withVNetToVNet() .withSecondVirtualNetworkGateway(vngw2) .withSharedKey("MySecretKey") .create(); // Create storage account to store troubleshooting information StorageAccount storageAccount = azure.storageAccounts().define("sa" + SdkContext.randomResourceName("", 8)) .withRegion(region) .withExistingResourceGroup(resourceGroup) .create(); // Troubleshoot connection Troubleshooting troubleshooting = nw.troubleshoot() .withTargetResourceId(connection1.id()) .withStorageAccount(storageAccount.id()) .withStoragePath(storageAccount.endPoints().primary().blob() + "results") .execute(); Assert.assertEquals("UnHealthy", troubleshooting.code()); // Create corresponding connection on second gateway to make it work vngw2.connections() .define(connectionName + "2") .withVNetToVNet() .withSecondVirtualNetworkGateway(vngw1) .withSharedKey("MySecretKey") .create(); SdkContext.sleep(250000); troubleshooting = nw.troubleshoot() .withTargetResourceId(connection1.id()) .withStorageAccount(storageAccount.id()) .withStoragePath(storageAccount.endPoints().primary().blob() + "results") .execute(); Assert.assertEquals("Healthy", troubleshooting.code()); azure.resourceGroups().deleteByName(resourceGroup); }
Example 19
Source File: GroupsTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Test public void canCRUDGroup() throws Exception { String userName = SdkContext.randomResourceName("user", 16); String spName = SdkContext.randomResourceName("sp", 16); String group1Name = SdkContext.randomResourceName("group", 16); String group2Name = SdkContext.randomResourceName("group", 16); ActiveDirectoryUser user = null; ServicePrincipal servicePrincipal = null; ActiveDirectoryGroup group1 = null; ActiveDirectoryGroup group2 = null; try { user = graphRbacManager.users().define(userName) .withEmailAlias(userName) .withPassword("StrongPass!123") .create(); servicePrincipal = graphRbacManager.servicePrincipals().define(spName) .withNewApplication("https://" + spName) .create(); group1 = graphRbacManager.groups().define(group1Name) .withEmailAlias(group1Name) .create(); SdkContext.sleep(15000); group2 = graphRbacManager.groups().define(group2Name) .withEmailAlias(group2Name) .withMember(user.id()) .withMember(servicePrincipal.id()) .withMember(group1.id()) .create(); Assert.assertNotNull(group2); Assert.assertNotNull(group2.id()); Set<ActiveDirectoryObject> members = group2.listMembers(); Assert.assertEquals(3, members.size()); Assert.assertNotNull(members.iterator().next().id()); Assert.assertNotNull(members.iterator().next().id()); Assert.assertNotNull(members.iterator().next().id()); Assert.assertNotNull(members.iterator().next().id()); } finally { if (servicePrincipal != null) { graphRbacManager.servicePrincipals().deleteById(servicePrincipal.id()); } // cannot delete users or groups from service principal // if (user != null) { // graphRbacManager.users().deleteById(user.id()); // } // if (group != null) { // graphRbacManager.groups().deleteById(group.id()); // } } }
Example 20
Source File: WebAppsMsiTests.java From azure-libraries-for-java with MIT License | 4 votes |
@Test public void canCRUDWebAppWithUserAssignedMsi() throws Exception { String identityName1 = generateRandomResourceName("msi-id", 15); String identityName2 = generateRandomResourceName("msi-id", 15); // Prepare a definition for yet-to-be-created resource group // Creatable<ResourceGroup> creatableRG = resourceManager.resourceGroups() .define(RG_NAME) .withRegion(Region.US_WEST); // Create an "User Assigned (External) MSI" residing in the above RG and assign reader access to the virtual network // final Identity createdIdentity = msiManager.identities() .define(identityName1) .withRegion(Region.US_WEST) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .create(); // Prepare a definition for yet-to-be-created "User Assigned (External) MSI" with contributor access to the resource group // it resides // Creatable<Identity> creatableIdentity = msiManager.identities() .define(identityName2) .withRegion(Region.US_WEST) .withNewResourceGroup(creatableRG) .withAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR); // Create with new app service plan WebApp webApp = appServiceManager.webApps().define(WEBAPP_NAME_1) .withRegion(Region.US_WEST) .withNewResourceGroup(RG_NAME_1) .withNewWindowsPlan(PricingTier.BASIC_B1) .withRemoteDebuggingEnabled(RemoteVisualStudioVersion.VS2019) .withSystemAssignedManagedServiceIdentity() .withSystemAssignedIdentityBasedAccessToCurrentResourceGroup(BuiltInRole.CONTRIBUTOR) .withJavaVersion(JavaVersion.JAVA_8_NEWEST) .withWebContainer(WebContainer.TOMCAT_8_0_NEWEST) .withUserAssignedManagedServiceIdentity() .withNewUserAssignedManagedServiceIdentity(creatableIdentity) .withExistingUserAssignedManagedServiceIdentity(createdIdentity) .create(); Assert.assertNotNull(webApp); Assert.assertEquals(Region.US_WEST, webApp.region()); AppServicePlan plan = appServiceManager.appServicePlans().getById(webApp.appServicePlanId()); Assert.assertNotNull(plan); Assert.assertEquals(Region.US_WEST, plan.region()); Assert.assertEquals(PricingTier.BASIC_B1, plan.pricingTier()); Assert.assertNotNull(webApp.systemAssignedManagedServiceIdentityPrincipalId()); Assert.assertNotNull(webApp.systemAssignedManagedServiceIdentityTenantId()); Set<String> identityIds = webApp.userAssignedManagedServiceIdentityIds(); Assert.assertNotNull(identityIds); Assert.assertEquals(identityIds.size(), 2); Assert.assertTrue(setContainsValue(identityIds, identityName1)); Assert.assertTrue(setContainsValue(identityIds, identityName2)); if (!isPlaybackMode()) { // Check availability of environment variables uploadFileToWebApp(webApp.getPublishingProfile(), "appservicemsi.war", WebAppsMsiTests.class.getResourceAsStream("/appservicemsi.war")); SdkContext.sleep(10000); Response response = curl("http://" + WEBAPP_NAME_1 + "." + "azurewebsites.net/appservicemsi/"); Assert.assertEquals(200, response.code()); String body = response.body().string(); Assert.assertNotNull(body); Assert.assertTrue(body.contains(webApp.resourceGroupName())); Assert.assertTrue(body.contains(webApp.id())); } }