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());
 }
 private void assertIpHostAndStatusACTIVE(Instance instance) {
   assertNotNull(instance.getIp());
   assertNotNull(instance.getHostname());
   assertEquals(instance.getStatus(), Instance.Status.ACTIVE);
 }
 private void assertIpHostNullAndStatusNEW(Instance instance) {
   assertEquals(instance.getIp(), null);
   assertEquals(instance.getHostname(), null);
   assertEquals(instance.getStatus(), Instance.Status.NEW);
 }