com.microsoft.azure.management.resources.ResourceGroup Java Examples

The following examples show how to use com.microsoft.azure.management.resources.ResourceGroup. 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: ResourceGroupInventoryCollector.java    From pacbot with Apache License 2.0 6 votes vote down vote up
public List<ResourceGroupVH> fetchResourceGroupDetails(SubscriptionVH subscription) {
	List<ResourceGroupVH> resourceGroupList = new ArrayList<>();
	Azure azure = azureCredentialProvider.getClient(subscription.getTenant(),subscription.getSubscriptionId());
	PagedList<ResourceGroup> resourceGroups = azure.resourceGroups().list();
	for (ResourceGroup resourceGroup : resourceGroups) {
		ResourceGroupVH resourceGroupVH = new ResourceGroupVH();
		resourceGroupVH.setSubscription(subscription.getSubscriptionId());
		resourceGroupVH.setSubscriptionName(subscription.getSubscriptionName());
		resourceGroupVH.setId(resourceGroup.id());
		resourceGroupVH.setResourceGroupName(resourceGroup.name());
		resourceGroupVH.setKey(resourceGroup.key());
		resourceGroupVH.setType(resourceGroup.type());
		resourceGroupVH.setProvisioningState(resourceGroup.provisioningState());
		resourceGroupVH.setRegionName(resourceGroup.regionName());
		resourceGroupVH.setTags(resourceGroup.tags());
		resourceGroupList.add(resourceGroupVH);
	}
	log.info("Target Type : {}  Total: {} ","ResourceGroup",resourceGroupList.size());
	return resourceGroupList;
}
 
Example #2
Source File: AzureNetworkTemplateBuilderTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testBuildShouldReturnTheRenderedTemplate() throws IOException, TemplateException {
    NetworkCreationRequest networkCreationRequest = createRequest();
    ResourceGroup resourceGroup = mock(ResourceGroup.class);

    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode expectedJson = objectMapper.readTree(new File("src/test/resources/json/arm-network.json"));

    when(freeMarkerTemplateUtils.processTemplateIntoString(any(), any())).thenCallRealMethod();
    when(resourceGroup.name()).thenReturn("testRg");

    String actual = underTest.build(networkCreationRequest, Lists.newArrayList(
            publicSubnetRequest("10.0.1.0/24", 0),
            publicSubnetRequest("10.0.1.0/24", 1),
            publicSubnetRequest("10.0.1.0/24", 2)),
            resourceGroup.name());

    JsonNode json = objectMapper.readTree(actual);
    assertEquals(expectedJson, json);
    verify(freeMarkerTemplateUtils).processTemplateIntoString(any(Template.class), anyMap());
}
 
Example #3
Source File: AzureNetworkConnector.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
private ResourceGroup getOrCreateResourceGroup(AzureClient azureClient, NetworkCreationRequest networkRequest) {
    String region = networkRequest.getRegion().value();
    Map<String, String> tags = Collections.unmodifiableMap(networkRequest.getTags());
    String resourceGroupName = networkRequest.getResourceGroup();
    ResourceGroup resourceGroup;
    if (StringUtils.isNotEmpty(resourceGroupName)) {
        LOGGER.debug("Fetching existing resource group {}", resourceGroupName);
        resourceGroup = azureClient.getResourceGroup(resourceGroupName);
    } else {
        LOGGER.debug("Creating resource group {}", resourceGroupName);
        String resourceGroupNameForCreation = azureUtils.generateResourceGroupNameByNameAndId(
                String.format("%s-", networkRequest.getEnvName()),
                UUID.randomUUID().toString());
        resourceGroup = azureClient.createResourceGroup(resourceGroupNameForCreation, region, tags);
    }
    return resourceGroup;
}
 
