@Test public void testApplyWithIllegalStateException() throws UnknownHostException { final NovaApi api = createMock(NovaApi.class); KeyPairApi keyApi = createMock(KeyPairApi.class); @SuppressWarnings("unchecked") final Supplier<String> uniqueIdSupplier = createMock(Supplier.class); KeyPair pair = createMock(KeyPair.class); expect(api.getKeyPairExtensionForZone("zone")).andReturn(Optional.of(keyApi)).atLeastOnce(); expect(uniqueIdSupplier.get()).andReturn("1"); expect(keyApi.createKeyPair("group-1")).andThrow(new IllegalStateException()); expect(uniqueIdSupplier.get()).andReturn("2"); expect(keyApi.createKeyPair("group-2")).andReturn(pair); replay(api, keyApi, uniqueIdSupplier); CreateUniqueKeyPair parser = Guice.createInjector( new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() {}).toInstance(uniqueIdSupplier); bind(NovaApi.class).toInstance(api); } }) .getInstance(CreateUniqueKeyPair.class); assertEquals(parser.load(ZoneAndName.fromZoneAndName("zone", "group")), pair); verify(api, keyApi, uniqueIdSupplier); }
/** * Create a public key in the cloud and write the private key file to the local working directory. */ private KeyPair createKeyPair() throws IOException { System.out.format(" Create Key Pair%n"); KeyPairApi keyPairApi = novaApi.getKeyPairExtensionForZone(ZONE).get(); KeyPair keyPair = keyPairApi.create(NAME); Files.write(keyPair.getPrivateKey(), keyPairFile, UTF_8); System.out.format(" Wrote %s%n", keyPairFile.getAbsolutePath()); return keyPair; }
/** Delete the public key in the cloud and the local private key. */ private void deleteKeyPair(KeyPair keyPair) { System.out.format(" Delete Key Pair%n"); KeyPairApi keyPairApi = novaApi.getKeyPairExtensionForZone(ZONE).get(); keyPairApi.delete(keyPair.getName()); if (keyPairFile.delete()) { System.out.format(" Deleted %s%n", keyPairFile.getAbsolutePath()); } else { System.err.format(" Could not delete %s%n", keyPairFile.getAbsolutePath()); } }
/** * Detect that the OpenStack Key Pair Extension is installed on the Rackspace Cloud. * * <p>This method is not necessary and is here for demonstration purposes only. */ private void detectKeyPairExtension() { Optional<? extends KeyPairApi> keyPairApiExtension = novaApi.getKeyPairExtensionForZone(ZONE); if (keyPairApiExtension.isPresent()) { System.out.format(" Key Pair Extension Present%n"); KeyPairApi keyPairApi = keyPairApiExtension.get(); for (KeyPair keyPair : keyPairApi.list()) { System.out.format(" %s%n", keyPair.getName()); } } }