CreateUniqueKeyPair extends CacheLoader<ZoneAndName, KeyPair> { @Override public KeyPair load(ZoneAndName zoneAndName) { String zoneId = checkNotNull(zoneAndName, "zoneAndName").getZone(); String prefix = zoneAndName.getName(); Optional<? extends KeyPairApi> api = novaApi.getKeyPairExtensionForZone(zoneId); checkArgument(api.isPresent(), "Key pairs are required, but the extension is not available in zone %s!", zoneId); logger.debug(">> creating keyPair zone(%s) prefix(%s)", zoneId, prefix); KeyPair keyPair = null; while (keyPair == null) { try { keyPair = api.get().create(namingConvention.createWithoutPrefix().uniqueNameForGroup(prefix)); } catch (IllegalStateException e) { } } logger.debug("<< created keyPair(%s)", keyPair.getName()); return keyPair; } @Inject  CreateUniqueKeyPair(NovaApi novaApi, GroupNamingConvention.Factory namingConvention); @Override KeyPair load(ZoneAndName zoneAndName);  }
@Test public void testApply() throws UnknownHostException { final NovaApi api = createMock(NovaApi.class); KeyPairApi keyApi = createMock(KeyPairApi.class); KeyPair pair = createMock(KeyPair.class); Optional optKeyApi = Optional.of(keyApi); expect(api.getKeyPairExtensionForZone("zone")).andReturn(optKeyApi).atLeastOnce(); expect(keyApi.create("group-1")).andReturn(pair); replay(api, keyApi); CreateUniqueKeyPair parser = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bind(new TypeLiteral<Supplier<String>>() { }).toInstance(Suppliers.ofInstance("1")); bind(NovaApi.class).toInstance(api); } }).getInstance(CreateUniqueKeyPair.class); assertEquals(parser.load(ZoneAndName.fromZoneAndName("zone", "group")), pair); verify(api, keyApi); }
@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) Optional.of(keyApi)).atLeastOnce(); expect(uniqueIdSupplier.get()).andReturn("1"); expect(keyApi.create("group-1")).andThrow(new IllegalStateException()); expect(uniqueIdSupplier.get()).andReturn("2"); expect(keyApi.create("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); }