Example #4
Source File: VirtualNetworkGatewaysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<VirtualNetworkGateway> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<VirtualNetworkGateway>>() {
                @Override
                public Observable<VirtualNetworkGateway> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #5
Source File: RegistriesImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Registry> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<Registry>>() {
                @Override
                public Observable<Registry> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #6
Source File: GroupableResourceImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Creates a new resource group to put the resource in, based on the definition specified.
 * @param creatable a creatable definition for a new resource group
 * @return the next stage of the definition
 */
@SuppressWarnings("unchecked")
public final FluentModelImplT withNewResourceGroup(Creatable<ResourceGroup> creatable) {
    this.groupName = creatable.name();
    this.creatableGroup = creatable;
    this.addDependency(creatable);
    return (FluentModelImplT) this;
}
 
Example #7
Source File: ManagementLockImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public ManagementLockImpl withLockedResourceGroup(ResourceGroup resourceGroup) {
    if (resourceGroup != null) {
        this.lockedResourceId = resourceGroup.id();
    } else {
        throw new IllegalArgumentException("Missing resource group ID.");
    }
    return this;
}
 
Example #8
Source File: CosmosDBAccountsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<CosmosDBAccount> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<CosmosDBAccount>>() {
                @Override
                public Observable<CosmosDBAccount> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #9
Source File: AzureNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateNetworkWithSubnetsShouldReturnTheNetworkNameAndSubnetName() {
    String networkCidr = "0.0.0.0/16";
    Set<NetworkSubnetRequest> subnets = new HashSet<>(Arrays.asList(createSubnetRequest(SUBNET_CIDR_0), createSubnetRequest(SUBNET_CIDR_1)));
    Deployment templateDeployment = mock(Deployment.class);
    ResourceGroup resourceGroup = mock(ResourceGroup.class);
    Map<String, Map> outputs = createOutput();

    ArrayList<SubnetRequest> subnetRequests = Lists.newArrayList(
            publicSubnetRequest("10.0.1.0/24", 0),
            publicSubnetRequest("10.0.1.0/24", 1));


    NetworkCreationRequest networkCreationRequest = createNetworkRequest(networkCidr, subnets);
    when(resourceGroup.name()).thenReturn(ENV_NAME);
    when(azureSubnetRequestProvider.provide(anyString(), anyList(), anyList(), anyBoolean())).thenReturn(subnetRequests);
    when(azureUtils.generateResourceGroupNameByNameAndId(anyString(), anyString())).thenReturn(ENV_NAME);
    when(azureClientService.getClient(networkCreationRequest.getCloudCredential())).thenReturn(azureClient);
    when(azureNetworkTemplateBuilder.build(networkCreationRequest, subnetRequests, resourceGroup.name())).thenReturn(TEMPLATE);
    when(azureClient.createTemplateDeployment(ENV_NAME, STACK_NAME, TEMPLATE, PARAMETER)).thenReturn(templateDeployment);
    when(azureClient.createResourceGroup(ENV_NAME, REGION.value(), Collections.emptyMap())).thenReturn(resourceGroup);
    when(resourceGroup.name()).thenReturn(ENV_NAME);
    when(templateDeployment.outputs()).thenReturn(outputs);

    CreatedCloudNetwork actual = underTest.createNetworkWithSubnets(networkCreationRequest);

    assertEquals(ENV_NAME, actual.getNetworkId());
    assertTrue(actual.getSubnets().stream().anyMatch(cloudSubnet -> cloudSubnet.getSubnetId().equals(SUBNET_ID_0)));
    assertTrue(actual.getSubnets().stream().anyMatch(cloudSubnet -> cloudSubnet.getSubnetId().equals(SUBNET_ID_1)));
    assertTrue(actual.getSubnets().size() == 2);
}
 
Example #10
Source File: KubernetesClustersImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<KubernetesCluster> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
        .flatMap(new Func1<ResourceGroup, Observable<KubernetesCluster>>() {
            @Override
            public Observable<KubernetesCluster> call(ResourceGroup resourceGroup) {
                return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
            }
        });
}
 
Example #11
Source File: DeploymentsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<Deployment> listAsync() {
    return this.manager().resourceGroups().listAsync().flatMap(new Func1<ResourceGroup, Observable<Deployment>>() {
        @Override
        public Observable<Deployment> call(ResourceGroup resourceGroup) {
            return listByResourceGroupAsync(resourceGroup.name());
        }
    });
}
 
Example #12
Source File: ResourceGroupImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<ResourceGroup> createResourceAsync() {
    ResourceGroupInner params = new ResourceGroupInner();
    params.withLocation(this.inner().location());
    params.withTags(this.inner().getTags());
    return client.createOrUpdateAsync(this.name(), params)
            .map(innerToFluentMap(this));
}
 
Example #13
Source File: VirtualNetworkGatewayConnectionsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<VirtualNetworkGatewayConnection> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<VirtualNetworkGatewayConnection>>() {
                @Override
                public Observable<VirtualNetworkGatewayConnection> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #14
Source File: LocalNetworkGatewaysImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<LocalNetworkGateway> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<LocalNetworkGateway>>() {
                @Override
                public Observable<LocalNetworkGateway> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #15
Source File: AzureNetworkConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test(expected = CloudConnectorException.class)
public void testDeleteNetworkWithSubNetsShouldThrowAnExceptionWhenTheStackDeletionFailed() {
    NetworkDeletionRequest networkDeletionRequest = createNetworkDeletionRequest();

    when(azureClient.getResourceGroup(networkDeletionRequest.getResourceGroup())).thenReturn(mock(ResourceGroup.class));
    when(azureClientService.getClient(networkDeletionRequest.getCloudCredential())).thenReturn(azureClient);
    doThrow(createCloudException()).when(azureClient).deleteTemplateDeployment(RESOURCE_GROUP, STACK);

    underTest.deleteNetworkWithSubnets(networkDeletionRequest);
}
 
Example #16
Source File: Utils.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
/**
 * Print resource group info.
 *
 * @param resource a resource group
 */
public static void print(ResourceGroup resource) {
    StringBuilder info = new StringBuilder();
    info.append("Resource Group: ").append(resource.id())
            .append("\n\tName: ").append(resource.name())
            .append("\n\tRegion: ").append(resource.region())
            .append("\n\tTags: ").append(resource.tags());
    System.out.println(info.toString());
}
 
Example #17
Source File: GenericResourcesImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Completable moveResourcesAsync(String sourceResourceGroupName, ResourceGroup targetResourceGroup, List<String> resources) {
    ResourcesMoveInfo moveInfo = new ResourcesMoveInfo();
    moveInfo.withTargetResourceGroup(targetResourceGroup.id());
    moveInfo.withResources(resources);
    return this.inner().moveResourcesAsync(sourceResourceGroupName, moveInfo).toCompletable();
}
 
Example #18
Source File: SearchServicesImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<SearchService> listAsync() {
  return this.manager().resourceManager().resourceGroups().listAsync()
      .flatMap(new Func1<ResourceGroup, Observable<SearchService>>() {
        @Override
        public Observable<SearchService> call(ResourceGroup resourceGroup) {
          return wrapListAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
        }
      });
}
 
Example #19
Source File: AvailabilitySetsImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<AvailabilitySet> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<AvailabilitySet>>() {
                @Override
                public Observable<AvailabilitySet> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #20
Source File: ContainerServicesImpl.java    From azure-libraries-for-java with MIT License 5 votes vote down vote up
@Override
public Observable<ContainerService> listAsync() {
    return this.manager().resourceManager().resourceGroups().listAsync()
            .flatMap(new Func1<ResourceGroup, Observable<ContainerService>>() {
                @Override
                public Observable<ContainerService> call(ResourceGroup resourceGroup) {
                    return wrapPageAsync(inner().listByResourceGroupAsync(resourceGroup.name()));
                }
            });
}
 
Example #21
Source File: VirtualMachineScaleSetEMSILMSIOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
private LoadBalancer createInternalLoadBalancer(Region region, ResourceGroup resourceGroup,
                                                  Network network, String id) throws Exception {
    final String loadBalancerName = generateRandomResourceName("InternalLb" + id + "-", 18);
    final String privateFrontEndName = loadBalancerName + "-FE1";
    final String backendPoolName1 = loadBalancerName + "-BAP1";
    final String backendPoolName2 = loadBalancerName + "-BAP2";
    final String natPoolName1 = loadBalancerName + "-INP1";
    final String natPoolName2 = loadBalancerName + "-INP2";
    final String subnetName = "subnet1";

    LoadBalancer loadBalancer = this.networkManager.loadBalancers().define(loadBalancerName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            // Add two rules that uses above backend and probe
            .defineLoadBalancingRule("httpRule")
            .withProtocol(TransportProtocol.TCP)
            .fromFrontend(privateFrontEndName)
            .fromFrontendPort(1000)
            .toBackend(backendPoolName1)
            .withProbe("httpProbe")
            .attach()
            .defineLoadBalancingRule("httpsRule")
            .withProtocol(TransportProtocol.TCP)
            .fromFrontend(privateFrontEndName)
            .fromFrontendPort(1001)
            .toBackend(backendPoolName2)
            .withProbe("httpsProbe")
            .attach()

            // Add two NAT pools to enable direct VM connectivity to port 44 and 45
            .defineInboundNatPool(natPoolName1)
            .withProtocol(TransportProtocol.TCP)
            .fromFrontend(privateFrontEndName)
            .fromFrontendPortRange(8000, 8099)
            .toBackendPort(44)
            .attach()
            .defineInboundNatPool(natPoolName2)
            .withProtocol(TransportProtocol.TCP)
            .fromFrontend(privateFrontEndName)
            .fromFrontendPortRange(9000, 9099)
            .toBackendPort(45)
            .attach()

            // Explicitly define the frontend
            .definePrivateFrontend(privateFrontEndName)
            .withExistingSubnet(network, subnetName) // Frontend with VNET means internal load-balancer
            .attach()

            // Add two probes one per rule
            .defineHttpProbe("httpProbe")
            .withRequestPath("/")
            .attach()
            .defineHttpProbe("httpsProbe")
            .withRequestPath("/")
            .attach()

            .create();
    return loadBalancer;
}
 
Example #22
Source File: ComputeManagementTest.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
protected LoadBalancer createInternalLoadBalancer(Region region, ResourceGroup resourceGroup,
                                                Network network, String id) throws Exception {
    final String loadBalancerName = generateRandomResourceName("InternalLb" + id + "-", 18);
    final String privateFrontEndName = loadBalancerName + "-FE1";
    final String backendPoolName1 = loadBalancerName + "-BAP1";
    final String backendPoolName2 = loadBalancerName + "-BAP2";
    final String natPoolName1 = loadBalancerName + "-INP1";
    final String natPoolName2 = loadBalancerName + "-INP2";
    final String subnetName = "subnet1";

    LoadBalancer loadBalancer = this.networkManager.loadBalancers().define(loadBalancerName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            // Add two rules that uses above backend and probe
            .defineLoadBalancingRule("httpRule")
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(privateFrontEndName)
                .fromFrontendPort(1000)
                .toBackend(backendPoolName1)
                .withProbe("httpProbe")
                .attach()
            .defineLoadBalancingRule("httpsRule")
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(privateFrontEndName)
                .fromFrontendPort(1001)
                .toBackend(backendPoolName2)
                .withProbe("httpsProbe")
                .attach()

            // Add two NAT pools to enable direct VM connectivity to port 44 and 45
            .defineInboundNatPool(natPoolName1)
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(privateFrontEndName)
                .fromFrontendPortRange(8000, 8099)
                .toBackendPort(44)
                .attach()
            .defineInboundNatPool(natPoolName2)
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(privateFrontEndName)
                .fromFrontendPortRange(9000, 9099)
                .toBackendPort(45)
                .attach()

            // Explicitly define the frontend
            .definePrivateFrontend(privateFrontEndName)
                .withExistingSubnet(network, subnetName) // Frontend with VNET means internal load-balancer
                .attach()

            // Add two probes one per rule
            .defineHttpProbe("httpProbe")
                .withRequestPath("/")
                .attach()
            .defineHttpProbe("httpsProbe")
                .withRequestPath("/")
                .attach()

            .create();
    return loadBalancer;
}
 
Example #23
Source File: ManagedDiskOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canOperateOnManagedDiskFromDisk() {
    final String diskName1 = generateRandomResourceName("md-1", 20);
    final String diskName2 = generateRandomResourceName("md-2", 20);

    ResourceGroup resourceGroup = resourceManager
            .resourceGroups()
            .define(RG_NAME)
            .withRegion(region)
            .create();

    // Create an empty  managed disk
    //
    Disk emptyDisk = computeManager.disks()
            .define(diskName1)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup.name())
            .withData()
            .withSizeInGB(100)
            .create();

    // Create a managed disk from existing managed disk
    //
    Disk disk = computeManager.disks()
            .define(diskName2)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup.name())
            .withData()
            .fromDisk(emptyDisk)
            // Start Option
            .withSizeInGB(200)
            .withSku(DiskSkuTypes.STANDARD_LRS)
            // End Option
            .create();

    disk = computeManager.disks().getById(disk.id());

    Assert.assertNotNull(disk.id());
    Assert.assertTrue(disk.name().equalsIgnoreCase(diskName2));
    Assert.assertEquals(disk.sku(), DiskSkuTypes.STANDARD_LRS);
    Assert.assertEquals(disk.creationMethod(), DiskCreateOption.COPY);
    Assert.assertFalse(disk.isAttachedToVirtualMachine());
    Assert.assertEquals(disk.sizeInGB(), 200);
    Assert.assertNull(disk.osType());
    Assert.assertNotNull(disk.source());
    Assert.assertEquals(disk.source().type(), CreationSourceType.COPIED_FROM_DISK);
    Assert.assertTrue(disk.source().sourceId().equalsIgnoreCase(emptyDisk.id()));

    computeManager.disks().deleteById(emptyDisk.id());
    computeManager.disks().deleteById(disk.id());
}
 
Example #24
Source File: ComputeManagementTest.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
protected LoadBalancer createHttpLoadBalancers(Region region, ResourceGroup resourceGroup,
                                             String id) throws Exception {
    final String loadBalancerName = generateRandomResourceName("extlb" + id + "-", 18);
    final String publicIpName = "pip-" + loadBalancerName;
    final String frontendName = loadBalancerName + "-FE1";
    final String backendPoolName = loadBalancerName + "-BAP1";
    final String natPoolName = loadBalancerName + "-INP1";

    PublicIPAddress publicIPAddress = this.networkManager.publicIPAddresses().define(publicIpName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withLeafDomainLabel(publicIpName)
            .create();

    LoadBalancer loadBalancer = this.networkManager.loadBalancers().define(loadBalancerName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            // Add two rules that uses above backend and probe
            .defineLoadBalancingRule("httpRule")
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPort(80)
                .toBackend(backendPoolName)
                .withProbe("httpProbe")
                .attach()
            .defineInboundNatPool(natPoolName)
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPortRange(5000, 5099)
                .toBackendPort(22)
                .attach()
            // Explicitly define the frontend
            .definePublicFrontend(frontendName)
                .withExistingPublicIPAddress(publicIPAddress)
                .attach()
            // Add an HTTP probe
            .defineHttpProbe("httpProbe")
                .withRequestPath("/")
                .attach()

            .create();
    return loadBalancer;

}
 
Example #25
Source File: ComputeManagementTest.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
protected LoadBalancer createInternetFacingLoadBalancer(Region region, ResourceGroup resourceGroup, String id, LoadBalancerSkuType lbSkuType) throws Exception {
    final String loadBalancerName = generateRandomResourceName("extlb" + id + "-", 18);
    final String publicIPName = "pip-" + loadBalancerName;
    final String frontendName = loadBalancerName + "-FE1";
    final String backendPoolName1 = loadBalancerName + "-BAP1";
    final String backendPoolName2 = loadBalancerName + "-BAP2";
    final String natPoolName1 = loadBalancerName + "-INP1";
    final String natPoolName2 = loadBalancerName + "-INP2";

    // Sku of PublicIP and LoadBalancer must match
    //
    PublicIPSkuType publicIPSkuType = lbSkuType.equals(LoadBalancerSkuType.BASIC) ? PublicIPSkuType.BASIC : PublicIPSkuType.STANDARD;

    PublicIPAddress publicIPAddress = this.networkManager.publicIPAddresses().define(publicIPName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withLeafDomainLabel(publicIPName)
            // Optionals
            .withStaticIP()
            .withSku(publicIPSkuType)
            // Create
            .create();

    LoadBalancer loadBalancer = this.networkManager.loadBalancers().define(loadBalancerName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)

            // Add two rules that uses above backend and probe
            .defineLoadBalancingRule("httpRule")
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPort(80)
                .toBackend(backendPoolName1)
                .withProbe("httpProbe")
                .attach()
            .defineLoadBalancingRule("httpsRule")
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPort(443)
                .toBackend(backendPoolName2)
                .withProbe("httpsProbe")
                .attach()

            // Add two nat pools to enable direct VM connectivity to port SSH and 23
            .defineInboundNatPool(natPoolName1)
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPortRange(5000, 5099)
                .toBackendPort(22)
                .attach()
            .defineInboundNatPool(natPoolName2)
                .withProtocol(TransportProtocol.TCP)
                .fromFrontend(frontendName)
                .fromFrontendPortRange(6000, 6099)
                .toBackendPort(23)
                .attach()

            // Explicitly define the frontend
            .definePublicFrontend(frontendName)
                .withExistingPublicIPAddress(publicIPAddress)   // Frontend with PIP means internet-facing load-balancer
                .attach()

                // Add two probes one per rule
            .defineHttpProbe("httpProbe")
                .withRequestPath("/")
                .attach()
            .defineHttpProbe("httpsProbe")
                .withRequestPath("/")
                .attach()
            .withSku(lbSkuType)
            .create();
    return loadBalancer;
}
 
Example #26
Source File: ServiceBusOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canPerformCRUDOnSubscriptions() {
    Region region = Region.US_EAST;
    Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region);

    String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
    String topicName = generateRandomResourceName("topic1-", 15);
    String subscriptionName = generateRandomResourceName("sub1-", 15);
    // Create NS with Topic
    //
    ServiceBusNamespace namespace = serviceBusManager.namespaces()
            .define(namespaceDNSLabel)
            .withRegion(region)
            .withNewResourceGroup(rgCreatable)
            .withSku(NamespaceSku.STANDARD)
            .withNewTopic(topicName, 1024)
            .create();
    // Create Topic subscriptions and list it
    //
    Topic topic = namespace.topics().getByName(topicName);
    ServiceBusSubscription subscription = topic.subscriptions().define(subscriptionName)
            .withDefaultMessageTTL(new Period().withMinutes(20))
            .create();
    Assert.assertNotNull(subscription);
    Assert.assertNotNull(subscription.inner());
    Assert.assertEquals(20, subscription.defaultMessageTtlDuration().getMinutes());
    subscription = topic.subscriptions().getByName(subscriptionName);
    Assert.assertNotNull(subscription);
    Assert.assertNotNull(subscription.inner());
    PagedList<ServiceBusSubscription> subscriptionsInTopic = topic.subscriptions().list();
    Assert.assertTrue(subscriptionsInTopic.size() > 0);
    boolean foundSubscription = false;
    for (ServiceBusSubscription s : subscriptionsInTopic) {
        if (s.name().equalsIgnoreCase(subscription.name())) {
            foundSubscription = true;
            break;
        }
    }
    Assert.assertTrue(foundSubscription);
    topic.subscriptions().deleteByName(subscriptionName);
    subscriptionsInTopic = topic.subscriptions().list();
    Assert.assertTrue(subscriptionsInTopic.size() == 0);
}
 
Example #27
Source File: TestResourceStreaming.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@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;
}
 
Example #28
Source File: ManagedDiskOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canOperateOnEmptyManagedDisk() {
    final String diskName = generateRandomResourceName("md-empty-", 20);
    final DiskSkuTypes updateTo = DiskSkuTypes.STANDARD_LRS;

    ResourceGroup resourceGroup = resourceManager
            .resourceGroups()
            .define(RG_NAME)
            .withRegion(region)
            .create();

    // Create an empty managed disk
    //
    Disk disk = computeManager.disks()
            .define(diskName)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup.name())
            .withData()
            .withSizeInGB(100)
            // Start option
            .withSku(DiskSkuTypes.STANDARD_LRS)
            .withTag("tkey1", "tval1")
            // End option
            .create();

    Assert.assertNotNull(disk.id());
    Assert.assertTrue(disk.name().equalsIgnoreCase(diskName));
    Assert.assertEquals(disk.sku(), DiskSkuTypes.STANDARD_LRS);
    Assert.assertEquals(disk.creationMethod(), DiskCreateOption.EMPTY);
    Assert.assertFalse(disk.isAttachedToVirtualMachine());
    Assert.assertEquals(disk.sizeInGB(), 100);
    Assert.assertNull(disk.osType());
    Assert.assertNotNull(disk.source());
    Assert.assertEquals(disk.source().type(), CreationSourceType.EMPTY);
    Assert.assertNull(disk.source().sourceId());

    // Resize and change storage account type
    //
    disk = disk.update()
            .withSku(updateTo)
            .withSizeInGB(200)
            .apply();

    Assert.assertEquals(disk.sku(), updateTo);
    Assert.assertEquals(disk.sizeInGB(), 200);

    disk = computeManager.disks().getByResourceGroup(disk.resourceGroupName(), disk.name());
    Assert.assertNotNull(disk);

    PagedList<Disk> myDisks = computeManager.disks().listByResourceGroup(disk.resourceGroupName());
    Assert.assertNotNull(myDisks);
    Assert.assertTrue(myDisks.size() > 0);

    String sasUrl = disk.grantAccess(100);
    Assert.assertTrue(sasUrl != null && sasUrl != "");

    // Requires access to be revoked before deleting the disk
    //
    disk.revokeAccess();
    computeManager.disks().deleteById(disk.id());
}
 
Example #29
Source File: ServiceBusOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canCreateDeleteTopicWithNamespace() {
    Region region = Region.US_EAST;
    Creatable<ResourceGroup> rgCreatable = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region);

    String namespaceDNSLabel = generateRandomResourceName("jvsbns", 15);
    String topicName = generateRandomResourceName("topic1-", 15);
    // Create NS with Topic
    //
    ServiceBusNamespace namespace = serviceBusManager.namespaces()
            .define(namespaceDNSLabel)
            .withRegion(region)
            .withNewResourceGroup(rgCreatable)
            .withSku(NamespaceSku.STANDARD)
            .withNewTopic(topicName, 1024)
            .create();
    Assert.assertNotNull(namespace);
    Assert.assertNotNull(namespace.inner());
    // Lookup topic
    //
    PagedList<Topic> topicsInNamespace = namespace.topics().list();
    Assert.assertNotNull(topicsInNamespace);
    Assert.assertEquals(1, topicsInNamespace.size());
    Topic foundTopic = null;
    for (Topic t : topicsInNamespace) {
        if (t.name().equalsIgnoreCase(topicName)) {
            foundTopic = t;
            break;
        }
    }
    Assert.assertNotNull(foundTopic);
    // Remove Topic
    //
    namespace.update()
            .withoutTopic(topicName)
            .apply();
    topicsInNamespace = namespace.topics().list();
    Assert.assertNotNull(topicsInNamespace);
    Assert.assertEquals(0, topicsInNamespace.size());
}
 
Example #30
Source File: VirtualMachineManagedDiskOperationsTests.java    From azure-libraries-for-java with MIT License 4 votes vote down vote up
@Test
public void canUpdateVirtualMachineByAddingAndRemovingManagedDisks() {
    final String publicIpDnsLabel = generateRandomResourceName("pip", 20);
    final String uname = "juser";
    final String password = "123tEst!@|ac";
    // Create with implicit + explicit empty disks, check default and override
    //
    final String vmName1 = "myvm1";
    final String explicitlyCreatedEmptyDiskName1 = generateRandomResourceName(vmName1 + "_mdisk_", 25);
    final String explicitlyCreatedEmptyDiskName2 = generateRandomResourceName(vmName1 + "_mdisk_", 25);
    final String explicitlyCreatedEmptyDiskName3 = generateRandomResourceName(vmName1 + "_mdisk_", 25);

    ResourceGroup resourceGroup = resourceManager.resourceGroups()
            .define(RG_NAME)
            .withRegion(region)
            .create();

    Creatable<Disk> creatableEmptyDisk1 = computeManager.disks()
            .define(explicitlyCreatedEmptyDiskName1)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withData()
            .withSizeInGB(150);

    Creatable<Disk> creatableEmptyDisk2 = computeManager.disks()
            .define(explicitlyCreatedEmptyDiskName2)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withData()
            .withSizeInGB(150);

    Creatable<Disk> creatableEmptyDisk3 = computeManager.disks()
            .define(explicitlyCreatedEmptyDiskName3)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withData()
            .withSizeInGB(150);

    VirtualMachine virtualMachine1 = computeManager.virtualMachines().define(vmName1)
            .withRegion(region)
            .withExistingResourceGroup(resourceGroup)
            .withNewPrimaryNetwork("10.0.0.0/28")
            .withPrimaryPrivateIPAddressDynamic()
            .withNewPrimaryPublicIPAddress(publicIpDnsLabel)
            .withPopularLinuxImage(linuxImage)
            .withRootUsername(uname)
            .withRootPassword(password)
            // Start: Add bunch of empty managed disks
            .withNewDataDisk(100)                                             // CreateOption: EMPTY
            .withNewDataDisk(100, 1, CachingTypes.READ_WRITE)                 // CreateOption: EMPTY
            .withNewDataDisk(creatableEmptyDisk1)                             // CreateOption: ATTACH
            .withNewDataDisk(creatableEmptyDisk2, 2, CachingTypes.NONE)       // CreateOption: ATTACH
            .withNewDataDisk(creatableEmptyDisk3, 3, CachingTypes.NONE)       // CreateOption: ATTACH
            // End : Add bunch of empty managed disks
            .withDataDiskDefaultCachingType(CachingTypes.READ_ONLY)
            .withDataDiskDefaultStorageAccountType(StorageAccountTypes.STANDARD_LRS)
            .withSize(VirtualMachineSizeTypes.STANDARD_D5_V2)
            .withOSDiskCaching(CachingTypes.READ_WRITE)
            .create();

    virtualMachine1.update()
            .withoutDataDisk(1)
            .withNewDataDisk(100, 6, CachingTypes.READ_WRITE)                 // CreateOption: EMPTY
            .apply();

    Map<Integer, VirtualMachineDataDisk> dataDisks = virtualMachine1.dataDisks();
    Assert.assertNotNull(dataDisks);
    Assert.assertEquals(dataDisks.size(), 5); // Removed one added another
    Assert.assertTrue(dataDisks.containsKey(6));
    Assert.assertFalse(dataDisks.containsKey(1));
}