@AfterTest(groups = {"live"})
  void tearDown() {
    if (volume != null)
      try {
        connection.deleteVolume(volume.getId());
      } catch (Exception e) {

      }
    if (ip != null)
      try {
        connection.releaseAddress(ip.getId());
      } catch (Exception e) {

      }
    if (key != null)
      try {
        connection.deleteKey(key.getName());
      } catch (Exception e) {

      }
    if (instance != null)
      try {
        connection.deleteInstance(instance.getId());
      } catch (Exception e) {

      }
    if (instance2 != null)
      try {
        connection.deleteInstance(instance2.getId());
      } catch (Exception e) {

      }
  }
  @Test(
      dependsOnMethods = {
        "testAddPublicKey",
        "testAllocateIpAddress",
        "testCreateVolume",
        "resolveImageAndInstanceType"
      })
  public void testCreateInstanceWithIpAndVolume() throws Exception {
    String name = TAG + "1";
    killInstance(name);

    instance2 =
        connection.createInstanceInLocation(
            location.getId(),
            name,
            image.getId(),
            instanceType.getId(),
            attachIp(ip.getId())
                .authorizePublicKey(key.getName())
                .mountVolume(volume.getId(), "/mnt"));

    assertBeginState(instance2, name);
    assertIpHostAndStatusNEW(instance2);
    blockUntilRunning(instance2);
    instance2 = assertRunning(instance2, name);

    volume = connection.getVolume(volume.getId());
    assertEquals(volume.getInstanceId(), instance2.getId());

    refreshIpAndReturnAllAddresses();
    assertEquals(ip.getInstanceId(), instance2.getId());
    assertEquals(ip.getIp(), instance2.getIp());
    sshAndDf(
        new IPSocket(instance2.getIp(), 22), new Credentials("idcuser", keyPair.get("private")));
  }
 @Test
 public void testGetInstance() throws Exception {
   Set<? extends Instance> response = connection.listInstances();
   assertNotNull(response);
   if (response.size() > 0) {
     Instance instance = Iterables.get(response, 0);
     assertEquals(connection.getInstance(instance.getId()).getId(), instance.getId());
   }
 }
  private void killInstance(final String nameToKill) {
    Set<? extends Instance> instances = connection.listInstances();
    try {
      Instance instance =
          Iterables.find(
              instances,
              new Predicate<Instance>() {

                @Override
                public boolean apply(Instance input) {
                  return input.getName().equals(nameToKill);
                }
              });
      if (instance.getStatus() != Instance.Status.DEPROVISIONING
          && instance.getStatus() != Instance.Status.DEPROVISION_PENDING) {
        System.out.println("deleting instance: " + instance);
        int timeout =
            (instance.getStatus() == Instance.Status.NEW
                    || instance.getStatus() == Instance.Status.PROVISIONING)
                ? 300
                : 30;
        assert new RetryablePredicate<Instance>(
                    new InstanceActiveOrFailed(connection), timeout, 2, TimeUnit.SECONDS)
                .apply(instance)
            : instance;
        connection.deleteInstance(instance.getId());
      }
      assert new RetryablePredicate<Instance>(
                  new InstanceRemovedOrNotFound(connection), 120, 2, TimeUnit.SECONDS)
              .apply(instance)
          : instance;
    } catch (NoSuchElementException ex) {
    }
  }
 @Test(dependsOnMethods = "testGetLocation")
 public void testAddPublicKey() throws Exception {
   try {
     connection.addPublicKey(TAG, keyPair.get("public"));
     key = connection.getKey(TAG);
     try {
       assert key.getInstanceIds().equals(ImmutableSet.<String>of()) : key;
     } catch (AssertionError e) {
       // inconsistency in the key api when recreating a key
       // http://www-180.ibm.com/cloud/enterprise/beta/ram/community/discussionTopic.faces?guid={DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&fid=1068&tid=1528
     }
   } catch (IllegalStateException e) {
     // must have been found
     connection.updatePublicKey(TAG, keyPair.get("public"));
     key = connection.getKey(TAG);
     for (String instanceId : key.getInstanceIds()) {
       Instance instance = connection.getInstance(instanceId);
       if (instance.getStatus() == Instance.Status.FAILED
           || instance.getStatus() == Instance.Status.ACTIVE) {
         killInstance(instance.getId());
       }
     }
   }
   assertEquals(key.getName(), TAG);
   assert keyPair.get("public").indexOf(key.getKeyMaterial()) > 0;
   assertNotNull(key.getLastModifiedTime());
 }
  @BeforeGroups(groups = {"live"})
  public void setupClient() {

    String endpoint = System.getProperty("jclouds.test.endpoint");
    identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
    String credential =
        checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");

    Properties props = new Properties();
    if (endpoint != null) props.setProperty("ibmdev.endpoint", endpoint);
    context =
        new RestContextFactory()
            .createContext(
                "ibmdev",
                identity,
                credential,
                ImmutableSet.<Module>of(new Log4JLoggingModule()),
                props);

    connection = context.getApi();
    for (Instance instance : connection.listInstances()) {
      try {
        connection.deleteInstance(instance.getId());
      } catch (Exception e) {

      }
    }
  }
  private void blockUntilRunning(Instance instance) {
    long start = System.currentTimeMillis();
    assert new RetryablePredicate<Instance>(new InstanceActive(connection), 15 * 60 * 1000)
            .apply(instance)
        : connection.getInstance(instance.getId());

    System.out.println(((System.currentTimeMillis() - start) / 1000) + " seconds");
  }
 private void assertBeginState(Instance instance, String name) throws AssertionError {
   try {
     assertConsistent(instance, name);
   } catch (NullPointerException e) {
     System.err.println(instance);
     throw e;
   } catch (AssertionError e) {
     killInstance(instance.getId());
     throw e;
   }
 }
 private void assertConsistent(Instance instance, String name) {
   assertNotNull(instance.getId());
   assertEquals(instance.getName(), name);
   assertEquals(instance.getInstanceType(), instanceType.getId());
   assertEquals(instance.getLocation(), location.getId());
   assertEquals(instance.getImageId(), image.getId());
   assertEquals(instance.getSoftware(), SOFTWARE);
   assertEquals(instance.getKeyName(), key.getName());
   assertNotNull(instance.getLaunchTime());
   assertNotNull(instance.getExpirationTime());
   assertEquals(instance.getOwner(), identity);
   assertEquals(instance.getProductCodes(), ImmutableSet.<String>of());
   assertEquals(instance.getRequestName(), name);
   assertNotNull(instance.getRequestId());
 }
  private Instance assertRunning(Instance instance, String name) throws AssertionError {
    instance = connection.getInstance(instance.getId());

    try {
      assertIpHostAndStatusACTIVE(instance);
      assertConsistent(instance, name);
    } catch (NullPointerException e) {
      System.err.println(instance);
      throw e;
    } catch (AssertionError e) {
      System.err.println(instance);
      throw e;
    }
    System.err.println("RUNNING: " + instance);
    return instance;
  }