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 = logg...
@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()...
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...
@Test(expectedExceptions = RuntimeException.class) public void testArbitraryExceptionDoesntConvert() throws Exception { fn.createOrPropagate(new RuntimeException()); } @Test(expectedExceptions = RetryAfterException.class, expectedExceptionsMessageRegExp = "retry now") public void testHttpResponseExceptionWithRetryAfter...
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.g...
@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 test403ToAuthorizatio...
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...
@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.getI...
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.apiMeta...
@Test public void testProviderMetadataWithUpdatedEndpointUpdatesAndRetainsAllDefaultPropertiesExceptEndpoint() { ProviderMetadata md = forApiOnEndpoint(IntegrationTestClient.class, "http: Properties props = new Properties(); props.putAll(md.getDefaultProperties()); props.setProperty(Constants.PROPERTY_ENDPOINT, "http: ...
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(ViewTo...
@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.getExistingBind...
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)...
@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 PagedIterabl...
@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...
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) ExecutorServ...
@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...
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); Ma...
@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...
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 provi...
@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>>ofIn...
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, Locatio...
@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 regionToProviderOrJ...
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 : re...
@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"...
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 rfc82...
@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, w...
@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()...
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)) ret...
@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 testWhenFindsRe...
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 lo...
@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 testMustHaveEndpo...
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 rfc82...
@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 Str...
@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}"...
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(); StringBuf...
@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("unexistin...
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 in...
@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) p...
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 ? ...
@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...
@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<?> typ...
@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, api...
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, ProviderMetada...
@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("/...
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...
@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/servic...
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, typ...
@SuppressWarnings("rawtypes") @Test public void testInstantiateAvailableClassesWhenAllAssignable() throws ClassNotFoundException { Bundle bundle = createMock(Bundle.class); expect((Class) bundle.loadClass("org.jclouds.providers.JcloudsTestBlobStoreProviderMetadata")).andReturn( JcloudsTestBlobStoreProviderMetadata.clas...
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>...
@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(expecte...
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, ...
@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); fina...
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(); S...
@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()).a...
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.start...
@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, ...
@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.registerIm...
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, AtomicRefe...
@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(...
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(...
@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 I...
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 sessionInt...
@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...
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 ...
@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, MI...
ConcurrentOpenSocketFinder implements OpenSocketFinder { @VisibleForTesting static FluentIterable<String> checkNodeHasIps(NodeMetadata node, AllowedInterfaces allowedInterfaces) { ImmutableSet.Builder<String> ipsBuilder = ImmutableSet.builder(); if (allowedInterfaces.scanPublic) { ipsBuilder.addAll(node.getPublicAddres...
@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() thro...
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(ComputeMetadataIncluding...
@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(...
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();...
@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", ""))...
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(...
@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_ta...
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 (osVersio...
@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...
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...
@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( ComputeServiceU...
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 ...
@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( ComputeServic...
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, Inte...
@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)...
@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('=') .spl...
@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") pu...
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...
@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:cor...
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...
@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.instal...
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...
@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 co...
@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.aut...
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()...
@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 hashCo...
@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.toS...
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 TemplateOp...
@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...
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(); State...
@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(); Stat...
@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 equal...
@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); @Overri...
@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 in...
@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 (shad...
@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()); }...
@Test public void testPublicKeyDoesNotGenerateAuthorizePublicKeyStatementIfOnlyPublicKeyOptionsConfigured() { Map<String, String> keys = SshKeys.generate(); TemplateOptions options = TemplateOptions.Builder.authorizePublicKey(keys.get("public")); NodeAndTemplateOptionsToStatementWithoutPublicKey function = new NodeAndT...
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 stop...
@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("i...
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.cla...
@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.getDefa...
@Test public void createImageRegistersInCacheAndAddsCredentials() { ImageCacheSupplier imageCache = createMock(ImageCacheSupplier.class); ImageExtension delegate = createMock(ImageExtension.class); AddDefaultCredentialsToImage credsToImage = createMock(AddDefaultCredentialsToImage.class); ImageTemplate template = new I...
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, A...
@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); ne...
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 ...
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(); checkArgum...
@Test public void testReturnTrueWhenISpecifyARegionAndInputLocationIsProvider() { NullEqualToIsParentOrIsGrandparentOfCurrentLocation predicate = new NullEqualToIsParentOrIsGrandparentOfCurrentLocation(Suppliers.ofInstance(region)); Hardware md = new HardwareBuilder().id("foo").location(provider).build(); assertTrue(pr...
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 = optionsProvid...
@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>...
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 publicKeySpecFromOpenSS...
@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.g...
SshKeys { public static boolean privateKeyHasFingerprint(RSAPrivateCrtKeySpec privateKey, String fingerprint) { return fingerprint(privateKey.getPublicExponent(), privateKey.getModulus()).equals(fingerprint); } static RSAPublicKeySpec publicKeySpecFromOpenSSH(String idRsaPub); static RSAPublicKeySpec publicKeySpecFrom...
@Test public void testPrivateKeyMatchesFingerprintTyped() throws IOException { String privKey = Strings2.toStringAndClose(getClass().getResourceAsStream("/test")); RSAPrivateCrtKeySpec privateKey = (RSAPrivateCrtKeySpec) Pems.privateKeySpec(privKey); assert privateKeyHasFingerprint(privateKey, 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 generateRsaKey...
@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 test...
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 privateKeyMat...
@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...
@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")))))...
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()) requestBuilde...
@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"...
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 (ResourceNotF...
@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); exp...
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 setHead...
@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); Cop...
@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()...
@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 ifUnmod...
@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 ...
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>", paylo...
@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) .ser...
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);...
@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 ov...
@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()"); replace...
@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); CopyObjectOpt...
@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 ifETagDo...
@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...
@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(); ...
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 ac...
@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</loadBalancer...
@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_...
RegisterLoadBalancerRequestBinder extends BaseProfitBricksRequestBinder<LoadBalancer.Request.RegisterPayload> { @Override protected String createPayload(LoadBalancer.Request.RegisterPayload payload) { requestBuilder .append("<ws:registerServersOnLoadBalancer>") .append(format("<loadBalancerId>%s</loadBalancerId>", payl...
@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"); assert...
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")...
@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"); HttpRequ...
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>", p...
@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()...
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...
@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.getCont...
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"); Obj...
@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(binde...
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.sto...
@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(Stora...
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.bindT...
@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"); as...
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...
@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...
FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists implements Fallback<Boolean>, InvocationContext<FalseIfBucketAlreadyOwnedByYouOrOperationAbortedWhenBucketExists> { @Override public Boolean createOrPropagate(Throwable t) throws Exception { AWSResponseException exception = getFirstThrowableOfType(c...
@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(ex...
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 (...
@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(par...
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>%...
@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); assertN...
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, @B...
@SuppressWarnings("unchecked") @Test public void testInvalidate() throws Exception { LoadingCache<String, Optional<String>> bucketToRegionCache = createMock(LoadingCache.class); bucketToRegionCache.invalidate("mybucket"); replay(bucketToRegionCache); AssignCorrectHostnameForBucket delegate = new AssignCorrectHostnameFo...