src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
BindLoggersAnnotatedWithResource implements TypeListener { public <I> void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter) { Class<? super I> type = injectableType.getRawType(); Set<Field> loggerFields = getLoggerFieldsAnnotatedWithResource(type); if (loggerFields.isEmpty()) return; Logger logger = loggerFactory.getLogger(type.getName()); for (Field field : loggerFields) { if (field.isAnnotationPresent(Named.class)) { Named name = field.getAnnotation(Named.class); encounter.register(new AssignLoggerToField<I>(loggerFactory.getLogger(name.value()), field)); } else { encounter.register(new AssignLoggerToField<I>(logger, field)); } } } @Inject BindLoggersAnnotatedWithResource(LoggerFactory loggerFactory); void hear(TypeLiteral<I> injectableType, TypeEncounter<I> encounter); }
@Test void testHear() { Injector i = Guice.createInjector(new AbstractModule() { @Override protected void configure() { bindListener(any(), blawr); } }); assertEquals(i.getInstance(A.class).logger.getCategory(), getClass().getName() + "$A"); assertEquals(i.getInstance(B.class).logger.getCategory(), getClass().getName() + "$B"); assertEquals(i.getInstance(B.class).blogger.getCategory(), "blogger"); }
HeaderToRetryAfterException implements PropagateIfRetryAfter { @Override public Object createOrPropagate(Throwable t) throws Exception { if (!(t instanceof HttpResponseException)) throw propagate(t); HttpResponse response = HttpResponseException.class.cast(t).getResponse(); if (response == null) { return null; } String retryAfter = response.getFirstHeaderOrNull(HttpHeaders.RETRY_AFTER); if (retryAfter != null) { Optional<RetryAfterException> retryException = tryCreateRetryAfterException(t, retryAfter); if (retryException.isPresent()) throw retryException.get(); } return null; } @Inject private HeaderToRetryAfterException(DateCodecFactory factory); private HeaderToRetryAfterException(Ticker ticker, DateCodec dateCodec); static HeaderToRetryAfterException create(Ticker ticker, DateCodec dateCodec); @Override Object createOrPropagate(Throwable t); Optional<RetryAfterException> tryCreateRetryAfterException(Throwable in, String retryAfter); }
@Test(expectedExceptions = RuntimeException.class) public void testArbitraryExceptionDoesntConvert() throws Exception { fn.createOrPropagate(new RuntimeException()); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT") .build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(503).addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT") .build())); }
MapHttp4xxCodesToExceptions implements Fallback<Object> { @Override public Object createOrPropagate(Throwable t) throws Exception { propagateIfRetryAfter.createOrPropagate(t); if (t instanceof HttpResponseException) { HttpResponseException responseException = HttpResponseException.class.cast(t); if (responseException.getResponse() != null) switch (responseException.getResponse().getStatusCode()) { case 401: throw new AuthorizationException(responseException); case 403: throw new AuthorizationException(responseException); case 404: throw new ResourceNotFoundException(responseException); case 409: throw new IllegalStateException(responseException); } } throw propagate(t); } @Inject MapHttp4xxCodesToExceptions(PropagateIfRetryAfter propagateIfRetryAfter); @Override Object createOrPropagate(Throwable t); }
@Test(expectedExceptions = AuthorizationException.class) public void test401ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(401).build())); } @Test(expectedExceptions = AuthorizationException.class) public void test403ToAuthorizationException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(403).build())); } @Test(expectedExceptions = ResourceNotFoundException.class) public void test404ToResourceNotFoundException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(404).build())); } @Test(expectedExceptions = IllegalStateException.class) public void test409ToIllegalStateException() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder().statusCode(409).build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfterDate() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Fri, 31 Dec 1999 23:59:59 GMT").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 700 seconds") public void testHttpResponseExceptionWithRetryAfterOffset() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "700").build())); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry in 86400 seconds") public void testHttpResponseExceptionWithRetryAfterPastIsZero() throws Exception { fn.createOrPropagate(new HttpResponseException(command, HttpResponse.builder() .statusCode(503) .addHeader(HttpHeaders.RETRY_AFTER, "Sun, 2 Jan 2000 00:00:00 GMT").build())); }
Providers { public static ProviderMetadata withId(String id) throws NoSuchElementException { return find(all(), ProviderPredicates.id(id)); } static Function<ProviderMetadata, String> idFunction(); static Function<ProviderMetadata, ApiMetadata> apiMetadataFunction(); static Iterable<ProviderMetadata> fromServiceLoader(); static Iterable<ProviderMetadata> all(); static ProviderMetadata withId(String id); static Iterable<ProviderMetadata> viewableAs(TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> viewableAs(Class<? extends View> viewableAs); static Iterable<ProviderMetadata> apiMetadataAssignableFrom(TypeToken<? extends ApiMetadata> api); static Iterable<ProviderMetadata> contextAssignableFrom( TypeToken<? extends Context> context); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code, TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> boundedByIso3166Code(String iso3166Code, Class<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata, TypeToken<? extends View> viewableAs); static Iterable<ProviderMetadata> collocatedWith(ProviderMetadata providerMetadata, Class<? extends View> viewableAs); }
@Test public void testWithId() { ProviderMetadata providerMetadata; try { providerMetadata = Providers.withId("fake-id"); fail("Looking for a provider with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } providerMetadata = Providers.withId(testBlobstoreProvider.getId()); assertEquals(testBlobstoreProvider, providerMetadata); assertNotEquals(testBlobstoreProvider, testComputeProvider); assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider); } @Test public void testWithId() { ProviderMetadata providerMetadata; try { providerMetadata = Providers.withId("fake-id"); fail("Looking for a provider with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { ; } providerMetadata = Providers.withId(testBlobstoreProvider.getId()); assertEquals(testBlobstoreProvider, providerMetadata); assertNotEquals(testBlobstoreProvider, testComputeProvider); assertNotEquals(testBlobstoreProvider, testYetAnotherComputeProvider); }
UpdateProviderMetadataFromProperties implements Function<Properties, ProviderMetadata> { @Override public ProviderMetadata apply(Properties input) { Properties mutable = new Properties(); mutable.putAll(input); ApiMetadata apiMetadata = this.apiMetadata.toBuilder() .name(getAndRemove(mutable, PROPERTY_API, this.apiMetadata.getName())) .version(getAndRemove(mutable, PROPERTY_API_VERSION, this.apiMetadata.getVersion())) .buildVersion(getAndRemove(mutable, PROPERTY_BUILD_VERSION, this.apiMetadata.getBuildVersion().orNull())).build(); String endpoint = getAndRemove(mutable, PROPERTY_ENDPOINT, providerMetadata.isPresent() ? providerMetadata.get() .getEndpoint() : null); String providerId = getAndRemove(mutable, PROPERTY_PROVIDER, providerMetadata.isPresent() ? providerMetadata.get() .getId() : apiMetadata.getId()); String isoCodes = getAndRemove(mutable, PROPERTY_ISO3166_CODES, providerMetadata.isPresent() ? Joiner.on(',').join(providerMetadata.get() .getIso3166Codes()) : ""); ProviderMetadata providerMetadata = this.providerMetadata .or(AnonymousProviderMetadata.forApiWithEndpoint(apiMetadata, checkNotNull(endpoint, PROPERTY_ENDPOINT))) .toBuilder() .apiMetadata(apiMetadata) .id(providerId) .iso3166Codes(Splitter.on(',').omitEmptyStrings().split(isoCodes)) .endpoint(endpoint).defaultProperties(mutable).build(); return providerMetadata; } UpdateProviderMetadataFromProperties(ProviderMetadata providerMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata); UpdateProviderMetadataFromProperties(ApiMetadata apiMetadata, Optional<ProviderMetadata> providerMetadata); @Override ProviderMetadata apply(Properties input); }
@Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getEndpoint(), "http: assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(PROPERTY_ISO3166_CODES, "US-CA"); ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getIso3166Codes(), ImmutableSet.of("US-CA")); assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint( IntegrationTestClient.class, IntegrationTestAsyncClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getEndpoint(), "http: assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); } @Test public void testProviderMetadataWithUpdatedIso3166CodesUpdatesAndRetainsAllDefaultPropertiesExceptIso3166Codes() { ProviderMetadata md = AnonymousProviderMetadata.forClientMappedToAsyncClientOnEndpoint( IntegrationTestClient.class, IntegrationTestAsyncClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(PROPERTY_ISO3166_CODES, "US-CA"); ProviderMetadata newMd = new UpdateProviderMetadataFromProperties(md).apply(props); assertEquals(newMd.getIso3166Codes(), ImmutableSet.of("US-CA")); assertEquals(newMd.getDefaultProperties(), md.getDefaultProperties()); }
ContextLinking { public static Module linkView(final String id, final Supplier<View> view) { return new AbstractModule() { @Override protected void configure() { bind(VIEW_SUPPLIER).annotatedWith(Names.named(id)).toInstance(view); bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(Suppliers.compose(ViewToContext, view)); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }
@Test public void testLinkedViewBindsViewAndContextSuppliers() { Injector injector = Guice.createInjector(linkView(new DummyView(contextFor(IntegrationTestClient.class)))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); assertNotNull(injector.getExistingBinding(Key.get(VIEW_SUPPLIER, Names.named("IntegrationTestClient")))); }
ContextLinking { public static Module linkContext(final String id, final Supplier<Context> context) { return new AbstractModule() { @Override protected void configure() { bind(CONTEXT_SUPPLIER).annotatedWith(Names.named(id)).toInstance(context); } }; } static Module linkView(final String id, final Supplier<View> view); static Module linkContext(final String id, final Supplier<Context> context); static Module linkView(View view); static Module linkContext(Context context); }
@Test public void testLinkedContextBindsContextSupplier() { Injector injector = Guice.createInjector(linkContext(contextFor(IntegrationTestClient.class))); assertNotNull(injector.getExistingBinding(Key.get(CONTEXT_SUPPLIER, Names.named("IntegrationTestClient")))); }
ArgsToPagedIterable implements Function<IterableWithMarker<T>, PagedIterable<T>>, InvocationContext<I> { @Override public PagedIterable<T> apply(IterableWithMarker<T> input) { return input.nextMarker().isPresent() ? advance(input, markerToNextForArgs(getArgs(request))) : onlyPage(input); } @Override PagedIterable<T> apply(IterableWithMarker<T> input); @SuppressWarnings("unchecked") @Override I setContext(HttpRequest request); }
@Test public void testWhenNextMarkerAbsentDoesntAdvance() { GeneratedHttpRequest request = args(ImmutableList.of()); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { fail("The Iterable should not advance"); return null; } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"))).concat().toSet(), ImmutableSet.of("foo", "bar")); } @Test public void testWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = args(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = args(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestArgs converter = new TestArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testFromCallerWhenNextMarkerPresentButNoArgsMarkerToNextForArgsParamIsAbsent() { GeneratedHttpRequest request = callerArgs(ImmutableList.of()); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertTrue(args.isEmpty()); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); } @Test public void testFromCallerWhenNextMarkerPresentWithArgsMarkerToNextForArgsParamIsPresent() { GeneratedHttpRequest request = callerArgs(ImmutableList.<Object> of("path")); final IterableWithMarker<String> next = IterableWithMarkers.from(ImmutableSet.of("baz")); TestCallerArgs converter = new TestCallerArgs(request) { @Override protected Function<Object, IterableWithMarker<String>> markerToNextForArgs(List<Object> args) { assertEquals(args.get(0), "path"); return Functions.constant(next); } }; assertEquals(converter.apply(IterableWithMarkers.from(ImmutableSet.of("foo", "bar"), "marker")).concat().toSet(), ImmutableSet.of("foo", "bar", "baz")); }
ExecutorServiceModule extends AbstractModule { static <T extends ListeningExecutorService> T shutdownOnClose(final T service, Closer closer) { closer.addToClose(new ShutdownExecutorOnClose(service)); return service; } ExecutorServiceModule(); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor, ExecutorService ioExecutor); @Deprecated ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor, ListeningExecutorService ioExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ExecutorService userExecutor); ExecutorServiceModule(@Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); static SimpleTimeLimiter createSimpleTimeLimiter(ExecutorService executorService); }
@Test public void testShutdownOnClose() throws IOException { Injector i = Guice.createInjector(); Closer closer = i.getInstance(Closer.class); ListeningExecutorService executor = createMock(ListeningExecutorService.class); ExecutorServiceModule.shutdownOnClose(executor, closer); expect(executor.shutdownNow()).andReturn(ImmutableList.<Runnable> of()).atLeastOnce(); replay(executor); closer.close(); verify(executor); }
ZoneToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> zoneIds = zoneIdsSupplier.get(); checkState(!zoneIds.isEmpty(), "no zones found for provider %s, using supplier %s", provider, zoneIdsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); for (String zoneId : zoneIds) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(provider); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToProvider(JustProvider justProvider, @Zone Supplier<Set<String>> zoneIdsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); }
@Test public void test() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("zone1", "zone2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "zone1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "zone2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.ZONE).id("zone1").description("zone1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.ZONE).id("zone2").description("zone2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } @Test(expectedExceptions = IllegalStateException.class) public void testWhenNoZones() { Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); ZoneToProvider fn = new ZoneToProvider(justProvider, zoneIdsSupplier, locationToIsoCodes); fn.get(); }
RegionToProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Builder<Location> locations = ImmutableSet.builder(); Location provider = Iterables.getOnlyElement(justProvider.get()); Set<String> regions = regionsSupplier.get(); checkState(!regions.isEmpty(), "no regions found for provider %s, using supplier %s", provider, regionsSupplier); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); for (String region : regions) { LocationBuilder builder = new LocationBuilder().scope(LocationScope.REGION).id(region).description(region) .parent(provider); if (isoCodesById.containsKey(region)) builder.iso3166Codes(isoCodesById.get(region).get()); locations.add(builder.build()); } return locations.build(); } @Inject RegionToProvider(JustProvider justProvider, @Region Supplier<Set<String>> regionsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier); @Override Set<? extends Location> get(); }
@Test public void test() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.of( "servo", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US")), "region1", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-CA")), "region2", Suppliers.<Set<String>>ofInstance(ImmutableSet.of("US-VA")) )); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); assertEquals(fn.get(), ImmutableSet.of( new LocationBuilder().scope(LocationScope.REGION).id("region1").description("region1").iso3166Codes(ImmutableSet.of("US-CA")).parent(provider).build(), new LocationBuilder().scope(LocationScope.REGION).id("region2").description("region2").iso3166Codes(ImmutableSet.of("US-VA")).parent(provider).build() )); } @Test(expectedExceptions = IllegalStateException.class) public void testWhenNoRegions() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>>ofInstance(ImmutableSet.<String>of()); Supplier<Map<String, Supplier<Set<String>>>> locationToIsoCodes = Suppliers.<Map<String, Supplier<Set<String>>>>ofInstance( ImmutableMap.<String, Supplier<Set<String>>>of()); RegionToProvider fn = new RegionToProvider(justProvider, regionIdsSupplier, locationToIsoCodes); fn.get(); }
ZoneToRegionToProviderOrJustProvider implements LocationsSupplier { @Override public Set<? extends Location> get() { Set<? extends Location> regionsOrJustProvider = regionToProviderOrJustProvider.get(); Set<String> zoneIds = zoneIdsSupplier.get(); if (zoneIds.isEmpty()) return regionsOrJustProvider; Map<String, Location> zoneIdToParent = setParentOfZoneToRegionOrProvider(zoneIds, regionsOrJustProvider); Map<String, Supplier<Set<String>>> isoCodesById = isoCodesByIdSupplier.get(); Builder<Location> locations = ImmutableSet.builder(); if (!Iterables.all(regionsOrJustProvider, LocationPredicates.isProvider())) locations.addAll(regionsOrJustProvider); for (Map.Entry<String, Location> entry : zoneIdToParent.entrySet()) { String zoneId = entry.getKey(); Location parent = entry.getValue(); LocationBuilder builder = new LocationBuilder().scope(LocationScope.ZONE).id(zoneId).description(zoneId) .parent(parent); if (isoCodesById.containsKey(zoneId)) builder.iso3166Codes(isoCodesById.get(zoneId).get()); else if (parent.getScope() == LocationScope.REGION) builder.iso3166Codes(parent.getIso3166Codes()); locations.add(builder.build()); } return locations.build(); } @Inject ZoneToRegionToProviderOrJustProvider(RegionToProviderOrJustProvider regionToProviderOrJustProvider, @Zone Supplier<Set<String>> zoneIdsSupplier, @Iso3166 Supplier<Map<String, Supplier<Set<String>>>> isoCodesByIdSupplier, @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIdsSupplier); @Override Set<? extends Location> get(); }
@Test public void testGetAll() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region1", "region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("zone1", "zone2", "zone3")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region1, region2, zone1, zone2, zone3)); } @Test public void testRegionAndZoneFilter() { Supplier<Set<String>> regionIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.of("region2")); Supplier<Set<String>> zoneIdsSupplier = Suppliers.<Set<String>> ofInstance(ImmutableSet.<String> of("zone2")); RegionToProviderOrJustProvider regionToProviderOrJustProvider = new RegionToProviderOrJustProvider(justProvider, regionIdsSupplier, locationToIsoCodes); ZoneToRegionToProviderOrJustProvider fn = new ZoneToRegionToProviderOrJustProvider(regionToProviderOrJustProvider, zoneIdsSupplier, locationToIsoCodes, regionToZones); assertEquals(fn.get(), ImmutableSet.of(region2, zone2)); }
ZoneIdToURIFromJoinOnRegionIdToURI implements ZoneIdToURISupplier { @Override public Map<String, Supplier<URI>> get() { Map<String, Supplier<Set<String>>> regionIdToZoneIds = this.regionIdToZoneIds.get(); Builder<String, Supplier<URI>> builder = ImmutableMap.builder(); for (Entry<String, Supplier<URI>> regionToURI : regionIdToURIs.get().entrySet()) { Supplier<Set<String>> zoneIds = regionIdToZoneIds.get(regionToURI.getKey()); checkState(zoneIds != null, "region %s is not in the configured region to zone mappings: %s", regionToURI.getKey(), regionIdToZoneIds); for (String zone : zoneIds.get()) { builder.put(zone, regionToURI.getValue()); } } return builder.build(); } @Inject ZoneIdToURIFromJoinOnRegionIdToURI(@Region Supplier<Map<String, Supplier<URI>>> regionIdToURIs, @Zone Supplier<Map<String, Supplier<Set<String>>>> regionIdToZoneIds); @Override Map<String, Supplier<URI>> get(); }
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "region eu-central-1 is not in the configured region to zone mappings: .*") public void zoneToRegionMappingsInconsistentOnKeys() { Map<String, Supplier<URI>> regionIdToURIs = Maps.newLinkedHashMap(); regionIdToURIs.put("us-east-1", Suppliers.ofInstance(URI.create("ec2.us-east-1.amazonaws.com"))); regionIdToURIs.put("eu-central-1", Suppliers.ofInstance(URI.create("ec2.eu-central-1.amazonaws.com"))); Map<String, Supplier<Set<String>>> regionIdToZoneIds = Maps.newLinkedHashMap(); regionIdToZoneIds.put("us-east-1", supplyZoneIds("us-east-1a", "us-east-1b")); new ZoneIdToURIFromJoinOnRegionIdToURI(Suppliers.ofInstance(regionIdToURIs), Suppliers.ofInstance(regionIdToZoneIds)).get(); }
JodaDateService implements DateService { public final String rfc822DateFormat(Date dateTime) { return rfc822DateFormatter.print(new DateTime(dateTime)); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }
@Override @Test public void testRfc822DateFormat() { String dsString = dateService.rfc822DateFormat(testData[0].date); assertEquals(dsString, testData[0].rfc822DateString); }
ZoneToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> zoneToEndpoint = zoneToEndpoints.get(); checkState(!zoneToEndpoint.isEmpty(), "no zone name to endpoint mappings configured!"); checkArgument(zoneToEndpoint.containsKey(from), "requested location %s, which is not a configured zone: %s", from, zoneToEndpoint); return zoneToEndpoint.get(from).get(); } @Inject ZoneToEndpoint(@Zone Supplier<Map<String, Supplier<URI>>> zoneToEndpoints); @Override URI apply(Object from); }
@Test public void testCorrect() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(new File("foo")); } @Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNullIsIllegal() { ZoneToEndpoint fn = new ZoneToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: fn.apply(null); }
RegionToEndpointOrProviderIfNull implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { if (from == null) return defaultUri.get(); Map<String, Supplier<URI>> regionToEndpoint = regionToEndpointSupplier.get(); if (from.equals(defaultProvider)) { if (regionToEndpoint.containsKey(from)) return regionToEndpoint.get(from).get(); return defaultUri.get(); } checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not in the configured locations: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpointOrProviderIfNull(@Provider String defaultProvider, @Provider Supplier<URI> defaultUri, @Region Supplier<Map<String, Supplier<URI>>> regionToEndpointSupplier); @Override URI apply(@Nullable Object from); }
@Test public void testWhenRegionNameIsSameAsProviderName() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("leader"), URI.create("http: } @Test public void testWhenFindsRegion() throws SecurityException, NoSuchMethodException { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeString() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply(new File("foo")); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeInRegionMapIfSpecified() { RegionToEndpointOrProviderIfNull fn = new RegionToEndpointOrProviderIfNull("leader", Suppliers.ofInstance(URI .create("http: fn.apply("2"); }
RegionToEndpoint implements Function<Object, URI> { @Override public URI apply(Object from) { Map<String, Supplier<URI>> regionToEndpoint = regionToEndpoints.get(); checkState(!regionToEndpoint.isEmpty(), "no region name to endpoint mappings configured!"); checkArgument(regionToEndpoint.containsKey(from), "requested location %s, which is not a configured region: %s", from, regionToEndpoint); return regionToEndpoint.get(from).get(); } @Inject RegionToEndpoint(@Region Supplier<Map<String, Supplier<URI>>> regionToEndpoints); @Override URI apply(Object from); }
@Test public void testCorrect() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap.of("1", Suppliers.ofInstance(URI.create("http: assertEquals(fn.apply("1"), URI.create("http: } @Test(expectedExceptions = IllegalStateException.class) public void testMustHaveEndpoints() { RegionToEndpoint fn = new RegionToEndpoint(Suppliers.<Map<String, Supplier<URI>>> ofInstance(ImmutableMap .<String, Supplier<URI>> of())); fn.apply("1"); }
JodaDateService implements DateService { public final Date rfc822DateParse(String toParse) { return rfc822DateFormatter.parseDateTime(toParse).toDate(); } final Date fromSeconds(long seconds); final String cDateFormat(Date dateTime); final String cDateFormat(); final Date cDateParse(String toParse); final String rfc822DateFormat(Date dateTime); final String rfc822DateFormat(); final Date rfc822DateParse(String toParse); final String iso8601SecondsDateFormat(Date dateTime); final String iso8601SecondsDateFormat(); final String iso8601DateFormat(Date date); final String iso8601DateFormat(); final Date iso8601DateParse(String toParse); final Date iso8601SecondsDateParse(String toParse); @Override Date iso8601DateOrSecondsDateParse(String toParse); @Override final String rfc1123DateFormat(Date dateTime); @Override final String rfc1123DateFormat(); @Override final Date rfc1123DateParse(String toParse); }
@Override @Test(enabled = false) public void testRfc822DateParse() { Date dsDate = dateService.rfc822DateParse(testData[0].rfc822DateString); assertEquals(dsDate, testData[0].date); }
ExpandProperties implements Function<Properties, Properties> { @Override public Properties apply(final Properties properties) { checkNotNull(properties, "properties cannot be null"); Map<String, String> stringProperties = Maps.toMap(properties.stringPropertyNames(), new Function<String, String>() { @Override public String apply(String input) { return properties.getProperty(input); } }); boolean pendingReplacements = true; Map<String, String> propertiesToResolve = new HashMap<String, String>(stringProperties); while (pendingReplacements) { Map<String, String> leafs = leafs(propertiesToResolve); if (leafs.isEmpty()) { break; } pendingReplacements = resolveProperties(propertiesToResolve, leafs); } Properties resolved = new Properties(); resolved.putAll(properties); for (Map.Entry<String, String> entry : propertiesToResolve.entrySet()) { resolved.setProperty(entry.getKey(), entry.getValue()); } return resolved; } @Override Properties apply(final Properties properties); }
@Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = "properties cannot be null") public void testPropertiesMandatory() { new ExpandProperties().apply(null); } @Test public void testNoLeafs() { Properties props = new Properties(); props.put("one", "${two}"); props.put("two", "${one}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("one"), "${two}"); assertEquals(resolved.get("two"), "${one}"); }
ExpandProperties implements Function<Properties, Properties> { @SuppressModernizer private boolean resolveProperties(Map<String, String> properties, Map<String, String> variables) { boolean anyReplacementDone = false; for (Map.Entry<String, String> entry : properties.entrySet()) { String key = entry.getKey(); StringBuffer sb = new StringBuffer(); Matcher m = VAR.matcher(entry.getValue()); while (m.find()) { String match = m.group(); String var = match.substring(2, match.length() - 1); Optional<String> value = var.equals(key) ? Optional.<String> absent() : Optional.fromNullable(variables .get(var)); m.appendReplacement(sb, value.or("\\" + match)); if (value.isPresent()) { anyReplacementDone = true; } } m.appendTail(sb); properties.put(key, sb.toString()); } return anyReplacementDone; } @Override Properties apply(final Properties properties); }
@Test public void testResolveProperties() { Properties props = new Properties(); props.put("number", 1); props.put("two", "2"); props.put("greeting", "hello"); props.put("simple", "simple: ${greeting}"); props.put("nested", "nested: ${simple}"); props.put("mixed", "mixed: ${nested} and ${simple}"); props.put("unexisting", "${foobar} substitution"); props.put("recursive", "variable5 ${recursive} recursive ${unexisting}"); props.put("characters{{$$", "characters"); props.put("ugly", "substitute: ${characters{{$$}"); Properties resolved = new ExpandProperties().apply(props); assertEquals(resolved.size(), props.size()); assertEquals(resolved.get("number"), 1); assertEquals(resolved.get("two"), "2"); assertEquals(resolved.get("greeting"), "hello"); assertEquals(resolved.get("simple"), "simple: hello"); assertEquals(resolved.get("nested"), "nested: simple: hello"); assertEquals(resolved.get("mixed"), "mixed: nested: simple: hello and simple: hello"); assertEquals(resolved.get("unexisting"), "${foobar} substitution"); assertEquals(resolved.get("recursive"), "variable5 ${recursive} recursive ${unexisting}"); assertEquals(resolved.get("ugly"), "substitute: characters"); }
JoinOnComma implements Function<Object, String> { public String apply(Object o) { checkNotNull(o, "input cannot be null"); if (o.getClass().isArray()) { Builder<Object> builder = ImmutableList.builder(); for (int i = 0; i < Array.getLength(o); i++) builder.add(Array.get(o, i)); o = builder.build(); } checkArgument(o instanceof Iterable<?>, "you must pass an iterable or array"); Iterable<?> toJoin = (Iterable<?>) o; checkArgument(!Iterables.isEmpty(toJoin), "you must pass an iterable or array with elements"); return Joiner.on(',').join(toJoin); } String apply(Object o); }
@Test public void testIterableLong() { String list = new JoinOnComma().apply(ImmutableList.of(1L, 2L)); assertEquals(list, "1,2"); } @Test public void testLongArray() { String list = new JoinOnComma().apply(new long[] { 1L, 2L }); assertEquals(list, "1,2"); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyArrayIllegalArgumentException() { new JoinOnComma().apply(new long[] {}); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIterableIllegalArgumentException() { new JoinOnComma().apply(ImmutableList.of()); } @Test(expectedExceptions = NullPointerException.class) public void testNullPointer() { new JoinOnComma().apply(null); }
SshjSshClient implements SshClient { @VisibleForTesting SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); logger.error(e, "<< " + message); if (e instanceof UserAuthException) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } SshjSshClient(BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override ExecChannel execChannel(String command); @Override String getHostAddress(); @Override String getUsername(); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new UserAuthException(""), ""); }
ContextBuilder { @VisibleForTesting static void addExecutorServiceIfNotPresent(List<Module> modules) { if (!any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(ConfiguresExecutorService.class); } } )) { if (any(modules, new Predicate<Module>() { public boolean apply(Module input) { return input.getClass().isAnnotationPresent(SingleThreaded.class); } })) { modules.add(new ExecutorServiceModule(newDirectExecutorService())); } else { modules.add(new ExecutorServiceModule()); } } } protected ContextBuilder(ProviderMetadata providerMetadata); protected ContextBuilder(@Nullable ProviderMetadata providerMetadata, ApiMetadata apiMetadata); ContextBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(String providerOrApi); static ContextBuilder newBuilder(ApiMetadata apiMetadata); static ContextBuilder newBuilder(ProviderMetadata providerMetadata); @Override String toString(); ContextBuilder name(String name); ContextBuilder credentialsSupplier(Supplier<Credentials> credentialsSupplier); ContextBuilder credentials(String identity, @Nullable String credential); ContextBuilder endpoint(String endpoint); ContextBuilder apiVersion(String apiVersion); ContextBuilder buildVersion(String buildVersion); ContextBuilder modules(Iterable<? extends Module> modules); ContextBuilder overrides(Properties overrides); static String searchPropertiesForProviderScopedProperty(Properties mutable, String prov, String key); Injector buildInjector(); static Injector buildInjector(String name, ProviderMetadata providerMetadata, Supplier<Credentials> creds, List<Module> inputModules); @SuppressWarnings("unchecked") C build(); V build(Class<V> viewType); V buildView(Class<V> viewType); @SuppressWarnings("unchecked") V buildView(TypeToken<V> viewType); @SuppressWarnings("unchecked") C build(TypeToken<C> contextType); A buildApi(Class<A> api); @SuppressWarnings("unchecked") A buildApi(TypeToken<A> apiType); ApiMetadata getApiMetadata(); }
@Test public void testAddExecutorServiceModuleIfNotPresent() { List<Module> modules = Lists.newArrayList(); ExecutorServiceModule module = new ExecutorServiceModule(); modules.add(module); ContextBuilder.addExecutorServiceIfNotPresent(modules); assertEquals(modules.size(), 1); assertEquals(modules.remove(0), module); }
Apis { public static ApiMetadata withId(String id) throws NoSuchElementException { return find(all(), ApiPredicates.id(id)); } static Function<ApiMetadata, String> idFunction(); static Iterable<ApiMetadata> all(); static ApiMetadata withId(String id); static Iterable<ApiMetadata> contextAssignableFrom(TypeToken<?> type); static Iterable<ApiMetadata> viewableAs(TypeToken<? extends View> type); static Iterable<ApiMetadata> viewableAs(Class<? extends View> type); static TypeToken<?> findView(final ApiMetadata apiMetadata, final TypeToken<?> view); }
@Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); } @Test public void testWithId() { ApiMetadata apiMetadata; try { apiMetadata = Apis.withId("fake-id"); fail("Looking for a api with an id that doesn't exist should " + "throw an exception."); } catch (NoSuchElementException nsee) { ; } apiMetadata = Apis.withId(testBlobstoreApi.getId()); assertEquals(testBlobstoreApi, apiMetadata); }
MetadataBundleListener implements BundleListener { public Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle( "/META-INF/services/org.jclouds.providers.ProviderMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ProviderMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); }
@SuppressWarnings("rawtypes") @Test public void testGetProviderMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(3, providerMetadataList.size()); assertTrue(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @SuppressWarnings("rawtypes") @Test public void testGetProviderMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreProviderMetadata.class.getName())).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(2, providerMetadataList.size()); assertFalse(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @Test public void testGetProviderMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(3, providerMetadataList.size()); assertTrue(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @Test public void testGetProviderMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.providers.ProviderMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.providers.ProviderMetadata")).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreProviderMetadata.class.getName())).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class).anyTimes(); replay(bundle); List<ProviderMetadata> providerMetadataList = Lists.newArrayList(listener.listProviderMetadata(bundle)); assertNotNull(providerMetadataList); assertEquals(2, providerMetadataList.size()); assertFalse(providerMetadataList.contains(new JcloudsTestBlobStoreProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestComputeProviderMetadata())); assertTrue(providerMetadataList.contains(new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); }
MetadataBundleListener implements BundleListener { public Iterable<ApiMetadata> listApiMetadata(Bundle bundle) { Iterable<String> classNames = stringsForResourceInBundle("/META-INF/services/org.jclouds.apis.ApiMetadata", bundle); return instantiateAvailableClasses(bundle, classNames, ApiMetadata.class); } synchronized void start(BundleContext bundleContext); void stop(BundleContext bundleContext); @Override synchronized void bundleChanged(BundleEvent event); Iterable<ProviderMetadata> listProviderMetadata(Bundle bundle); Iterable<ApiMetadata> listApiMetadata(Bundle bundle); synchronized void addProviderListener(ProviderListener listener); synchronized void removeProviderListener(ProviderListener listener); synchronized void addApiListenerListener(ApiListener listener); synchronized void removeApiListenerListener(ApiListener listener); }
@SuppressWarnings("rawtypes") @Test public void testGetApiMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( JcloudsTestBlobStoreApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(3, apiMetadataList.size()); assertTrue(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); } @SuppressWarnings("rawtypes") @Test public void testGetApiMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreApiMetadata.class.getName())).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(2, apiMetadataList.size()); assertFalse(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); } @Test public void testGetApiMetadata() throws Exception { MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( JcloudsTestBlobStoreApiMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(3, apiMetadataList.size()); assertTrue(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); } @Test public void testGetApiMetadataFromMultipleClassLoaders() throws Exception { ClassLoader isolatedClassLoader = createIsolatedClassLoader(); MetadataBundleListener listener = new MetadataBundleListener(); Bundle bundle = createMock(Bundle.class); expect(bundle.getEntry("/META-INF/services/org.jclouds.apis.ApiMetadata")).andReturn( getClass().getResource("/META-INF/services/org.jclouds.apis.ApiMetadata")).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestBlobStoreApiMetadata")).andReturn( isolatedClassLoader.loadClass(JcloudsTestBlobStoreApiMetadata.class.getName())).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class).anyTimes(); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestYetAnotherComputeApiMetadata")).andReturn( JcloudsTestYetAnotherComputeApiMetadata.class).anyTimes(); replay(bundle); List<ApiMetadata> apiMetadataList = Lists.newArrayList(listener.listApiMetadata(bundle)); assertNotNull(apiMetadataList); assertEquals(2, apiMetadataList.size()); assertFalse(apiMetadataList.contains(new JcloudsTestBlobStoreApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestComputeApiMetadata())); assertTrue(apiMetadataList.contains(new JcloudsTestYetAnotherComputeApiMetadata())); verify(bundle); }
Bundles { public static <T> ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type) { checkNotNull(bundle, "bundle"); checkNotNull(classNames, "classNames"); checkNotNull(type, "type"); return FluentIterable.from(classNames) .transform(loadClassIfAssignableFrom(bundle, type)) .filter(notNull()) .transform(instantiateIfPossible(type)) .filter(notNull()) .toSet(); } private Bundles(); static ImmutableSet<T> instantiateAvailableClasses(Bundle bundle, Iterable<String> classNames, Class<T> type); static ImmutableSet<String> stringsForResourceInBundle(String resourcePath, Bundle bundle); }
@SuppressWarnings("rawtypes") @Test public void testInstantiateAvailableClassesWhenAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.providers.JcloudsTestComputeProviderMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestComputeProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @SuppressWarnings("rawtypes") @Test public void testInstantiateAvailableClassesWhenNotAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect((Class) bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.apis.JcloudsTestComputeApiMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @Test public void testInstantiateAvailableClassesWhenAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestComputeProviderMetadata")).andReturn( JcloudsTestComputeProviderMetadata.class); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.providers.JcloudsTestComputeProviderMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestComputeProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); } @Test public void testInstantiateAvailableClassesWhenNotAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.class); expect(bundle.loadClass("org.jclouds.apis.JcloudsTestComputeApiMetadata")).andReturn( JcloudsTestComputeApiMetadata.class); expect(bundle.loadClass("org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata")).andReturn( JcloudsTestYetAnotherComputeProviderMetadata.class); replay(bundle); Iterable<ProviderMetadata> providers = Bundles.instantiateAvailableClasses(bundle, ImmutableSet.of( "org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata", "org.jclouds.apis.JcloudsTestComputeApiMetadata", "org.jclouds.providers.JcloudsTestYetAnotherComputeProviderMetadata"), ProviderMetadata.class); assertEquals(providers, ImmutableSet.of(new JcloudsTestBlobStoreProviderMetadata(), new JcloudsTestYetAnotherComputeProviderMetadata())); verify(bundle); }
IpPermissions extends IpPermission { public static ToSourceSelection permitAnyProtocol() { return new ToSourceSelection(IpProtocol.ALL, 1, 65535); } protected IpPermissions(IpProtocol ipProtocol, int fromPort, int toPort, Multimap<String, String> tenantIdGroupPairs, Iterable<String> groupIds, Iterable<String> cidrBlocks, Iterable<String> exclusionCidrBlocks); static ICMPTypeSelection permitICMP(); static ToSourceSelection permitAnyProtocol(); static PortSelection permit(IpProtocol protocol); }
@Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlock("a.0.0.0/0").build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidr() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlock("a.0.0.0/0").build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .cidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testAllProtocolInvalidExclusionCidrMultiple() { IpPermissions authorization = IpPermissions.permitAnyProtocol(); assertEquals(authorization, IpPermission.builder().ipProtocol(IpProtocol.ALL).fromPort(1).toPort(65535) .exclusionCidrBlocks(ImmutableSet.of("a.0.0.0/0", "0.0.0.0/0")).build()); }
IpPermission implements Comparable<IpPermission> { public static Builder builder() { return new Builder(); } IpPermission(IpProtocol ipProtocol, int fromPort, int toPort, Multimap<String, String> tenantIdGroupNamePairs, Iterable<String> groupIds, Iterable<String> cidrBlocks, Iterable<String> exclusionCidrBlocks); static Builder builder(); IpProtocol getIpProtocol(); int getFromPort(); int getToPort(); Multimap<String, String> getTenantIdGroupNamePairs(); Set<String> getGroupIds(); Set<String> getCidrBlocks(); @Beta Set<String> getExclusionCidrBlocks(); @Override int compareTo(IpPermission that); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }
@Test public void testCompareProtocol() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission tcp2 = builder().ipProtocol(IpProtocol.TCP).build(); assertEqualAndComparable(tcp, tcp2); final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build(); assertOrder(tcp, udp); final IpPermission t10 = builder().fromPermission(tcp).fromPort(10).build(); final IpPermission t20 = builder().fromPermission(tcp).fromPort(20).build(); final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build(); final IpPermission t0to10 = builder().fromPermission(tcp).toPort(10).build(); final IpPermission t0to20 = builder().fromPermission(tcp).toPort(20).build(); assertTotalOrder(ImmutableList.of(tcp, t0to10, t0to20, t10, t20, udp, u10)); } @Test public void testCompareTenantIdGroupNamePairs() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission g1 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1").build(); final IpPermission g2 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group2").build(); final IpPermission g12 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1") .tenantIdGroupNamePair("tenant1", "group2").build(); final IpPermission g21 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group2") .tenantIdGroupNamePair("tenant1", "group1").build(); final IpPermission t2g1 = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant2", "group1").build(); assertTotalOrder(ImmutableList.of(tcp, g1, g12, g2, g21, t2g1)); final IpPermission g12b = builder().fromPermission(tcp) .tenantIdGroupNamePair("tenant1", "group1") .tenantIdGroupNamePair("tenant1", "group2").build(); assertEqualAndComparable(g12, g12b); } @Test public void testCompareGroupIds() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission aa = builder().fromPermission(tcp) .groupId("a").build(); final IpPermission a = builder().fromPermission(tcp) .groupId("a").build(); final IpPermission ab = builder().fromPermission(tcp) .groupId("a") .groupId("b").build(); final IpPermission ba = builder().fromPermission(tcp) .groupId("b") .groupId("a").build(); assertTotalOrder(ImmutableList.of(tcp, a, ab, ba)); assertEqualAndComparable(a, aa); } @Test public void testCompareCidrBlocks() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission everything = builder().fromPermission(tcp) .cidrBlock("0.0.0.0/0").build(); final IpPermission universal = builder().fromPermission(tcp) .cidrBlock("0.0.0.0/0").build(); assertEqualAndComparable(everything, universal); final IpPermission localhost = builder().fromPermission(tcp) .cidrBlock("127.0.0.1/32").build(); final IpPermission tenTwentyOne = builder().fromPermission(tcp) .cidrBlock("10.0.0.21/32").build(); final IpPermission tenTwoHundred = builder().fromPermission(tcp) .cidrBlock("10.0.0.200/32").build(); assertOrder(tenTwoHundred, tenTwentyOne); assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost)); } @Test public void testCompareExclusionCidrBlocks() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission everything = builder().fromPermission(tcp) .exclusionCidrBlock("0.0.0.0/0").build(); final IpPermission universal = builder().fromPermission(tcp) .exclusionCidrBlock("0.0.0.0/0").build(); assertEqualAndComparable(everything, universal); final IpPermission localhost = builder().fromPermission(tcp) .exclusionCidrBlock("127.0.0.1/32").build(); final IpPermission stillLocal = builder().fromPermission(tcp) .exclusionCidrBlock("127.0.0.1/32").build(); assertEqualAndComparable(localhost, stillLocal); final IpPermission tenTwentyOne = builder().fromPermission(tcp) .exclusionCidrBlock("10.0.0.21/32").build(); final IpPermission tenTwoHundred = builder().fromPermission(tcp) .exclusionCidrBlock("10.0.0.200/32").build(); assertOrder(tenTwoHundred, tenTwentyOne); assertTotalOrder(ImmutableList.of(tcp, everything, tenTwoHundred, tenTwentyOne, localhost)); } @Test public void testPairwise() { final IpPermission tcp = builder().ipProtocol(IpProtocol.TCP).build(); final IpPermission udp = builder().ipProtocol(IpProtocol.UDP).build(); final IpPermission f10 = builder().fromPermission(tcp).fromPort(10).build(); final IpPermission f20 = builder().fromPermission(tcp).fromPort(20).build(); final IpPermission u10 = builder().fromPermission(udp).fromPort(10).build(); final IpPermission t20 = builder().fromPermission(f10).toPort(20).build(); final IpPermission t30 = builder().fromPermission(f10).toPort(30).build(); final IpPermission t2g1 = builder().fromPermission(t20) .tenantIdGroupNamePair("tenant1", "group1") .build(); final IpPermission t2g2 = builder().fromPermission(t20) .tenantIdGroupNamePair("tenant1", "group2") .build(); final IpPermission gidA = builder().fromPermission(t2g1) .groupId("groupA") .build(); final IpPermission gidB = builder().fromPermission(t2g1) .groupId("groupB") .build(); final IpPermission cidr10 = builder().fromPermission(gidA) .cidrBlock("10.10.10.10/32") .build(); final IpPermission cidr20 = builder().fromPermission(gidA) .cidrBlock("10.10.10.20/32") .build(); final IpPermission ex10 = builder().fromPermission(cidr10) .exclusionCidrBlock("172.16.10.10/32") .build(); final IpPermission ex20 = builder().fromPermission(cidr10) .exclusionCidrBlock("172.16.10.20/32") .build(); assertTotalOrder(ImmutableList.of( tcp, f10, t20, t2g1, gidA, cidr10, ex10, ex20, cidr20, gidB, t2g2, t30, f20, udp, u10 )); }
ConvertToJcloudsResponse implements Function<HTTPResponse, HttpResponse> { @Override public HttpResponse apply(HTTPResponse gaeResponse) { Payload payload = gaeResponse.getContent() != null ? Payloads.newByteArrayPayload(gaeResponse.getContent()) : null; Multimap<String, String> headers = LinkedHashMultimap.create(); String message = null; for (HTTPHeader header : gaeResponse.getHeaders()) { if (header.getName() == null) message = header.getValue(); else headers.put(header.getName(), header.getValue()); } if (payload != null) { contentMetadataCodec.fromHeaders(payload.getContentMetadata(), headers); } return HttpResponse.builder() .statusCode(gaeResponse.getResponseCode()) .message(message) .payload(payload) .headers(filterOutContentHeaders(headers)).build(); } @Inject ConvertToJcloudsResponse(ContentMetadataCodec contentMetadataCodec); @Override HttpResponse apply(HTTPResponse gaeResponse); }
@Test void testConvertWithContent() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn("hello".getBytes()).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(Strings2.toStringAndClose(response.getPayload().openStream()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); } @Test void testConvertWithHeaders() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn(null).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(response.getPayload(), null); assertEquals(response.getHeaders().size(), 0); } @Test void testConvertWithContent() throws IOException { HTTPResponse gaeResponse = createMock(HTTPResponse.class); expect(gaeResponse.getResponseCode()).andReturn(200); List<HTTPHeader> headers = Lists.newArrayList(); headers.add(new HTTPHeader(HttpHeaders.CONTENT_TYPE, "text/xml")); expect(gaeResponse.getHeaders()).andReturn(headers); expect(gaeResponse.getContent()).andReturn("hello".getBytes()).atLeastOnce(); replay(gaeResponse); HttpResponse response = req.apply(gaeResponse); assertEquals(response.getStatusCode(), 200); assertEquals(Strings2.toString(response.getPayload()), "hello"); assertEquals(response.getHeaders().size(), 0); assertEquals(response.getPayload().getContentMetadata().getContentType(), "text/xml"); }
InitScriptConfigurationForTasks { @Inject(optional = true) public InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern) { this.initScriptPattern = checkNotNull(initScriptPattern, "initScriptPattern ex. /tmp/init-%s"); checkArgument(this.initScriptPattern.startsWith("/"), "initScriptPattern must be a UNIX-style path starting at the root (/)"); int lastSlash = initScriptPattern.lastIndexOf('/'); if (lastSlash == 0) { this.basedir = "/"; } else { this.basedir = initScriptPattern.substring(0, lastSlash); } return this; } protected InitScriptConfigurationForTasks(); static InitScriptConfigurationForTasks create(); @Inject(optional = true) InitScriptConfigurationForTasks initScriptPattern( @Named(PROPERTY_INIT_SCRIPT_PATTERN) String initScriptPattern); InitScriptConfigurationForTasks appendCurrentTimeMillisToAnonymousTaskNames(); InitScriptConfigurationForTasks appendIncrementingNumberToAnonymousTaskNames(); String getBasedir(); String getInitScriptPattern(); Supplier<String> getAnonymousTaskSuffixSupplier(); static final String PROPERTY_INIT_SCRIPT_PATTERN; }
@Test public void testInitScriptPattern() throws Exception { InitScriptConfigurationForTasks config = InitScriptConfigurationForTasks.create(); config.initScriptPattern("/var/tmp/jclouds-%s"); assertEquals(config.getBasedir(), "/var/tmp"); assertEquals(config.getInitScriptPattern(), "/var/tmp/jclouds-%s"); }
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void registerImage(Image image) { checkNotNull(image, "image"); imageCache.put(image.getId(), image); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }
@Test(expectedExceptions = NullPointerException.class) public void testRegisterNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.registerImage(null); }
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { public void removeImage(String imageId) { imageCache.invalidate(checkNotNull(imageId, "imageId")); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }
@Test(expectedExceptions = NullPointerException.class) public void testRemoveNullImageIsNotAllowed() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); imageCache.removeImage(null); } @Test public void testRemoveImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); imageCache.removeImage(image.getId()); assertEquals(imageCache.get().size(), 0); }
ConvertToGaeRequest implements Function<HttpRequest, HTTPRequest> { @Override public HTTPRequest apply(HttpRequest request) { URL url = null; try { url = request.getEndpoint().toURL(); } catch (MalformedURLException e) { Throwables.propagate(e); } FetchOptions options = disallowTruncate(); options.doNotFollowRedirects(); if (utils.relaxHostname() || utils.trustAllCerts()) options.doNotFollowRedirects(); options.setDeadline(10.0); HTTPRequest gaeRequest = new HTTPRequest(url, HTTPMethod.valueOf(request.getMethod().toString()), options); for (Entry<String, String> entry : request.getHeaders().entries()) { String header = entry.getKey(); if (!prohibitedHeaders.contains(header)) gaeRequest.addHeader(new HTTPHeader(header, entry.getValue())); } gaeRequest.addHeader(new HTTPHeader(HttpHeaders.USER_AGENT, USER_AGENT)); if (request.getPayload() != null) { InputStream input = request.getPayload().getInput(); try { byte[] array = ByteStreams.toByteArray(input); if (!request.getPayload().isRepeatable()) { Payload oldPayload = request.getPayload(); request.setPayload(array); HttpUtils.copy(oldPayload.getContentMetadata(), request.getPayload().getContentMetadata()); } gaeRequest.setPayload(array); if (array.length > 0) { gaeRequest.setHeader(new HTTPHeader("Expect", "100-continue")); } } catch (IOException e) { Throwables.propagate(e); } finally { Closeables2.closeQuietly(input); } for (Entry<String, String> header : contentMetadataCodec.toHeaders( request.getPayload().getContentMetadata()).entries()) { if (!prohibitedHeaders.contains(header.getKey())) gaeRequest.setHeader(new HTTPHeader(header.getKey(), header.getValue())); } } return gaeRequest; } @Inject ConvertToGaeRequest(HttpUtils utils, ContentMetadataCodec contentMetadataCodec); @Override HTTPRequest apply(HttpRequest request); static final String USER_AGENT; final Set<String> prohibitedHeaders; }
@Test void testConvertRequestGetsTargetAndUri() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getURL().getPath(), "/foo"); } @Test void testConvertRequestSetsFetchOptions() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assert gaeRequest.getFetchOptions() != null; } @Test void testConvertRequestSetsHeaders() throws IOException { HttpRequest request = HttpRequest.builder() .method(HttpMethod.GET) .endpoint(endPoint) .addHeader("foo", "bar").build(); HTTPRequest gaeRequest = req.apply(request); assertEquals(gaeRequest.getHeaders().get(0).getName(), "foo"); assertEquals(gaeRequest.getHeaders().get(0).getValue(), "bar"); } @Test void testConvertRequestNoContent() throws IOException { HttpRequest request = HttpRequest.builder().method(HttpMethod.GET).endpoint(endPoint).build(); HTTPRequest gaeRequest = req.apply(request); assert gaeRequest.getPayload() == null; assertEquals(gaeRequest.getHeaders().size(), 1); assertEquals(gaeRequest.getHeaders().get(0).getName(), HttpHeaders.USER_AGENT); assertEquals(gaeRequest.getHeaders().get(0).getValue(), "jclouds/1.0 urlfetch/1.4.3"); } @Test(expectedExceptions = UnsupportedOperationException.class) void testConvertRequestBadContent() throws IOException { HttpRequest request = HttpRequest.builder() .method(HttpMethod.GET) .endpoint(endPoint) .payload(Payloads.newPayload(new Date())).build(); req.apply(request); }
ImageCacheSupplier implements Supplier<Set<? extends Image>>, ValueLoadedCallback<Set<? extends Image>> { @Override public Set<? extends Image> get() { memoizedImageSupplier.get(); return ImmutableSet.copyOf(imageCache.asMap().values()); } ImageCacheSupplier(Supplier<Set<? extends Image>> imageSupplier, long sessionIntervalSeconds, AtomicReference<AuthorizationException> authException, final Provider<GetImageStrategy> imageLoader); @Override Set<? extends Image> get(); @Override void valueLoaded(Optional<Set<? extends Image>> value); void reset(Set<? extends Image> images); Set<? extends Image> rebuildCache(); Optional<? extends Image> get(String id); void registerImage(Image image); void removeImage(String imageId); }
@Test public void testLoadImage() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 60, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); } @Test public void testSupplierExpirationReloadsTheCache() { ImageCacheSupplier imageCache = new ImageCacheSupplier(Suppliers.<Set<? extends Image>> ofInstance(images), 3, Atomics.<AuthorizationException> newReference(), Providers.of(getImageStrategy)); assertEquals(imageCache.get().size(), 1); Optional<? extends Image> image = imageCache.get("foo"); assertTrue(image.isPresent()); assertEquals(image.get().getName(), "imageName-foo"); assertEquals(imageCache.get().size(), 2); Uninterruptibles.sleepUninterruptibly(4, TimeUnit.SECONDS); assertEquals(imageCache.get().size(), 1); assertFalse(any(imageCache.get(), idEquals("foo"))); }
ConcurrentOpenSocketFinder implements OpenSocketFinder { @Override public HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits) { ImmutableSet<HostAndPort> sockets = checkNodeHasIps(node, allowedInterfaces).transform(new Function<String, HostAndPort>() { @Override public HostAndPort apply(String from) { return HostAndPort.fromParts(from, port); } }).toSet(); long period = timeUnits.convert(1, TimeUnit.SECONDS); AtomicReference<HostAndPort> result = newReference(); Predicate<Iterable<HostAndPort>> findOrBreak = or(updateRefOnSocketOpen(result), throwISEIfNoLongerRunning(node)); logger.debug(">> blocking on sockets %s for %d %s", sockets, timeout, timeUnits); boolean passed = retryPredicate(findOrBreak, timeout, period, timeUnits).apply(sockets); if (passed) { logger.debug("<< socket %s opened", result); assert result.get() != null; return result.get(); } else { logger.warn("<< sockets %s didn't open after %d %s", sockets, timeout, timeUnits); throw new NoSuchElementException(format("could not connect to any ip address port %d on node %s", port, node)); } } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester, @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning, @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); }
@Test public void testRespectsTimeout() throws Exception { final long timeoutMs = 1000; OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeRunning, userExecutor); Stopwatch stopwatch = Stopwatch.createUnstarted(); stopwatch.start(); try { finder.findOpenSocketOnNode(node, 22, timeoutMs, MILLISECONDS); fail(); } catch (NoSuchElementException success) { } long timetaken = stopwatch.elapsed(MILLISECONDS); assertTrue(timetaken >= timeoutMs - EARLY_GRACE && timetaken <= timeoutMs + SLOW_GRACE, "timetaken=" + timetaken); } @Test public void testReturnsReachable() throws Exception { SocketOpen secondSocketOpen = new SocketOpen() { @Override public boolean apply(HostAndPort input) { return HostAndPort.fromParts(PRIVATE_IP, 22).equals(input); } }; OpenSocketFinder finder = new ConcurrentOpenSocketFinder(secondSocketOpen, nodeRunning, userExecutor); HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22)); } @Test public void testChecksSocketsConcurrently() throws Exception { ControllableSocketOpen socketTester = new ControllableSocketOpen(ImmutableMap.of( HostAndPort.fromParts(PUBLIC_IP, 22), new SlowCallable<Boolean>(true, 1500), HostAndPort.fromParts(PRIVATE_IP, 22), new SlowCallable<Boolean>(true, 1000))); OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketTester, nodeRunning, userExecutor); HostAndPort result = finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); assertEquals(result, HostAndPort.fromParts(PRIVATE_IP, 22)); } @Test public void testAbortsWhenNodeNotRunning() throws Exception { OpenSocketFinder finder = new ConcurrentOpenSocketFinder(socketAlwaysClosed, nodeNotRunning, userExecutor) { @Override protected <T> Predicate<T> retryPredicate(final Predicate<T> findOrBreak, long timeout, long period, TimeUnit timeUnits) { return new Predicate<T>() { @Override public boolean apply(T input) { try { findOrBreak.apply(input); fail("should have thrown IllegalStateException"); } catch (IllegalStateException e) { } return false; } }; } }; try { finder.findOpenSocketOnNode(node, 22, 2000, MILLISECONDS); fail(); } catch (NoSuchElementException e) { } }
ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddresses()); } if (allowedInterfaces.scanPrivate) { ipsBuilder.addAll(node.getPrivateAddresses()); } ImmutableSet<String> ips = ipsBuilder.build(); checkState(!ips.isEmpty(), "node does not have IP addresses configured: %s", node); return FluentIterable.from(ips); } @Inject @VisibleForTesting ConcurrentOpenSocketFinder(SocketOpen socketTester, @Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning, @Named(PROPERTY_USER_THREADS) ListeningExecutorService userExecutor); @Override HostAndPort findOpenSocketOnNode(NodeMetadata node, final int port, long timeout, TimeUnit timeUnits); }
@Test public void testSocketFinderAllowedInterfacesAll() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.ALL); assertTrue(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } @Test public void testSocketFinderAllowedInterfacesPrivate() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PRIVATE); assertFalse(ips.contains(PUBLIC_IP)); assertTrue(ips.contains(PRIVATE_IP)); } @Test public void testSocketFinderAllowedInterfacesPublic() throws Exception { FluentIterable<String> ips = ConcurrentOpenSocketFinder.checkNodeHasIps(node, AllowedInterfaces.PUBLIC); assertTrue(ips.contains(PUBLIC_IP)); assertFalse(ips.contains(PRIVATE_IP)); }
ComputeServiceUtils { public static String formatStatus(ComputeMetadataIncludingStatus<?> resource) { if (resource.getBackendStatus() == null) return resource.getStatus().toString(); return String.format("%s[%s]", resource.getStatus(), resource.getBackendStatus()); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@SuppressWarnings("unchecked") @Test public void testFormatStatusWithBackendStatus() { ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class); expect(resource.getStatus()).andReturn(Image.Status.PENDING); expect(resource.getBackendStatus()).andReturn("queued").anyTimes(); replay(resource); assertEquals(formatStatus(resource), "PENDING[queued]"); verify(resource); } @SuppressWarnings("unchecked") @Test public void testFormatStatusWithoutBackendStatus() { ComputeMetadataIncludingStatus<Image.Status> resource = createMock(ComputeMetadataIncludingStatus.class); expect(resource.getStatus()).andReturn(Image.Status.PENDING); expect(resource.getBackendStatus()).andReturn(null).anyTimes(); replay(resource); assertEquals(formatStatus(resource), "PENDING"); verify(resource); }
ComputeServiceUtils { public static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options) { Builder<String, String> builder = ImmutableMap.<String, String> builder(); builder.putAll(options.getUserMetadata()); for (String tag : options.getTags()) builder.put(tag, ""); return builder.build(); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testMetadataAndTagsAsValuesOfEmptyString() { TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of("tag")).userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of("foo", "bar", "tag", "")); } @Test public void testMetadataAndTagsAsValuesOfEmptyStringNoTags() { TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsValuesOfEmptyString(options), ImmutableMap.<String, String>of("foo", "bar")); }
ComputeServiceUtils { public static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options) { Builder<String, String> builder = ImmutableMap.<String, String> builder(); builder.putAll(options.getUserMetadata()); if (!options.getTags().isEmpty()) builder.put("jclouds_tags", Joiner.on(',').join(options.getTags())); return builder.build(); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testMetadataAndTagsAsCommaDelimitedValue() { TemplateOptions options = TemplateOptions.Builder.tags(ImmutableSet.of("tag")).userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of("foo", "bar", "jclouds_tags", "tag")); } @Test public void testMetadataAndTagsAsCommaDelimitedValueNoTags() { TemplateOptions options = TemplateOptions.Builder.userMetadata(ImmutableMap.<String, String>of("foo", "bar")); assertEquals(metadataAndTagsAsCommaDelimitedValue(options), ImmutableMap.<String, String>of("foo", "bar")); }
ComputeServiceUtils { public static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap) { if (osVersionMap.containsKey(family)) { if (osVersionMap.get(family).containsKey(in)) return osVersionMap.get(family).get(in); if (osVersionMap.get(family).containsValue(in)) return in; ContainsSubstring contains = new ContainsSubstring(in.replace('-', '.')); try { String key = Iterables.find(osVersionMap.get(family).keySet(), contains); return osVersionMap.get(family).get(key); } catch (NoSuchElementException e) { try { return Iterables.find(osVersionMap.get(family).values(), contains); } catch (NoSuchElementException e1) { } } } return ""; } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testParseVersionOrReturnEmptyStringUbuntu1004() { assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "Ubuntu 10.04", map), "10.04"); } @Test public void testParseVersionOrReturnEmptyStringUbuntu1104() { assertEquals(parseVersionOrReturnEmptyString(OsFamily.UBUNTU, "ubuntu 11.04 server (i386)", map), "11.04"); }
ComputeServiceUtils { public static Statement execHttpResponse(HttpRequest request) { return pipeHttpResponseToBash(request.getMethod(), request.getEndpoint(), request.getHeaders()); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testExecHttpResponse() { HttpRequest request = HttpRequest.builder() .method("GET") .endpoint("https: .addHeader("Host", "adriancolehappy.s3.amazonaws.com") .addHeader("Date", "Sun, 12 Sep 2010 08:25:19 GMT") .addHeader("Authorization", "AWS 0ASHDJAS82:JASHFDA=").build(); assertEquals( ComputeServiceUtils.execHttpResponse(request).render(org.jclouds.scriptbuilder.domain.OsFamily.UNIX), "curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https: }
ComputeServiceUtils { public static Statement extractTargzIntoDirectory(HttpRequest targz, String directory) { return Statements .extractTargzIntoDirectory(targz.getMethod(), targz.getEndpoint(), targz.getHeaders(), directory); } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testTarxzpHttpResponse() { HttpRequest request = HttpRequest.builder() .method("GET") .endpoint("https: .addHeader("Host", "adriancolehappy.s3.amazonaws.com") .addHeader("Date", "Sun, 12 Sep 2010 08:25:19 GMT") .addHeader("Authorization", "AWS 0ASHDJAS82:JASHFDA=").build(); assertEquals( ComputeServiceUtils.extractTargzIntoDirectory(request, "/stage/").render( org.jclouds.scriptbuilder.domain.OsFamily.UNIX), "curl -q -s -S -L --connect-timeout 10 --max-time 600 --retry 20 -X GET -H \"Host: adriancolehappy.s3.amazonaws.com\" -H \"Date: Sun, 12 Sep 2010 08:25:19 GMT\" -H \"Authorization: AWS 0ASHDJAS82:JASHFDA=\" https: }
ComputeServiceUtils { public static Map<Integer, Integer> getPortRangesFromList(int... ports) { Set<Integer> sortedPorts = ImmutableSortedSet.copyOf(Ints.asList(ports)); RangeSet<Integer> ranges = TreeRangeSet.create(); for (Integer port : sortedPorts) { ranges.add(Range.closedOpen(port, port + 1)); } Map<Integer, Integer> portRanges = Maps.newHashMap(); for (Range<Integer> r : ranges.asRanges()) { portRanges.put(r.lowerEndpoint(), r.upperEndpoint() - 1); } return portRanges; } static String formatStatus(ComputeMetadataIncludingStatus<?> resource); static Statement execHttpResponse(HttpRequest request); static Statement execHttpResponse(URI location); static Statement extractTargzIntoDirectory(HttpRequest targz, String directory); static Statement extractTargzIntoDirectory(URI targz, String directory); static Statement extractZipIntoDirectory(HttpRequest zip, String directory); static Statement extractZipIntoDirectory(URI zip, String directory); static double getCores(Hardware input); static double getCoresAndSpeed(Hardware input); static double getSpace(Hardware input); static org.jclouds.compute.domain.OsFamily parseOsFamilyOrUnrecognized(String in); static String createExecutionErrorMessage(Map<?, Exception> executionExceptions); static String createNodeErrorMessage(Map<? extends NodeMetadata, ? extends Throwable> failedNodes); static Iterable<? extends ComputeMetadata> filterByName(Iterable<? extends ComputeMetadata> nodes, final String name); static Map<String, String> metadataAndTagsAsValuesOfEmptyString(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromValuesOfEmptyString(NodeMetadataBuilder builder, Map<String, String> map); static Map<String, String> metadataAndTagsAsCommaDelimitedValue(TemplateOptions options); static NodeMetadataBuilder addMetadataAndParseTagsFromCommaDelimitedValue(NodeMetadataBuilder builder, Map<String, String> map); static String parseVersionOrReturnEmptyString(org.jclouds.compute.domain.OsFamily family, String in, Map<OsFamily, Map<String, String>> osVersionMap); static Map<Integer, Integer> getPortRangesFromList(int... ports); static String groupFromMapOrName(Map<String, String> metadataMap, String nodeName, GroupNamingConvention namingConvention); static final Pattern DELIMITED_BY_HYPHEN_ENDING_IN_HYPHEN_HEX; }
@Test public void testGetPortRangesFromList() { Map<Integer, Integer> portRanges = Maps.newHashMap(); portRanges.put(5, 7); portRanges.put(10, 11); portRanges.put(20, 20); assertEquals(portRanges, ComputeServiceUtils.getPortRangesFromList(5, 6, 7, 10, 11, 20)); }
AutomaticHardwareIdSpec { public static boolean isAutomaticId(String id) { return id.startsWith("automatic:"); } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }
@Test public void isAutomaticIdTest() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("automatic:cores=2;ram=256")).isTrue(); } @Test public void isNotAutomaticId() { assertThat(AutomaticHardwareIdSpec.isAutomaticId("Hi, I'm a non automatic id.")).isFalse(); }
AutomaticHardwareIdSpec { public static AutomaticHardwareIdSpec parseId(String hardwareId) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); String hardwareSpec = hardwareId.substring(10); Map<String, String> specValues = Splitter.on(';') .trimResults() .omitEmptyStrings() .withKeyValueSeparator('=') .split(hardwareSpec); if (!specValues.containsKey("ram") || !specValues.containsKey("cores")) { throw new IllegalArgumentException(String.format("Omitted keys on hardwareId: %s. Please set number " + "of cores and ram amount.", hardwareId)); } if (specValues.containsKey("disk")) { float disk = Float.parseFloat(specValues.get("disk")); if (disk > 0.0f) { spec.disk = Optional.of(disk); } else { throw new IllegalArgumentException(String.format("Invalid disk value: %s", hardwareId)); } } spec.ram = Integer.parseInt(specValues.get("ram")); spec.cores = Double.parseDouble(specValues.get("cores")); return spec; } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }
@Test(expectedExceptions = IllegalArgumentException.class) public void parseAutomaticIdMissingValuesTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Invalid disk value: automatic:cores=2;ram=4096;disk=-100") public void parseAutomaticIdInvalidDiskTest() { AutomaticHardwareIdSpec.parseId("automatic:cores=2;ram=4096;disk=-100"); }
AutomaticHardwareIdSpec { public static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk) { AutomaticHardwareIdSpec spec = new AutomaticHardwareIdSpec(); if (cores <= 0 || ram == 0) { throw new IllegalArgumentException(String.format("Omitted or wrong minCores and minRam. If you want to" + " use exact values, please set the minCores and minRam values: cores=%s, ram=%s", cores, ram)); } if (disk.isPresent() && disk.get() <= 0.0f) { throw new IllegalArgumentException(String.format("Invalid disk value: %.0f", disk.get())); } spec.disk = disk; spec.cores = cores; spec.ram = ram; return spec; } static boolean isAutomaticId(String id); static AutomaticHardwareIdSpec parseId(String hardwareId); static AutomaticHardwareIdSpec automaticHardwareIdSpecBuilder(double cores, int ram, Optional<Float> disk); @Override String toString(); double getCores(); int getRam(); Optional<Float> getDisk(); }
@Test public void automaticHardwareIdSpecBuilderTest() { AutomaticHardwareIdSpec spec = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.<Float>absent()); assertThat(spec.getCores()).isEqualTo(2.0); assertThat(spec.getRam()).isEqualTo(2048); assertThat(spec.toString()).isEqualTo("automatic:cores=2.0;ram=2048"); AutomaticHardwareIdSpec spec2 = AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(4.0, 4096, Optional.of(10.0f)); assertThat(spec2.getCores()).isEqualTo(4.0); assertThat(spec2.getRam()).isEqualTo(4096); assertThat(spec2.getDisk().get()).isEqualTo(10); assertThat(spec2.toString()).isEqualTo("automatic:cores=4.0;ram=4096;disk=10"); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Omitted or wrong minCores and minRam. If you want to" + " use exact values, please set the minCores and minRam values: cores=2.0, ram=0") public void automaticHardwareIdSpecBuilderWrongSpecsTest() { AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 0, Optional.<Float>absent()); } @Test(expectedExceptions = IllegalArgumentException.class, expectedExceptionsMessageRegExp = "Invalid disk value: -10") public void automaticHardwareIdSpecBuilderWrongDiskTest() { AutomaticHardwareIdSpec.automaticHardwareIdSpecBuilder(2.0, 2048, Optional.of(-10.0f)); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions installPrivateKey(String privateKey) { checkArgument(checkNotNull(privateKey, "privateKey").startsWith("-----BEGIN RSA PRIVATE KEY-----"), "key should start with -----BEGIN RSA PRIVATE KEY-----"); this.privateKey = privateKey; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testinstallPrivateKeyBadFormat() { TemplateOptions options = new TemplateOptions(); options.installPrivateKey("whompy"); } @Test public void testinstallPrivateKey() throws IOException { TemplateOptions options = new TemplateOptions(); options.installPrivateKey("-----BEGIN RSA PRIVATE KEY-----"); assertEquals(options.toString(), "{privateKeyPresent=true}"); assertEquals(options.getPrivateKey(), "-----BEGIN RSA PRIVATE KEY-----"); } @Test(expectedExceptions = NullPointerException.class) public void testinstallPrivateKeyNPE() { installPrivateKey((String) null); }
TemplateOptions extends RunScriptOptions implements Cloneable { public String getPrivateKey() { return privateKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testNullinstallPrivateKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPrivateKey(), null); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions authorizePublicKey(String publicKey) { checkArgument(checkNotNull(publicKey, "publicKey").startsWith("ssh-rsa"), "key should start with ssh-rsa"); this.publicKey = publicKey; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testauthorizePublicKeyBadFormat() { TemplateOptions options = new TemplateOptions(); options.authorizePublicKey("whompy"); } @Test public void testauthorizePublicKey() throws IOException { TemplateOptions options = new TemplateOptions(); options.authorizePublicKey("ssh-rsa"); assertEquals(options.toString(), "{publicKeyPresent=true}"); assertEquals(options.getPublicKey(), "ssh-rsa"); } @Test(expectedExceptions = NullPointerException.class) public void testauthorizePublicKeyNPE() { authorizePublicKey((String) null); }
TemplateOptions extends RunScriptOptions implements Cloneable { public String getPublicKey() { return publicKey; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testNullauthorizePublicKey() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getPublicKey(), null); }
TemplateOptions extends RunScriptOptions implements Cloneable { @Override public TemplateOptions blockOnPort(int port, int seconds) { return TemplateOptions.class.cast(super.blockOnPort(port, seconds)); } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testblockOnPortBadFormat() { TemplateOptions options = new TemplateOptions(); options.blockOnPort(-1, -1); } @Test public void testblockOnPort() { TemplateOptions options = new TemplateOptions(); options.blockOnPort(22, 30); assertEquals(options.toString(), "{blockOnPort:seconds=22:30}"); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); } @Test public void testblockOnPortStatic() { TemplateOptions options = blockOnPort(22, 30); assertEquals(options.getPort(), 22); assertEquals(options.getSeconds(), 30); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions inboundPorts(int... ports) { for (int port : ports) checkArgument(port > 0 && port < 65536, "port must be a positive integer < 65535"); this.inboundPorts = ImmutableSet.copyOf(Ints.asList(ports)); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test(expectedExceptions = IllegalArgumentException.class) public void testinboundPortsBadFormat() { TemplateOptions options = new TemplateOptions(); options.inboundPorts(-1, -1); } @Test public void testinboundPorts() { TemplateOptions options = new TemplateOptions(); options.inboundPorts(22, 30); assertEquals(options.getInboundPorts()[0], 22); assertEquals(options.getInboundPorts()[1], 30); }
TemplateOptions extends RunScriptOptions implements Cloneable { public int[] getInboundPorts() { return Ints.toArray(inboundPorts); } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testDefaultOpen22() { TemplateOptions options = new TemplateOptions(); assertEquals(options.getInboundPorts()[0], 22); }
TemplateOptions extends RunScriptOptions implements Cloneable { public boolean shouldBlockUntilRunning() { return blockUntilRunning; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testblockUntilRunningDefault() { TemplateOptions options = new TemplateOptions(); assertEquals(options.toString(), "{}"); assertEquals(options.shouldBlockUntilRunning(), true); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions blockUntilRunning(boolean blockUntilRunning) { this.blockUntilRunning = blockUntilRunning; if (!blockUntilRunning) port = seconds = -1; return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testblockUntilRunning() { TemplateOptions options = new TemplateOptions(); options.blockUntilRunning(false); assertEquals(options.toString(), "{blockUntilRunning=false}"); assertEquals(options.shouldBlockUntilRunning(), false); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions nodeNames(Iterable<String> nodeNames) { this.nodeNames = ImmutableSet.copyOf(checkNotNull(nodeNames, "nodeNames")); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testNodeNames() { Set<String> nodeNames = ImmutableSet.of("first-node", "second-node"); TemplateOptions options = nodeNames(nodeNames); assertTrue(options.getNodeNames().containsAll(nodeNames)); }
TemplateOptions extends RunScriptOptions implements Cloneable { public TemplateOptions networks(Iterable<String> networks) { this.networks = ImmutableSet.copyOf(checkNotNull(networks, "networks")); return this; } @Override TemplateOptions clone(); void copyTo(TemplateOptions to); boolean equals(Object o); @Override int hashCode(); @Override ToStringHelper string(); int[] getInboundPorts(); Statement getRunScript(); Set<String> getTags(); Set<String> getNodeNames(); Set<String> getGroups(); String getPrivateKey(); String getPublicKey(); Set<String> getNetworks(); boolean shouldBlockUntilRunning(); T as(Class<T> clazz); TemplateOptions runScript(String script); TemplateOptions runScript(Statement script); TemplateOptions installPrivateKey(String privateKey); TemplateOptions dontAuthorizePublicKey(); TemplateOptions authorizePublicKey(String publicKey); TemplateOptions tags(Iterable<String> tags); TemplateOptions nodeNames(Iterable<String> nodeNames); TemplateOptions securityGroups(Iterable<String> securityGroups); TemplateOptions securityGroups(String... securityGroups); TemplateOptions networks(Iterable<String> networks); TemplateOptions networks(String... networks); TemplateOptions inboundPorts(int... ports); TemplateOptions blockUntilRunning(boolean blockUntilRunning); TemplateOptions userMetadata(Map<String, String> userMetadata); TemplateOptions userMetadata(String key, String value); Map<String, String> getUserMetadata(); @Override TemplateOptions blockOnPort(int port, int seconds); @Override TemplateOptions nameTask(String name); @Override TemplateOptions runAsRoot(boolean runAsRoot); @Override TemplateOptions wrapInInitScript(boolean wrapInInitScript); @Override TemplateOptions blockOnComplete(boolean blockOnComplete); @Override TemplateOptions overrideLoginCredentials(LoginCredentials overridingCredentials); @Override TemplateOptions overrideLoginPassword(String password); @Override TemplateOptions overrideLoginPrivateKey(String privateKey); @Override TemplateOptions overrideLoginUser(String loginUser); @Override TemplateOptions overrideAuthenticateSudo(boolean authenticateSudo); static final TemplateOptions NONE; }
@Test public void testNetworks() { Set<String> networks = ImmutableSet.of("first-network", "second-network"); TemplateOptions options = networks(networks); assertTrue(options.getNetworks().containsAll(networks)); }
Sha512Crypt { static String makeShadowLine(String password, @Nullable String shadowPrefix) { MessageDigest ctx = sha512(); MessageDigest alt_ctx = sha512(); byte[] alt_result; byte[] temp_result; byte[] p_bytes = null; byte[] s_bytes = null; int cnt; int cnt2; int rounds = ROUNDS_DEFAULT; StringBuilder buffer; if (shadowPrefix != null) { if (shadowPrefix.startsWith(sha512_salt_prefix)) { shadowPrefix = shadowPrefix.substring(sha512_salt_prefix.length()); } if (shadowPrefix.startsWith(sha512_rounds_prefix)) { String num = shadowPrefix.substring(sha512_rounds_prefix.length(), shadowPrefix.indexOf('$')); int srounds = Integer.parseInt(num); shadowPrefix = shadowPrefix.substring(shadowPrefix.indexOf('$') + 1); rounds = Math.max(ROUNDS_MIN, Math.min(srounds, ROUNDS_MAX)); } if (shadowPrefix.length() > SALT_LEN_MAX) { shadowPrefix = shadowPrefix.substring(0, SALT_LEN_MAX); } } else { java.util.Random randgen = new java.security.SecureRandom(); StringBuilder saltBuf = new StringBuilder(); while (saltBuf.length() < 16) { int index = (int) (randgen.nextFloat() * SALTCHARS.length()); saltBuf.append(SALTCHARS, index, index + 1); } shadowPrefix = saltBuf.toString(); } byte[] key = password.getBytes(); byte[] salts = shadowPrefix.getBytes(); ctx.reset(); ctx.update(key, 0, key.length); ctx.update(salts, 0, salts.length); alt_ctx.reset(); alt_ctx.update(key, 0, key.length); alt_ctx.update(salts, 0, salts.length); alt_ctx.update(key, 0, key.length); alt_result = alt_ctx.digest(); for (cnt = key.length; cnt > 64; cnt -= 64) { ctx.update(alt_result, 0, 64); } ctx.update(alt_result, 0, cnt); for (cnt = key.length; cnt > 0; cnt >>= 1) { if ((cnt & 1) != 0) { ctx.update(alt_result, 0, 64); } else { ctx.update(key, 0, key.length); } } alt_result = ctx.digest(); alt_ctx.reset(); for (cnt = 0; cnt < key.length; ++cnt) { alt_ctx.update(key, 0, key.length); } temp_result = alt_ctx.digest(); p_bytes = new byte[key.length]; for (cnt2 = 0, cnt = p_bytes.length; cnt >= 64; cnt -= 64) { System.arraycopy(temp_result, 0, p_bytes, cnt2, 64); cnt2 += 64; } System.arraycopy(temp_result, 0, p_bytes, cnt2, cnt); alt_ctx.reset(); for (cnt = 0; cnt < 16 + (alt_result[0] & 0xFF); ++cnt) { alt_ctx.update(salts, 0, salts.length); } temp_result = alt_ctx.digest(); s_bytes = new byte[salts.length]; for (cnt2 = 0, cnt = s_bytes.length; cnt >= 64; cnt -= 64) { System.arraycopy(temp_result, 0, s_bytes, cnt2, 64); cnt2 += 64; } System.arraycopy(temp_result, 0, s_bytes, cnt2, cnt); for (cnt = 0; cnt < rounds; ++cnt) { ctx.reset(); if ((cnt & 1) != 0) { ctx.update(p_bytes, 0, key.length); } else { ctx.update(alt_result, 0, 64); } if (cnt % 3 != 0) { ctx.update(s_bytes, 0, salts.length); } if (cnt % 7 != 0) { ctx.update(p_bytes, 0, key.length); } if ((cnt & 1) != 0) { ctx.update(alt_result, 0, 64); } else { ctx.update(p_bytes, 0, key.length); } alt_result = ctx.digest(); } buffer = new StringBuilder(sha512_salt_prefix); if (rounds != 5000) { buffer.append(sha512_rounds_prefix); buffer.append(rounds); buffer.append("$"); } buffer.append(shadowPrefix); buffer.append("$"); buffer.append(b64_from_24bit(alt_result[0], alt_result[21], alt_result[42], 4)); buffer.append(b64_from_24bit(alt_result[22], alt_result[43], alt_result[1], 4)); buffer.append(b64_from_24bit(alt_result[44], alt_result[2], alt_result[23], 4)); buffer.append(b64_from_24bit(alt_result[3], alt_result[24], alt_result[45], 4)); buffer.append(b64_from_24bit(alt_result[25], alt_result[46], alt_result[4], 4)); buffer.append(b64_from_24bit(alt_result[47], alt_result[5], alt_result[26], 4)); buffer.append(b64_from_24bit(alt_result[6], alt_result[27], alt_result[48], 4)); buffer.append(b64_from_24bit(alt_result[28], alt_result[49], alt_result[7], 4)); buffer.append(b64_from_24bit(alt_result[50], alt_result[8], alt_result[29], 4)); buffer.append(b64_from_24bit(alt_result[9], alt_result[30], alt_result[51], 4)); buffer.append(b64_from_24bit(alt_result[31], alt_result[52], alt_result[10], 4)); buffer.append(b64_from_24bit(alt_result[53], alt_result[11], alt_result[32], 4)); buffer.append(b64_from_24bit(alt_result[12], alt_result[33], alt_result[54], 4)); buffer.append(b64_from_24bit(alt_result[34], alt_result[55], alt_result[13], 4)); buffer.append(b64_from_24bit(alt_result[56], alt_result[14], alt_result[35], 4)); buffer.append(b64_from_24bit(alt_result[15], alt_result[36], alt_result[57], 4)); buffer.append(b64_from_24bit(alt_result[37], alt_result[58], alt_result[16], 4)); buffer.append(b64_from_24bit(alt_result[59], alt_result[17], alt_result[38], 4)); buffer.append(b64_from_24bit(alt_result[18], alt_result[39], alt_result[60], 4)); buffer.append(b64_from_24bit(alt_result[40], alt_result[61], alt_result[19], 4)); buffer.append(b64_from_24bit(alt_result[62], alt_result[20], alt_result[41], 4)); buffer.append(b64_from_24bit((byte) 0x00, (byte) 0x00, alt_result[63], 2)); ctx.reset(); return buffer.toString(); } static com.google.common.base.Function<String, String> function(); }
@Test(dataProvider = "data") public void testMakeCryptedPasswordHash(String password, String salt, String expected) { assertEquals(Sha512Crypt.makeShadowLine(password, salt), expected); }
NodeAndTemplateOptionsToStatementWithoutPublicKey implements NodeAndTemplateOptionsToStatement { @Override public Statement apply(NodeMetadata node, TemplateOptions options) { ImmutableList.Builder<Statement> builder = ImmutableList.builder(); if (options.getRunScript() != null) { builder.add(options.getRunScript()); } if (options.getPrivateKey() != null) { builder.add(new InstallRSAPrivateKey(options.getPrivateKey())); } ImmutableList<Statement> bootstrap = builder.build(); if (!bootstrap.isEmpty()) { if (options.getTaskName() == null && !(options.getRunScript() instanceof InitScript)) { options.nameTask("bootstrap"); } return bootstrap.size() == 1 ? bootstrap.get(0) : new StatementList(bootstrap); } return null; } @Override Statement apply(NodeMetadata node, TemplateOptions options); }
@Test public void testPublicKeyDoesNotGenerateAuthorizePublicKeyStatementIfOnlyPublicKeyOptionsConfigured() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); assertNull(function.apply(null, options)); } @Test public void testPublicAndRunScriptKeyDoesNotGenerateAuthorizePublicKeyStatementIfRunScriptPresent() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")).runScript("uptime"); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); Statement statement = function.apply(null, options); assertEquals(statement.render(OsFamily.UNIX), "uptime\n"); } @Test public void testPublicAndPrivateKeyAndRunScriptDoesNotGenerateAuthorizePublicKeyStatementIfOtherOptionsPresent() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")) .installPrivateKey(keys.get("private")).runScript("uptime"); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndTemplateOptionsToStatementWithoutPublicKey(); Statement statement = function.apply(null, options); assertTrue(statement instanceof StatementList); StatementList statements = (StatementList) statement; assertEquals(statements.size(), 2); assertEquals(statements.get(0).render(OsFamily.UNIX), "uptime\n"); assertTrue(statements.get(1) instanceof InstallRSAPrivateKey); }
PollNodeRunning implements Function<AtomicReference<NodeMetadata>, AtomicReference<NodeMetadata>> { @Override public AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node) throws IllegalStateException { String originalId = node.get().getId(); NodeMetadata originalNode = node.get(); try { Stopwatch stopwatch = Stopwatch.createStarted(); if (!nodeRunning.apply(node)) { long timeWaited = stopwatch.elapsed(TimeUnit.MILLISECONDS); if (node.get() == null) { node.set(originalNode); throw new IllegalStateException(format("api response for node(%s) was null", originalId)); } else { throw new IllegalStateException(format( "node(%s) didn't achieve the status running; aborting after %d seconds with final status: %s", originalId, timeWaited / 1000, formatStatus(node.get()))); } } } catch (IllegalStateException e) { if (node.get().getStatus() == Status.TERMINATED) { throw new IllegalStateException(format("node(%s) terminated", originalId)); } else { throw propagate(e); } } return node; } @Inject PollNodeRunning(@Named(TIMEOUT_NODE_RUNNING) Predicate<AtomicReference<NodeMetadata>> nodeRunning); @Override AtomicReference<NodeMetadata> apply(AtomicReference<NodeMetadata> node); }
@Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) didn't achieve the status running; aborting after 0 seconds with final status: PENDING") public void testIllegalStateExceptionWhenNodeStillPending() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), pendingNode); } } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "node\\(id\\) terminated") public void testIllegalStateExceptionWhenNodeDied() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); final NodeMetadata deadNode = new NodeMetadataBuilder().ids("id").status(Status.TERMINATED).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); input.set(deadNode); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), deadNode); } } @Test(expectedExceptions = IllegalStateException.class, expectedExceptionsMessageRegExp = "api response for node\\(id\\) was null") public void testIllegalStateExceptionAndNodeResetWhenRefSetToNull() { final NodeMetadata pendingNode = new NodeMetadataBuilder().ids("id").status(Status.PENDING).build(); Predicate<AtomicReference<NodeMetadata>> nodeRunning = new Predicate<AtomicReference<NodeMetadata>>() { @Override public boolean apply(AtomicReference<NodeMetadata> input) { assertEquals(input.get(), pendingNode); input.set(null); return false; } }; AtomicReference<NodeMetadata> atomicNode = Atomics.newReference(pendingNode); try { new PollNodeRunning(nodeRunning).apply(atomicNode); } finally { assertEquals(atomicNode.get(), pendingNode); } }
JschSshClient implements SshClient { SshException propagate(Exception e, String message) { message += ": " + e.getMessage(); if (e.getMessage() != null && e.getMessage().indexOf("Auth fail") != -1) throw new AuthorizationException("(" + toString() + ") " + message, e); throw e instanceof SshException ? SshException.class.cast(e) : new SshException( "(" + toString() + ") " + message, e); } JschSshClient(ProxyConfig proxyConfig, BackoffLimitedRetryHandler backoffLimitedRetryHandler, HostAndPort socket, LoginCredentials loginCredentials, int timeout, Optional<Connector> agentConnector); @Override void put(String path, String contents); void connect(); Payload get(String path); @Override void put(String path, Payload contents); @Override String toString(); @Override @PreDestroy void disconnect(); @Override boolean isConnected(); ExecResponse exec(String command); @Override String getHostAddress(); @Override String getUsername(); @Override ExecChannel execChannel(String command); }
@Test(expectedExceptions = AuthorizationException.class) public void testPropateConvertsAuthException() { ssh.propagate(new JSchException("Auth fail"), ""); }
DelegatingImageExtension implements ImageExtension { public ListenableFuture<Image> createImage(final ImageTemplate template) { ListenableFuture<Image> future = delegate.createImage(template); future = Futures.transform(future, new Function<Image, Image>() { @Override public Image apply(Image input) { if (input.getDefaultCredentials() != null) { return input; } if (template instanceof CloneImageTemplate) { final CloneImageTemplate cloneImageTemplate = (CloneImageTemplate) template; Credentials nodeCredentials = credentialStore.get("node#" + cloneImageTemplate.getSourceNodeId()); if (nodeCredentials != null) { logger.info(">> Adding node(%s) credentials to image(%s)...", cloneImageTemplate.getSourceNodeId(), cloneImageTemplate.getName()); return ImageBuilder.fromImage(input) .defaultCredentials(LoginCredentials.fromCredentials(nodeCredentials)).build(); } } logger.info(">> Adding default image credentials to image(%s)...", template.getName()); return addDefaultCredentialsToImage.apply(input); } }); Futures.addCallback(future, new FutureCallback<Image>() { @Override public void onSuccess(Image result) { imageCache.registerImage(result); } @Override public void onFailure(Throwable t) { } }); return future; } @Inject DelegatingImageExtension(@Assisted ImageCacheSupplier imageCache, @Assisted ImageExtension delegate, AddDefaultCredentialsToImage addDefaultCredentialsToImage, Map<String, Credentials> credentialStore); ImageTemplate buildImageTemplateFromNode(String name, String id); ListenableFuture<Image> createImage(final ImageTemplate template); boolean deleteImage(String id); }
@Test public void createImageRegistersInCacheAndAddsCredentials() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); ImageTemplate template = new ImageTemplateImpl("test") { }; Image result = new ImageBuilder().id("test") .operatingSystem(OperatingSystem.builder().description("test").build()).status(Status.AVAILABLE).build(); LoginCredentials credentials = LoginCredentials.builder().user("jclouds").password("pass").build(); Image withCredentials = ImageBuilder.fromImage(result).defaultCredentials(credentials).build(); expect(delegate.createImage(template)).andReturn(immediateFuture(result)); expect(credsToImage.apply(result)).andReturn(withCredentials); imageCache.registerImage(withCredentials); expectLastCall(); replay(delegate, imageCache, credsToImage); new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template); verify(delegate, imageCache, credsToImage); } @Test public void createImageDoesNotRegisterInCacheWhenFailed() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); ImageTemplate template = new ImageTemplateImpl("test") { }; expect(delegate.createImage(template)).andReturn(Futures.<Image> immediateFailedFuture(new RuntimeException())); replay(delegate, imageCache, credsToImage); new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template); verify(delegate, imageCache, credsToImage); } @Test public void createImageDoesNotRegisterInCacheWhenCancelled() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); ImageTemplate template = new ImageTemplateImpl("test") { }; expect(delegate.createImage(template)).andReturn(Futures.<Image> immediateCancelledFuture()); replay(delegate, imageCache, credsToImage); new DelegatingImageExtension(imageCache, delegate, credsToImage, null).createImage(template); verify(delegate, imageCache, credsToImage); } @Test public void createByCloningDoesNothingIfImageHasCredentials() throws InterruptedException, ExecutionException { LoginCredentials credentials = LoginCredentials.builder().user("jclouds").password("pass").build(); ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); ImageTemplate template = new CloneImageTemplateBuilder().name("test").nodeId("node1").build(); Image result = new ImageBuilder().id("test") .operatingSystem(OperatingSystem.builder().description("test").build()).status(Status.AVAILABLE) .defaultCredentials(credentials).build(); expect(delegate.createImage(template)).andReturn(immediateFuture(result)); replay(delegate, credsToImage); Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, null) .createImage(template); assertTrue(image.get() == result); verify(delegate, credsToImage); } @Test public void createByCloningAddsNodeCredentials() throws InterruptedException, ExecutionException { Credentials credentials = LoginCredentials.builder().user("jclouds").password("pass").build(); ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); Map<String, Credentials> credentialStore = ImmutableMap.of("node#node1", credentials); ImageTemplate template = new CloneImageTemplateBuilder().name("test").nodeId("node1").build(); Image result = new ImageBuilder().id("test") .operatingSystem(OperatingSystem.builder().description("test").build()).status(Status.AVAILABLE).build(); expect(delegate.createImage(template)).andReturn(immediateFuture(result)); replay(delegate, credsToImage); Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, credentialStore) .createImage(template); assertEquals(image.get().getDefaultCredentials(), credentials); verify(delegate, credsToImage); } @Test public void createByCloningAddsDefaultImageCredentials() throws InterruptedException, ExecutionException { LoginCredentials credentials = LoginCredentials.builder().user("jclouds").password("pass").build(); ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); Map<String, Credentials> credentialStore = Collections.emptyMap(); ImageTemplate template = new CloneImageTemplateBuilder().name("test").nodeId("node1").build(); Image result = new ImageBuilder().id("test") .operatingSystem(OperatingSystem.builder().description("test").build()).status(Status.AVAILABLE).build(); expect(delegate.createImage(template)).andReturn(immediateFuture(result)); expect(credsToImage.apply(result)).andReturn( ImageBuilder.fromImage(result).defaultCredentials(credentials).build()); replay(delegate, credsToImage); Future<Image> image = new DelegatingImageExtension(imageCache, delegate, credsToImage, credentialStore) .createImage(template); assertEquals(image.get().getDefaultCredentials(), credentials); verify(delegate, credsToImage); }
DelegatingImageExtension implements ImageExtension { public boolean deleteImage(String id) { boolean success = delegate.deleteImage(id); if (success) { imageCache.removeImage(id); } return success; } @Inject DelegatingImageExtension(@Assisted ImageCacheSupplier imageCache, @Assisted ImageExtension delegate, AddDefaultCredentialsToImage addDefaultCredentialsToImage, Map<String, Credentials> credentialStore); ImageTemplate buildImageTemplateFromNode(String name, String id); ListenableFuture<Image> createImage(final ImageTemplate template); boolean deleteImage(String id); }
@Test public void deleteUnregistersImageFromCache() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(true); imageCache.removeImage("test"); expectLastCall(); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); } @Test public void deleteDoesNotUnregisterImageFromCacheWhenFailed() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); expect(delegate.deleteImage("test")).andReturn(false); replay(delegate, imageCache); new DelegatingImageExtension(imageCache, delegate, null, null).deleteImage("test"); verify(delegate, imageCache); }
ProfitBricksSoapMessageEnvelope implements HttpRequestFilter { @Override public HttpRequest filter(HttpRequest request) throws HttpException { checkNotNull(request.getPayload(), "HTTP Request must contain payload message."); return createSoapRequest(request); } @Override HttpRequest filter(HttpRequest request); }
@Test public void testPayloadEnclosedWithSoapTags() { String requestBody = "<ws:getAllDataCenters/>"; String expectedPayload = SOAP_PREFIX.concat(requestBody).concat(SOAP_SUFFIX); HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).payload(requestBody).build(); ProfitBricksSoapMessageEnvelope soapEnvelope = new ProfitBricksSoapMessageEnvelope(); HttpRequest filtered = soapEnvelope.filter(request); assertEquals(filtered.getPayload().getRawContent(), expectedPayload); assertEquals(filtered.getPayload().getContentMetadata().getContentLength(), Long.valueOf(expectedPayload.getBytes().length)); } @Test(expectedExceptions = NullPointerException.class, expectedExceptionsMessageRegExp = ".*must contain payload message.*") public void testNullRequest() { HttpRequest request = HttpRequest.builder().method("POST").endpoint(ENDPOINT).build(); new ProfitBricksSoapMessageEnvelope().filter(request); }
NullEqualToIsParentOrIsGrandparentOfCurrentLocation implements Predicate<ComputeMetadata> { @Override public boolean apply(ComputeMetadata input) { Location current = locationSupplier.get(); if (current == null) return true; if (input.getLocation() == null) return true; Location parent = current.getParent(); checkArgument( parent != null || current.getScope() == LocationScope.PROVIDER, "only locations of scope PROVIDER can have a null parent; arg: %s", current); checkState( input.getLocation().getParent() != null || input.getLocation().getScope() == LocationScope.PROVIDER, "only locations of scope PROVIDER can have a null parent; input: %s", input.getLocation()); Builder<Predicate<Location>> predicates = ImmutableSet.builder(); predicates.add(equalTo(current)); if (parent != null) { predicates.add(equalTo(parent)); Location grandparent = parent.getParent(); if (grandparent != null) predicates.add(equalTo(grandparent)); } return Predicates.or(predicates.build()).apply(input.getLocation()); } NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Supplier<Location> locationSupplier); @Override boolean apply(ComputeMetadata input); @Override String toString(); }
@Test public void testReturnTrueWhenISpecifyARegionAndInputLocationIsProvider() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(provider).build(); assertTrue(predicate.apply(md)); } @Test public void testReturnFalseWhenISpecifyALocationWhichTheSameScopeByNotEqualToInputLocationAndParentsAreNull() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(otherRegion).build(); assertFalse(predicate.apply(md)); } @Test(expectedExceptions = IllegalStateException.class) public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedRegion() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(orphanedRegion).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalStateException.class) public void testThrowIllegalStateExceptionWhenInputIsAnOrphanedZone() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(orphanedZone).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedRegion() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedRegion)); Hardware md = new HardwareBuilder().id("foo").location(region).build(); predicate.apply(md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testThrowIllegalArgumentExceptionWhenWhenISpecifyAnOrphanedZone() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(orphanedZone)); Hardware md = new HardwareBuilder().id("foo").location(region).build(); predicate.apply(md); }
TemplateBuilderImpl implements TemplateBuilder { @Override public Template build() { if (nothingChangedExceptOptions()) { TemplateBuilder defaultTemplate = defaultTemplateProvider.get(); if (options != null) defaultTemplate.options(options); return defaultTemplate.build(); } if (options == null) options = optionsProvider.get(); logger.debug(">> searching params(%s)", this); Set<? extends Image> images = getImages(); checkState(!images.isEmpty(), "no images present!"); Set<? extends Hardware> hardwaresToSearch = hardwares.get(); checkState(!hardwaresToSearch.isEmpty(), "no hardware profiles present!"); Image image = null; if (imageId != null) { image = loadImageWithId(images); if (currentLocationWiderThan(image.getLocation())) this.location = image.getLocation(); } Hardware hardware = null; if (hardwareId != null) { hardware = findHardwareWithId(hardwaresToSearch); if (currentLocationWiderThan(hardware.getLocation())) this.location = hardware.getLocation(); } if (location == null) location = defaultLocation.get(); if (image == null) { Iterable<? extends Image> supportedImages = findSupportedImages(images); if (hardware == null) hardware = resolveHardware(hardwaresToSearch, supportedImages); image = resolveImage(hardware, supportedImages); } else { if (hardware == null) hardware = resolveHardware(hardwaresToSearch, ImmutableSet.of(image)); } logger.debug("<< matched image(%s) hardware(%s) location(%s)", image.getId(), hardware.getId(), location.getId()); return new TemplateImpl(image, hardware, location, options); } @Inject protected TemplateBuilderImpl(@Memoized Supplier<Set<? extends Location>> locations, @Memoized Supplier<Set<? extends Image>> images, @Memoized Supplier<Set<? extends Hardware>> hardwares, Supplier<Location> defaultLocation, @Named("DEFAULT") Provider<TemplateOptions> optionsProvider, @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider); @Override TemplateBuilder fromTemplate(Template template); @Override TemplateBuilder fromHardware(Hardware hardware); @Override TemplateBuilder fromImage(Image image); @Override TemplateBuilder smallest(); @Override TemplateBuilder biggest(); @Override TemplateBuilder fastest(); @Override TemplateBuilder locationId(final String locationId); @Override TemplateBuilder osFamily(OsFamily os); @Override Template build(); @Override TemplateBuilder imageId(String imageId); @Override TemplateBuilder imageNameMatches(String nameRegex); @Override TemplateBuilder imageDescriptionMatches(String descriptionRegex); @Override TemplateBuilder imageMatches(Predicate<Image> condition); @Override TemplateBuilderImpl imageChooser(Function<Iterable<? extends Image>, Image> imageChooser); @Override TemplateBuilder imageVersionMatches(String imageVersionRegex); @Override TemplateBuilder osVersionMatches(String osVersionRegex); @Override TemplateBuilder osArchMatches(String osArchitectureRegex); @Override TemplateBuilder minCores(double minCores); @Override TemplateBuilder minRam(int megabytes); @Override TemplateBuilder minDisk(double gigabytes); @Override TemplateBuilder osNameMatches(String osNameRegex); @Override TemplateBuilder osDescriptionMatches(String osDescriptionRegex); @Override TemplateBuilder hardwareId(String hardwareId); @Override TemplateBuilder hypervisorMatches(String hypervisor); @Override TemplateBuilder options(TemplateOptions options); @Override TemplateBuilder any(); @Override String toString(); @Override TemplateBuilder os64Bit(boolean is64Bit); @Override TemplateBuilder from(TemplateBuilderSpec spec); @Override TemplateBuilder from(String spec); @Override TemplateBuilder forceCacheReload(); }
@SuppressWarnings("unchecked") @Test public void testNothingUsesDefaultTemplateBuilder() { Supplier<Set<? extends Location>> locations = Suppliers.<Set<? extends Location>> ofInstance(ImmutableSet .<Location> of()); Supplier<Set<? extends Image>> images = Suppliers.<Set<? extends Image>> ofInstance(ImmutableSet.<Image> of()); Supplier<Set<? extends Hardware>> hardwares = Suppliers.<Set<? extends Hardware>> ofInstance(ImmutableSet .<Hardware> of()); Location defaultLocation = createMock(Location.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); GetImageStrategy getImageStrategy = createMock(GetImageStrategy.class); expect(templateBuilderProvider.get()).andReturn(defaultTemplate); expect(defaultTemplate.build()).andReturn(null); replay(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy); TemplateBuilderImpl template = createTemplateBuilder(null, locations, images, hardwares, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy); template.build(); verify(defaultTemplate, defaultLocation, optionsProvider, templateBuilderProvider, getImageStrategy); }
SshKeys { public static String fingerprint(BigInteger publicExponent, BigInteger modulus) { byte[] keyBlob = keyBlob(publicExponent, modulus); return hexColonDelimited(Hashing.md5().hashBytes(keyBlob)); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }
@Test public void testCanReadRsaAndCompareFingerprintOnPrivateRSAKey() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec key = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); String fingerPrint = fingerprint(key.getPublicExponent(), key.getModulus()); assertEquals(fingerPrint, expectedFingerprint); }
SshKeys { public static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint) { return fingerprint(privateKey.getPublicExponent(), privateKey.getModulus()).equals(fingerprint); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }
@Test public void testPrivateKeyMatchesFingerprintTyped() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); assert privateKeyHasFingerprint(privateKey, expectedFingerprint); } @Test public void testPrivateKeyMatchesFingerprintString() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); assert privateKeyHasFingerprint(privKey, expectedFingerprint); }
SshKeys { public static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint) { return sha1(privateKey).equals(fingerprint); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }
@Test public void testPrivateKeyMatchesSha1Typed() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); assert privateKeyHasSha1(privateKey, expectedSha1); } @Test public void testPrivateKeyMatchesSha1String() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); assert privateKeyHasSha1(privKey, expectedSha1); }
SshKeys { public static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH) { KeySpec privateKeySpec = privateKeySpec(privateKeyPEM); checkArgument(privateKeySpec instanceof RSAPrivateCrtKeySpec, "incorrect format expected RSAPrivateCrtKeySpec was %s", privateKeySpec); return privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec.class.cast(privateKeySpec), publicKeySpecFromOpenSSH(publicKeyOpenSSH)); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }
@Test public void testPrivateKeyMatchesPublicKeyString() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); String pubKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test.pub")); assert privateKeyMatchesPublicKey(privKey, pubKey); }
SshKeys { public static String encodeAsOpenSSH(RSAPublicKey key) { byte[] keyBlob = keyBlob(key.getPublicExponent(), key.getModulus()); return "ssh-rsa " + base64().encode(keyBlob); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFromOpenSSH(ByteSource supplier); static KeyPair generateRsaKeyPair(KeyPairGenerator generator, SecureRandom rand); static Map<String, String> generate(); static Map<String, String> generate(KeyPairGenerator generator, SecureRandom rand); static String encodeAsOpenSSH(RSAPublicKey key); static boolean privateKeyMatchesPublicKey(String privateKeyPEM, String publicKeyOpenSSH); static boolean privateKeyMatchesPublicKey(RSAPrivateCrtKeySpec privateKey, RSAPublicKeySpec publicKey); static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasFingerprint(String privateKeyPEM, String fingerprint); static String fingerprintPrivateKey(String privateKeyPEM); static String fingerprintPublicKey(String publicKeyOpenSSH); static boolean privateKeyHasSha1(RSAPrivateCrtKeySpec privateKey, String fingerprint); static boolean privateKeyHasSha1(String privateKeyPEM, String sha1HexColonDelimited); static String sha1PrivateKey(String privateKeyPEM); static String sha1(RSAPrivateCrtKeySpec privateKey); static boolean publicKeyHasFingerprint(RSAPublicKeySpec publicKey, String fingerprint); static boolean publicKeyHasFingerprint(String publicKeyOpenSSH, String fingerprint); static String fingerprint(BigInteger publicExponent, BigInteger modulus); }
@Test public void testEncodeAsOpenSSH() throws IOException, InvalidKeySpecException, NoSuchAlgorithmException { String encoded = SshKeys.encodeAsOpenSSH((RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic( SshKeys.publicKeySpecFromOpenSSH(Resources.asByteSource(Resources.getResource(getClass(), "/test.pub"))))); assertEquals(encoded, Strings2.toStringAndClose(getClass().getResourceAsStream("/test.pub")).trim()); }
MacAddresses { public static boolean isMacAddress(String in) { return MAC_ADDR_PATTERN.matcher(in).matches(); } static boolean isMacAddress(String in); }
@Test public void testIsMacAddress() { for (String addr : expectedValidAddresses) assertTrue(isMacAddress(addr)); for (String addr : expectedInvalidAddresses) assertFalse(isMacAddress(addr)); }
DeregisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.DeregisterPayload> { @Override protected String createPayload(LoadBalancer.Request.DeregisterPayload payload) { requestBuilder.append("<ws:deregisterServersOnLoadBalancer>"); for (String s : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", s)); requestBuilder.append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append("</ws:deregisterServersOnLoadBalancer>"); return requestBuilder.toString(); } DeregisterLoadBalancerRequestBinder(); }
@Test public void testDeregisterPayload() { DeregisterLoadBalancerRequestBinder binder = new DeregisterLoadBalancerRequestBinder(); String actual = binder.createPayload(LoadBalancer.Request.createDeregisteringPayload( "load-balancer-id", ImmutableList.of("1", "2"))); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
BackoffOnNotFoundWhenGetBucketACL extends CacheLoader<String, AccessControlList> { @Override public AccessControlList load(String bucketName) { ResourceNotFoundException last = null; for (int currentTries = 0; currentTries < maxTries; currentTries++) { try { return client.getBucketACL(bucketName); } catch (ResourceNotFoundException e) { imposeBackoffExponentialDelay(100L, 200L, 2, currentTries, maxTries); last = e; } } throw last; } @Inject BackoffOnNotFoundWhenGetBucketACL(S3Client client); @Override AccessControlList load(String bucketName); @Override String toString(); }
@Test void testMaxRetriesNotExceededReturnsValue() { AccessControlList acl = createMock(AccessControlList.class); int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts - 1); expect(mock.getBucketACL("foo")).andReturn(acl); replay(mock); assertSame(backoff.load("foo"), acl); verify(mock); } @Test(expectedExceptions = ResourceNotFoundException.class) void testMaxRetriesExceededThrowsException() { int attempts = 5; BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new ResourceNotFoundException()).times(attempts); replay(mock); backoff.load("foo"); } @Test(expectedExceptions = UncheckedExecutionException.class) void testDoesntCatchOtherExceptions() { BackoffOnNotFoundWhenGetBucketACL backoff = new BackoffOnNotFoundWhenGetBucketACL(mock); expect(mock.getBucketACL("foo")).andThrow(new UncheckedExecutionException(new TimeoutException())); replay(mock); backoff.load("foo"); verify(mock); }
CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions overrideMetadataWith(Map<String, String> metadata) { checkNotNull(metadata, "metadata"); this.metadata = metadata; return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testMetaNPE() { overrideMetadataWith(null); }
CopyObjectOptions extends BaseHttpRequestOptions { public String getIfModifiedSince() { return getFirstHeaderOrNull(COPY_SOURCE_IF_MODIFIED_SINCE); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testNullIfModifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfModifiedSince()); }
CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifModifiedSince()"); checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifModifiedSince()"); replaceHeader(COPY_SOURCE_IF_MODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifModifiedSince, "ifModifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testIfModifiedSinceNPE() { ifSourceModifiedSince(null); }
CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifUnmodifiedSince()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifUnmodifiedSince()"); replaceHeader(COPY_SOURCE_IF_UNMODIFIED_SINCE, dateService.rfc822DateFormat(checkNotNull(ifUnmodifiedSince, "ifUnmodifiedSince"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testIfUnmodifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); options.ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test public void testIfUnmodifiedSinceStatic() { CopyObjectOptions options = ifSourceUnmodifiedSince(now); isNowExpected(options); } @Test(expectedExceptions = NullPointerException.class) public void testIfUnmodifiedSinceNPE() { ifSourceUnmodifiedSince(null); }
CreateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.CreatePayload> { @Override protected String createPayload(LoadBalancer.Request.CreatePayload payload) { requestBuilder.append("<ws:createLoadBalancer>") .append("<request>") .append(format("<dataCenterId>%s</dataCenterId>", payload.dataCenterId())) .append(format("<loadBalancerName>%s</loadBalancerName>", payload.name())) .append(format("<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>", payload.algorithm())) .append(format("<ip>%s</ip>", payload.ip())) .append(format("<lanId>%s</lanId>", payload.lanId())); for (String serverId : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", serverId)); requestBuilder .append("</request>") .append("</ws:createLoadBalancer>"); return requestBuilder.toString(); } CreateLoadBalancerRequestBinder(); }
@Test public void testCreatePayload() { CreateLoadBalancerRequestBinder binder = new CreateLoadBalancerRequestBinder(); String actual = binder.createPayload( LoadBalancer.Request.creatingBuilder() .dataCenterId("datacenter-id") .name("load-balancer-name") .algorithm(Algorithm.ROUND_ROBIN) .ip("10.0.0.1") .lanId(2) .serverIds(ImmutableList.<String>of( "server-id-1", "server-id-2")) .build()); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
CopyObjectOptions extends BaseHttpRequestOptions { public String getIfUnmodifiedSince() { return getFirstHeaderOrNull(COPY_SOURCE_IF_UNMODIFIED_SINCE); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testNullIfUnmodifiedSince() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfUnmodifiedSince()); }
CopyObjectOptions extends BaseHttpRequestOptions { public String getIfMatch() { return getFirstHeaderOrNull(COPY_SOURCE_IF_MATCH); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testNullIfETagMatches() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfMatch()); }
CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceETagMatches(String eTag) { checkState(getIfNoneMatch() == null, "ifETagDoesntMatch() is not compatible with ifETagMatches()"); checkState(getIfModifiedSince() == null, "ifModifiedSince() is not compatible with ifETagMatches()"); replaceHeader(COPY_SOURCE_IF_MATCH, maybeQuoteETag(checkNotNull(eTag, "eTag"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagMatchesNPE() { ifSourceETagMatches(null); }
CopyObjectOptions extends BaseHttpRequestOptions { public String getIfNoneMatch() { return getFirstHeaderOrNull(COPY_SOURCE_IF_NO_MATCH); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testNullIfETagDoesntMatch() { CopyObjectOptions options = new CopyObjectOptions(); assertNull(options.getIfNoneMatch()); }
CopyObjectOptions extends BaseHttpRequestOptions { public CopyObjectOptions ifSourceETagDoesntMatch(String eTag) { checkState(getIfMatch() == null, "ifETagMatches() is not compatible with ifETagDoesntMatch()"); Preconditions.checkState(getIfUnmodifiedSince() == null, "ifUnmodifiedSince() is not compatible with ifETagDoesntMatch()"); replaceHeader(COPY_SOURCE_IF_NO_MATCH, maybeQuoteETag(checkNotNull(eTag, "ifETagDoesntMatch"))); return this; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test(expectedExceptions = NullPointerException.class) public void testIfETagDoesntMatchNPE() { ifSourceETagDoesntMatch(null); }
CopyObjectOptions extends BaseHttpRequestOptions { @Override public Multimap<String, String> buildRequestHeaders() { checkState(headerTag != null, "headerTag should have been injected!"); checkState(metadataPrefix != null, "metadataPrefix should have been injected!"); ImmutableMultimap.Builder<String, String> returnVal = ImmutableMultimap.builder(); for (Entry<String, String> entry : headers.entries()) { returnVal.put(entry.getKey().replace(DEFAULT_AMAZON_HEADERTAG, headerTag), entry.getValue()); } boolean replace = false; if (cacheControl != null) { returnVal.put(HttpHeaders.CACHE_CONTROL, cacheControl); replace = true; } if (contentDisposition != null) { returnVal.put(HttpHeaders.CONTENT_DISPOSITION, contentDisposition); replace = true; } if (contentEncoding != null) { returnVal.put(HttpHeaders.CONTENT_ENCODING, contentEncoding); replace = true; } if (contentLanguage != null) { returnVal.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); replace = true; } if (contentType != null) { returnVal.put(HttpHeaders.CONTENT_TYPE, contentType); replace = true; } if (metadata != null) { for (Map.Entry<String, String> entry : metadata.entrySet()) { String key = entry.getKey(); returnVal.put(key.startsWith(metadataPrefix) ? key : metadataPrefix + key, entry.getValue()); } replace = true; } if (replace) { returnVal.put(METADATA_DIRECTIVE.replace(DEFAULT_AMAZON_HEADERTAG, headerTag), "REPLACE"); } return returnVal.build(); } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test void testBuildRequestHeaders() { CopyObjectOptions options = ifSourceModifiedSince(now).ifSourceETagDoesntMatch(etag).overrideMetadataWith( goodMeta); options.setHeaderTag(DEFAULT_AMAZON_HEADERTAG); options.setMetadataPrefix(USER_METADATA_PREFIX); Multimap<String, String> headers = options.buildRequestHeaders(); assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_MODIFIED_SINCE)), new SimpleDateFormatDateService() .rfc822DateFormat(now)); assertEquals(getOnlyElement(headers.get(COPY_SOURCE_IF_NO_MATCH)), "\"" + etag + "\""); for (String value : goodMeta.values()) assertTrue(headers.containsValue(value)); }
CopyObjectOptions extends BaseHttpRequestOptions { public CannedAccessPolicy getAcl() { return acl; } @Inject void setMetadataPrefix(@Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix); @Inject void setHeaderTag(@Named(PROPERTY_HEADER_TAG) String headerTag); CopyObjectOptions overrideAcl(CannedAccessPolicy acl); CannedAccessPolicy getAcl(); String getIfModifiedSince(); String getIfUnmodifiedSince(); String getIfMatch(); String getIfNoneMatch(); Map<String, String> getMetadata(); CopyObjectOptions ifSourceModifiedSince(Date ifModifiedSince); CopyObjectOptions ifSourceUnmodifiedSince(Date ifUnmodifiedSince); CopyObjectOptions ifSourceETagMatches(String eTag); CopyObjectOptions ifSourceETagDoesntMatch(String eTag); @Override Multimap<String, String> buildRequestHeaders(); CopyObjectOptions cacheControl(String cacheControl); CopyObjectOptions contentDisposition(String contentDisposition); CopyObjectOptions contentEncoding(String contentEncoding); CopyObjectOptions contentLanguage(String contentLanguage); CopyObjectOptions contentType(String contentType); CopyObjectOptions overrideMetadataWith(Map<String, String> metadata); static final CopyObjectOptions NONE; }
@Test public void testAclDefault() { CopyObjectOptions options = new CopyObjectOptions(); assertEquals(options.getAcl(), CannedAccessPolicy.PRIVATE); }
UpdateLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.UpdatePayload> { @Override protected String createPayload(LoadBalancer.Request.UpdatePayload payload) { return requestBuilder.append("<ws:updateLoadBalancer>") .append("<request>") .append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())) .append(formatIfNotEmpty("<loadBalancerName>%s</loadBalancerName>", payload.name())) .append(formatIfNotEmpty("<loadBalancerAlgorithm>%s</loadBalancerAlgorithm>", payload.algorithm())) .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append("</request>") .append("</ws:updateLoadBalancer>").toString(); } UpdateLoadBalancerRequestBinder(); }
@Test public void testDeregisterPayload() { UpdateLoadBalancerRequestBinder binder = new UpdateLoadBalancerRequestBinder(); LoadBalancer.Request.UpdatePayload payload = LoadBalancer.Request.updatingBuilder() .id("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee") .name("load-balancer-name") .algorithm(LoadBalancer.Algorithm.ROUND_ROBIN) .ip("10.0.0.2") .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
RegisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.RegisterPayload> { @Override protected String createPayload(LoadBalancer.Request.RegisterPayload payload) { requestBuilder .append("<ws:registerServersOnLoadBalancer>") .append(format("<loadBalancerId>%s</loadBalancerId>", payload.id())); for (String s : payload.serverIds()) requestBuilder.append(format("<serverIds>%s</serverIds>", s)); requestBuilder.append("</ws:registerServersOnLoadBalancer>"); return requestBuilder.toString().replaceAll("\\s+", ""); } RegisterLoadBalancerRequestBinder(); }
@Test public void testRegisterPayload() { RegisterLoadBalancerRequestBinder binder = new RegisterLoadBalancerRequestBinder(); String actual = binder.createPayload(LoadBalancer.Request.createRegisteringPaylod( "load-balancer-id", ImmutableList.of("1", "2"))); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
BindS3ObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof S3Object, "this binder is only valid for S3Object!, not %s", input); checkNotNull(request, "request"); S3Object s3Object = S3Object.class.cast(input); checkArgument(s3Object.getMetadata().getKey() != null, "s3Object.getMetadata().getKey() must be set!"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() != null, "contentLength must be set, streaming not supported"); checkArgument(s3Object.getPayload().getContentMetadata().getContentLength() <= 5L * 1024 * 1024 * 1024, "maximum size for put object is 5GB"); StorageClass storageClass = s3Object.getMetadata().getStorageClass(); if (storageClass != StorageClass.STANDARD) { request = (R) request.toBuilder() .replaceHeader("x-amz-storage-class", storageClass.toString()) .build(); } request = metadataPrefixer.bindToRequest(request, s3Object.getMetadata().getUserMetadata()); return request; } @Inject BindS3ObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }
@Test public void testPassWithMinimumDetailsAndPayload5GB() { S3Object object = injector.getInstance(S3Object.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(5368709120L); object.setPayload(payload); object.getMetadata().setKey("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, object), HttpRequest.builder().method("PUT").endpoint( URI.create("http: } @Test public void testExtendedPropertiesBind() { S3Object object = injector.getInstance(S3Object.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(5368709120L); object.setPayload(payload); object.getMetadata().setKey("foo"); object.getMetadata().setUserMetadata(ImmutableMap.of("foo", "bar")); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, object), HttpRequest.builder().method("PUT").endpoint( URI.create("http: ImmutableMultimap.of("x-amz-meta-foo", "bar")).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNoContentLengthIsBad() { S3Object object = injector.getInstance(S3Object.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(null); object.setPayload(payload); object.getMetadata().setKey("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); binder.bindToRequest(request, object); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNoKeyIsBad() { S3Object object = injector.getInstance(S3Object.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(5368709120000L); object.setPayload(payload); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); binder.bindToRequest(request, object); } @Test(expectedExceptions = IllegalArgumentException.class) public void testOver5GBIsBad() { S3Object object = injector.getInstance(S3Object.Factory.class).create(null); Payload payload = Payloads.newStringPayload(""); payload.getContentMetadata().setContentLength(5368709120000L); object.setPayload(payload); object.getMetadata().setKey("foo"); HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: BindS3ObjectMetadataToRequest binder = injector.getInstance(BindS3ObjectMetadataToRequest.class); binder.bindToRequest(request, object); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeS3Object() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindS3ObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
AddRomDriveToServerRequestBinder extends BaseProfitBricksRequestBinder<Drive.Request.AddRomDriveToServerPayload> { @Override protected String createPayload(Drive.Request.AddRomDriveToServerPayload payload) { requestBuilder.append("<ws:addRomDriveToServer>") .append("<request>") .append(format("<imageId>%s</imageId>", payload.imageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:addRomDriveToServer>"); return requestBuilder.toString(); } AddRomDriveToServerRequestBinder(); }
@Test public void testAddRomDriveToServerPayload() { AddRomDriveToServerRequestBinder binder = new AddRomDriveToServerRequestBinder(); Drive.Request.AddRomDriveToServerPayload payload = Drive.Request.AddRomDriveToServerPayload.builder() .serverId("server-id") .imageId("image-id") .deviceNumber("device-number") .build(); String actual = binder.createPayload(payload); assertEquals(actual, expectedPayload); }
BindIterableAsPayloadToDeleteRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input is null") instanceof Iterable, "this binder is only valid for an Iterable"); checkNotNull(request, "request is null"); Iterable<String> keys = (Iterable<String>) input; checkArgument(!Iterables.isEmpty(keys), "The list of keys should not be empty."); String content; try { XMLBuilder rootBuilder = XMLBuilder.create("Delete"); for (String key : keys) { XMLBuilder ownerBuilder = rootBuilder.elem("Object"); XMLBuilder keyBuilder = ownerBuilder.elem("Key").text(key); } Properties outputProperties = new Properties(); outputProperties.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); content = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + rootBuilder.asString(outputProperties); } catch (ParserConfigurationException pce) { throw Throwables.propagate(pce); } catch (TransformerException te) { throw Throwables.propagate(te); } Payload payload = Payloads.newStringPayload(content); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); byte[] md5 = md5().hashString(content, UTF_8).asBytes(); payload.getContentMetadata().setContentMD5(md5); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }
@Test public void testWithASmallSet() { HttpRequest result = binder.bindToRequest(request, ImmutableSet.of("key1", "key2")); Payload payload = Payloads .newStringPayload("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Delete>" + "<Object><Key>key1</Key></Object><Object><Key>key2</Key></Object></Delete>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); assertEquals(result.getPayload(), payload); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptySetThrowsException() { binder.bindToRequest(request, ImmutableSet.of()); } @Test(expectedExceptions = NullPointerException.class) public void testFailsOnNullSet() { binder.bindToRequest(request, null); } @Test(expectedExceptions = IllegalArgumentException.class) public void testExpectedASetInstance() { binder.bindToRequest(request, ImmutableList.of()); }
BindObjectMetadataToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof ObjectMetadata, "this binder is only valid for ObjectMetadata!"); checkNotNull(request, "request"); ObjectMetadata md = ObjectMetadata.class.cast(input); checkArgument(md.getKey() != null, "objectMetadata.getKey() must be set!"); request = metadataPrefixer.bindToRequest(request, md.getUserMetadata()); Builder<String, String> headers = ImmutableMultimap.builder(); if (md.getContentMetadata().getCacheControl() != null) { headers.put(HttpHeaders.CACHE_CONTROL, md.getContentMetadata().getCacheControl()); } if (md.getContentMetadata().getContentDisposition() != null) { headers.put("Content-Disposition", md.getContentMetadata().getContentDisposition()); } if (md.getContentMetadata().getContentEncoding() != null) { headers.put("Content-Encoding", md.getContentMetadata().getContentEncoding()); } String contentLanguage = md.getContentMetadata().getContentLanguage(); if (contentLanguage != null) { headers.put(HttpHeaders.CONTENT_LANGUAGE, contentLanguage); } if (md.getContentMetadata().getContentType() != null) { headers.put(HttpHeaders.CONTENT_TYPE, md.getContentMetadata().getContentType()); } else { headers.put(HttpHeaders.CONTENT_TYPE, "binary/octet-stream"); } if (md.getContentMetadata().getContentMD5() != null) { headers.put("Content-MD5", base64().encode(md.getContentMetadata().getContentMD5())); } ObjectMetadata.StorageClass storageClass = md.getStorageClass(); if (storageClass != ObjectMetadata.StorageClass.STANDARD) { headers.put("x-amz-storage-class", storageClass.toString()); } return (R) request.toBuilder().replaceHeaders(headers.build()).build(); } @Inject BindObjectMetadataToRequest(BindMapToHeadersWithPrefix metadataPrefixer); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }
@Test public void testPassWithMinimumDetailsAndPayload5GB() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST") .endpoint("http: } @Test public void testExtendedPropertiesBind() { ObjectMetadata md = ObjectMetadataBuilder.create().key("foo").cacheControl("no-cache").userMetadata( ImmutableMap.of("foo", "bar")).build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); assertEquals(binder.bindToRequest(request, md), HttpRequest.builder().method("POST").endpoint("http: ImmutableMultimap.of("Cache-Control", "no-cache", "x-amz-meta-foo", "bar", "Content-Type", "binary/octet-stream")).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testNoKeyIsBad() { ObjectMetadata md = ObjectMetadataBuilder.create().build(); HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: BindObjectMetadataToRequest binder = injector.getInstance(BindObjectMetadataToRequest.class); binder.bindToRequest(request, md); } @Test(expectedExceptions = IllegalArgumentException.class) public void testMustBeObjectMetadata() { HttpRequest request = HttpRequest.builder().method("POST").endpoint("http: injector.getInstance(BindObjectMetadataToRequest.class).bindToRequest(request, new File("foo")); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
ConnectStorageToServerRequestBinder extends BaseProfitBricksRequestBinder<Storage.Request.ConnectPayload> { @Override protected String createPayload(Storage.Request.ConnectPayload payload) { requestBuilder.append("<ws:connectStorageToServer>") .append("<request>") .append(format("<storageId>%s</storageId>", payload.storageId())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(formatIfNotEmpty("<busType>%s</busType>", payload.busType())) .append(formatIfNotEmpty("<deviceNumber>%s</deviceNumber>", payload.deviceNumber())) .append("</request>") .append("</ws:connectStorageToServer>"); return requestBuilder.toString(); } ConnectStorageToServerRequestBinder(); }
@Test public void testCreatePayload() { ConnectStorageToServerRequestBinder binder = new ConnectStorageToServerRequestBinder(); Storage.Request.ConnectPayload payload = Storage.Request.connectingBuilder() .serverId("qwertyui-qwer-qwer-qwer-qwertyyuiiop") .storageId("qswdefrg-qaws-qaws-defe-rgrgdsvcxbrh") .busType(Storage.BusType.VIRTIO) .deviceNumber(2) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
BindAsHostPrefixIfConfigured implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object payload) { String payloadAsString = payload.toString(); if (isVhostStyle && payloadAsString.equals(payloadAsString.toLowerCase())) { request = bindAsHostPrefix.bindToRequest(request, payload); String host = request.getEndpoint().getHost(); if (request.getEndpoint().getPort() != -1) { host += ":" + request.getEndpoint().getPort(); } return (R) request.toBuilder().replaceHeader(HttpHeaders.HOST, host).build(); } else { StringBuilder path = new StringBuilder(request.getEndpoint().getRawPath()); if (servicePath.equals("/")) { if (path.toString().equals("/")) path.append(payloadAsString); else path.insert(0, "/" + payloadAsString); } else { int indexToInsert = 0; indexToInsert = path.indexOf(servicePath); indexToInsert = indexToInsert == -1 ? 0 : indexToInsert; indexToInsert += servicePath.length(); path.insert(indexToInsert, "/" + payloadAsString); } return (R) request.toBuilder().replacePath(path.toString()).build(); } } @Inject BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix, @Named(PROPERTY_S3_VIRTUAL_HOST_BUCKETS) boolean isVhostStyle, @Named(PROPERTY_S3_SERVICE_PATH) String servicePath); @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object payload); }
@Test(dataProvider = "objects") public void testObject(String key) throws InterruptedException { HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: BindAsHostPrefixIfConfigured binder = injector.getInstance(BindAsHostPrefixIfConfigured.class); request = binder.bindToRequest(request, "bucket"); assertEquals(request.getRequestLine(), "GET http: }
BindPartIdsAndETagsToRequest implements Binder { @SuppressWarnings("unchecked") @Override public <R extends HttpRequest> R bindToRequest(R request, Object input) { checkArgument(checkNotNull(input, "input") instanceof Map, "this binder is only valid for Map!"); checkNotNull(request, "request"); Map<Integer, String> map = (Map<Integer, String>) input; checkArgument(!map.isEmpty(), "Please send parts"); StringBuilder content = new StringBuilder(); content.append("<CompleteMultipartUpload>"); for (Entry<Integer, String> entry : map.entrySet()) { content.append("<Part>"); content.append("<PartNumber>").append(entry.getKey()).append("</PartNumber>"); content.append("<ETag>").append(entry.getValue()).append("</ETag>"); content.append("</Part>"); } content.append("</CompleteMultipartUpload>"); Payload payload = Payloads.newStringPayload(content.toString()); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request.setPayload(payload); return request; } @SuppressWarnings("unchecked") @Override R bindToRequest(R request, Object input); }
@Test public void testPassWithMinimumDetailsAndPayload5GB() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: Payload payload = Payloads .newStringPayload("<CompleteMultipartUpload><Part><PartNumber>1</PartNumber><ETag>\"a54357aff0632cce46d942af68356b38\"</ETag></Part></CompleteMultipartUpload>"); payload.getContentMetadata().setContentType(MediaType.TEXT_XML); request = binder.bindToRequest(request, ImmutableMap.<Integer, String> of(1, "\"a54357aff0632cce46d942af68356b38\"")); assertEquals(request.getPayload().getRawContent(), payload.getRawContent()); assertEquals(request, HttpRequest.builder().method("PUT").endpoint("http: payload).build()); } @Test(expectedExceptions = IllegalArgumentException.class) public void testEmptyIsBad() { HttpRequest request = HttpRequest.builder().method("PUT").endpoint("http: binder.bindToRequest(request, ImmutableMap.<Integer, String> of()); } @Test(expectedExceptions = { NullPointerException.class, IllegalStateException.class }) public void testNullIsBad() { BindMapToHeadersWithPrefix binder = new BindMapToHeadersWithPrefix("prefix:"); HttpRequest request = HttpRequest.builder().method("GET").endpoint("http: binder.bindToRequest(request, null); }
FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>, InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(checkNotNull(t, "throwable"), AWSResponseException.class); if (exception != null && exception.getError() != null && exception.getError().getCode() != null) { String code = exception.getError().getCode(); if (code.equals("BucketAlreadyOwnedByYou")) return false; else if (code.equals("OperationAborted") && bucket != null && client.bucketExists(bucket)) return false; } throw propagate(t); } @Inject FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(S3Client client); @Override Boolean createOrPropagate(Throwable t); @Override FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists setContext(@Nullable HttpRequest request); }
@Test(expectedExceptions = IllegalStateException.class) void testIllegalStateIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = new IllegalStateException(); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); } @Test(expectedExceptions = AWSResponseException.class) void testBlahIsNotOk() throws Exception { S3Client client = createMock(S3Client.class); replay(client); Exception e = getErrorWithCode("blah"); new FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists(client).createOrPropagate(e); }
ETagFromHttpResponseViaRegex implements Function<HttpResponse, String> { @Override public String apply(HttpResponse response) { String value = null; String content = returnStringIf200.apply(response); if (content != null) { Matcher matcher = PATTERN.matcher(content); if (matcher.find()) { value = matcher.group(1); if (value.indexOf(ESCAPED_QUOTE) != -1) { value = value.replace(ESCAPED_QUOTE, "\""); } } } return value; } @Inject ETagFromHttpResponseViaRegex(ReturnStringIf2xx returnStringIf200); @Override String apply(HttpResponse response); }
@Test public void test() { HttpResponse response = HttpResponse.builder().statusCode(200).payload( Payloads.newInputStreamPayload(getClass().getResourceAsStream("/complete-multipart-upload.xml"))) .build(); ETagFromHttpResponseViaRegex parser = new ETagFromHttpResponseViaRegex(new ReturnStringIf2xx()); assertEquals(parser.apply(response), "\"3858f62230ac3c915f300c664312c11f-9\""); }
CreateNicRequestBinder extends BaseProfitBricksRequestBinder<Nic.Request.CreatePayload> { @Override protected String createPayload(Nic.Request.CreatePayload payload) { requestBuilder.append("<ws:createNic>") .append("<request>") .append(formatIfNotEmpty("<ip>%s</ip>", payload.ip())) .append(formatIfNotEmpty("<nicName>%s</nicName>", payload.name())) .append(formatIfNotEmpty("<dhcpActive>%s</dhcpActive>", payload.dhcpActive())) .append(format("<serverId>%s</serverId>", payload.serverId())) .append(format("<lanId>%s</lanId>", payload.lanId())) .append("</request>") .append("</ws:createNic>"); return requestBuilder.toString(); } CreateNicRequestBinder(); }
@Test public void testCreatePayload() { CreateNicRequestBinder binder = new CreateNicRequestBinder(); Nic.Request.CreatePayload payload = Nic.Request.creatingBuilder() .ip("192.168.0.1") .name("nic-name") .dhcpActive(true) .serverId("server-id") .lanId(1) .build(); String actual = binder.createPayload(payload); assertNotNull(actual, "Binder returned null payload"); assertEquals(actual, expectedPayload); }
DefaultEndpointThenInvalidateRegion implements Function<Object, URI> { @Override public URI apply(@Nullable Object from) { try { return delegate.apply(from); } finally { bucketToRegionCache.invalidate(from.toString()); } } @Inject DefaultEndpointThenInvalidateRegion(AssignCorrectHostnameForBucket delegate, @Bucket LoadingCache<String, Optional<String>> bucketToRegionCache); @Override URI apply(@Nullable Object from); }
@SuppressWarnings("unchecked") @Test public void testInvalidate() throws Exception { LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class); bucketToRegionCache.invalidate("mybucket"); replay(bucketToRegionCache); AssignCorrectHostnameForBucket delegate = new AssignCorrectHostnameForBucket(REGION_TO_ENDPOINT, Functions.forMap(ImmutableMap.of("mybucket", Optional.of("us-west-1")))); new DefaultEndpointThenInvalidateRegion(delegate, bucketToRegionCache).apply("mybucket"); verify(bucketToRegionCache); }