@Test(enabled = true)
  public void testRegisterTemplate() throws Exception {
    Zone zone = Iterables.getFirst(client.getZoneClient().listZones(), null);
    assertNotNull(zone);
    Iterable<Network> networks =
        client
            .getNetworkClient()
            .listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true));
    networks =
        Iterables.filter(
            networks,
            new Predicate<Network>() {
              @Override
              public boolean apply(@Nullable Network network) {
                return network != null && network.getState().equals("Implemented");
              }
            });
    assertEquals(Iterables.size(networks), 1);
    Network network = Iterables.getOnlyElement(networks, null);
    assertNotNull(network);
    Set<OSType> osTypes = client.getGuestOSClient().listOSTypes();
    OSType osType = Iterables.getFirst(osTypes, null);

    // Register a template
    RegisterTemplateOptions options = RegisterTemplateOptions.Builder.bits(32).isExtractable(true);
    TemplateMetadata templateMetadata =
        TemplateMetadata.builder()
            .name(prefix + "-registerTemplate")
            .osTypeId(osType.getId())
            .displayText("jclouds live testRegisterTemplate")
            .build();
    Set<Template> templates =
        client
            .getTemplateClient()
            .registerTemplate(
                templateMetadata, "VHD", "XenServer", IMPORT_VHD_URL, zone.getId(), options);
    registeredTemplate = Iterables.getOnlyElement(templates, null);
    assertNotNull(registeredTemplate);

    // Ensure it is available
    final long zoneId = zone.getId();
    Predicate<Template> templateReadyPredicate =
        new Predicate<Template>() {
          @Override
          public boolean apply(@Nullable Template template) {
            if (template == null) return false;
            Template t2 = client.getTemplateClient().getTemplateInZone(template.getId(), zoneId);
            Logger.CONSOLE.info("%s", t2.getStatus());
            return "Download Complete".equals(t2.getStatus());
          }
        };
    assertTrue(
        new RetryablePredicate<Template>(templateReadyPredicate, 60000).apply(registeredTemplate));

    // Create a VM that uses this template
    vmForRegistration =
        VirtualMachineClientLiveTest.createVirtualMachineInNetwork(
            network, registeredTemplate.getId(), client, jobComplete, virtualMachineRunning);
    assertNotNull(vmForRegistration);
  }
  @Test(enabled = true)
  public void testCreateTemplate() throws Exception {
    Zone zone = Iterables.getFirst(client.getZoneClient().listZones(), null);
    assertNotNull(zone);
    Iterable<Network> networks =
        client
            .getNetworkClient()
            .listNetworks(ListNetworksOptions.Builder.zoneId(zone.getId()).isDefault(true));
    networks =
        Iterables.filter(
            networks,
            new Predicate<Network>() {
              @Override
              public boolean apply(@Nullable Network network) {
                return network != null && network.getState().equals("Implemented");
              }
            });
    assertEquals(Iterables.size(networks), 1);
    Network network = Iterables.getOnlyElement(networks, null);
    assertNotNull(network);

    // Create a VM and stop it
    Long templateId = (imageId != null && !"".equals(imageId)) ? new Long(imageId) : null;
    vmForCreation =
        VirtualMachineClientLiveTest.createVirtualMachineInNetwork(
            network, templateId, client, jobComplete, virtualMachineRunning);
    assertTrue(
        jobComplete.apply(
            client.getVirtualMachineClient().stopVirtualMachine(vmForCreation.getId())),
        vmForCreation.toString());

    // Work out the VM's volume
    Set<Volume> volumes =
        client
            .getVolumeClient()
            .listVolumes(ListVolumesOptions.Builder.virtualMachineId(vmForCreation.getId()));
    assertEquals(volumes.size(), 1);
    Volume volume = Iterables.getOnlyElement(volumes);

    // Create a template
    CreateTemplateOptions options = CreateTemplateOptions.Builder.volumeId(volume.getId());
    AsyncCreateResponse response =
        client
            .getTemplateClient()
            .createTemplate(
                TemplateMetadata.builder()
                    .name(prefix + "-createTemplate")
                    .osTypeId(vmForCreation.getGuestOSId())
                    .displayText("jclouds live testCreateTemplate")
                    .build(),
                options);
    assertTrue(jobComplete.apply(response.getJobId()), vmForCreation.toString());
    createdTemplate =
        client.getTemplateClient().getTemplateInZone(response.getId(), vmForCreation.getZoneId());

    // Assertions
    assertNotNull(createdTemplate);
  }
  @Test
  public void testCreateVlanIPRange() {
    skipIfNotGlobalAdmin();

    final Zone zone =
        Iterables.find(
            client.getZoneClient().listZones(), ZonePredicates.supportsAdvancedNetworks());
    final NetworkOffering offering =
        find(
            client.getOfferingClient().listNetworkOfferings(),
            NetworkOfferingPredicates.supportsGuestVirtualNetworks());

    Set<Network> suitableNetworks =
        Sets.filter(
            client
                .getNetworkClient()
                .listNetworks(zoneId(zone.getId()).isSystem(false).trafficType(TrafficType.GUEST)),
            new Predicate<Network>() {
              @Override
              public boolean apply(Network network) {
                return network.getNetworkOfferingId().equals(offering.getId());
              }
            });

    if (suitableNetworks.size() > 0) {
      network = Iterables.get(suitableNetworks, 0);
      usingExistingNetwork = true;

    } else if (network == null) {
      network =
          client
              .getNetworkClient()
              .createNetworkInZone(
                  zone.getId(), offering.getId(), "net-" + prefix, "jclouds test " + prefix);
      usingExistingNetwork = false;
    }

    range =
        globalAdminClient
            .getVlanClient()
            .createVlanIPRange(
                "172.19.1.1",
                "172.19.1.199",
                CreateVlanIPRangeOptions.Builder.accountInDomain(
                        user.getAccount(), user.getDomainId())
                    .forVirtualNetwork(true)
                    .vlan(1001)
                    .networkId(network.getId()));
  }
  public void testCreateZoneWhenResponseIs2xxAnd404() {
    GlobalZoneApi client =
        requestSendsResponse(
            createZone,
            HttpResponse.builder()
                .statusCode(200)
                .payload(payloadFromResource("/createzoneresponse.json"))
                .build());

    assertEquals(
        client.createZone("test-zone", NetworkType.BASIC, "8.8.8.8", "10.10.10.10"),
        Zone.builder()
            .id("6")
            .name("test-zone")
            .DNS(ImmutableList.of("8.8.8.8"))
            .internalDNS(ImmutableList.of("10.10.10.10"))
            .networkType(NetworkType.BASIC)
            .securityGroupsEnabled(true)
            .allocationState(AllocationState.ENABLED)
            .zoneToken("7b6e27df-30a6-3024-9d8b-7971a3127f64")
            .dhcpProvider("DhcpServer")
            .build());

    client = requestSendsResponse(createZone, HttpResponse.builder().statusCode(404).build());
    assertNull(client.createZone("test-zone", NetworkType.BASIC, "8.8.8.8", "10.10.10.10"));
  }
 @Test(dependsOnMethods = "testCreateIngress")
 public void testCreateVMInSecurityGroup() throws Exception {
   if (!securityGroupsSupported) return;
   vm =
       VirtualMachineClientLiveTest.createVirtualMachineWithSecurityGroupInZone(
           zone.getId(), group.getId(), client, jobComplete, virtualMachineRunning);
   if (vm.getPassword() != null) password = vm.getPassword();
   // ingress port 22
   checkSSH(new IPSocket(vm.getIPAddress(), 22));
   // ingress icmp disabled as this is platform dependent and may actually
   // just try tcp port 7
   // assert InetAddress.getByName(vm.getIPAddress()).isReachable(1000) : vm;
 }
  public void testUpdateZoneWhenResponseIs2xxAnd404() {
    HttpRequest request =
        HttpRequest.builder()
            .method("GET")
            .endpoint("http://localhost:8080/client/api")
            .addQueryParam("response", "json")
            .addQueryParam("command", "updateZone")
            .addQueryParam("id", "6")
            .addQueryParam("name", "test-zone")
            .addQueryParam("dns1", "8.8.8.8")
            .addQueryParam("apiKey", "identity")
            .addQueryParam("signature", "v19FdHKHztdT0IRloYFFn0eNbWM=")
            .headers(
                ImmutableMultimap.<String, String>builder()
                    .put("Accept", "application/json")
                    .build())
            .build();

    GlobalZoneApi client =
        requestSendsResponse(
            request,
            HttpResponse.builder()
                .statusCode(200)
                .payload(payloadFromResource("/updatezoneresponse.json"))
                .build());

    assertEquals(
        client.updateZone("6", name("test-zone").externalDns(ImmutableList.of("8.8.8.8"))),
        Zone.builder()
            .id("6")
            .name("test-zone")
            .DNS(ImmutableList.of("8.8.8.8"))
            .internalDNS(ImmutableList.of("10.10.10.10"))
            .networkType(NetworkType.BASIC)
            .securityGroupsEnabled(true)
            .allocationState(AllocationState.ENABLED)
            .zoneToken("7b6e27df-30a6-3024-9d8b-7971a3127f64")
            .dhcpProvider("DhcpServer")
            .build());

    client = requestSendsResponse(request, HttpResponse.builder().statusCode(404).build());
    assertNull(client.updateZone("6", name("test-zone").externalDns(ImmutableList.of("8.8.8.8"))));
  }
 protected String getFirstZoneId() throws Exception {
   Zone zone = client.getZoneClient().listZones().iterator().next();
   if (zone != null) return zone.getId();
   else throw new Exception("Not found zone");
 }