Issue 315: added auto-deserialization of json into java objects and new @Unwrap annotation; Issue 311: fixed template parsing for new cluster instance in ec2; Issue 191: started adding node support to chef

This commit is contained in:
Adrian Cole 2010-07-17 01:30:37 -05:00
parent 328679799b
commit 1d0949dec5
171 changed files with 4944 additions and 6998 deletions

View File

@ -70,17 +70,15 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
private BlobToObject blobToObject; private BlobToObject blobToObject;
public void testListDirectories() throws SecurityException, NoSuchMethodException, IOException { public void testListDirectories() throws SecurityException, NoSuchMethodException, IOException {
Method method = AtmosStorageAsyncClient.class.getMethod("listDirectories", Array.newInstance( Method method = AtmosStorageAsyncClient.class.getMethod("listDirectories", Array
ListOptions.class, 0).getClass()); .newInstance(ListOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://accesspoint.atmosonline.com/rest/namespace HTTP/1.1");
"GET https://accesspoint.atmosonline.com/rest/namespace HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);
ParseDirectoryListFromContentAndHeaders.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -88,59 +86,47 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
} }
public void testListDirectory() throws SecurityException, NoSuchMethodException, IOException { public void testListDirectory() throws SecurityException, NoSuchMethodException, IOException {
Method method = AtmosStorageAsyncClient.class.getMethod("listDirectory", String.class, Array Method method = AtmosStorageAsyncClient.class.getMethod("listDirectory", String.class, Array.newInstance(
.newInstance(ListOptions.class, 0).getClass()); ListOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "directory"); HttpRequest request = processor.createRequest(method, "directory");
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1");
"GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);
ParseDirectoryListFromContentAndHeaders.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ThrowContainerNotFoundOn404.class); assertExceptionParserClassEquals(method, ThrowContainerNotFoundOn404.class);
checkFilters(request); checkFilters(request);
} }
public void testListDirectoriesOptions() throws SecurityException, NoSuchMethodException, public void testListDirectoriesOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AtmosStorageAsyncClient.class.getMethod("listDirectories", Array
Method method = AtmosStorageAsyncClient.class.getMethod("listDirectories", Array.newInstance( .newInstance(ListOptions.class, 0).getClass());
ListOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, new ListOptions().limit(1).token("asda"));
HttpRequest request = processor.createRequest(method, new ListOptions().limit(1)
.token("asda"));
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://accesspoint.atmosonline.com/rest/namespace HTTP/1.1");
"GET https://accesspoint.atmosonline.com/rest/namespace HTTP/1.1"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\nx-emc-limit: 1\nx-emc-token: asda\n");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT
+ ": text/xml\nx-emc-limit: 1\nx-emc-token: asda\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);
ParseDirectoryListFromContentAndHeaders.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(request); checkFilters(request);
} }
public void testListDirectoryOptions() throws SecurityException, NoSuchMethodException, public void testListDirectoryOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AtmosStorageAsyncClient.class.getMethod("listDirectory", String.class, Array.newInstance(
Method method = AtmosStorageAsyncClient.class.getMethod("listDirectory", String.class, Array ListOptions.class, 0).getClass());
.newInstance(ListOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "directory", new ListOptions().limit(1).token("asda"));
HttpRequest request = processor.createRequest(method, "directory", new ListOptions().limit(1)
.token("asda"));
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1");
"GET https://accesspoint.atmosonline.com/rest/namespace/directory/ HTTP/1.1"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": text/xml\nx-emc-limit: 1\nx-emc-token: asda\n");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT
+ ": text/xml\nx-emc-limit: 1\nx-emc-token: asda\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, assertResponseParserClassEquals(method, request, ParseDirectoryListFromContentAndHeaders.class);
ParseDirectoryListFromContentAndHeaders.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ThrowContainerNotFoundOn404.class); assertExceptionParserClassEquals(method, ThrowContainerNotFoundOn404.class);
@ -151,8 +137,7 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
Method method = AtmosStorageAsyncClient.class.getMethod("createDirectory", String.class); Method method = AtmosStorageAsyncClient.class.getMethod("createDirectory", String.class);
HttpRequest request = processor.createRequest(method, "dir"); HttpRequest request = processor.createRequest(method, "dir");
assertRequestLineEquals(request, assertRequestLineEquals(request, "POST https://accesspoint.atmosonline.com/rest/namespace/dir/ HTTP/1.1");
"POST https://accesspoint.atmosonline.com/rest/namespace/dir/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -164,15 +149,12 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
} }
public void testCreateFile() throws SecurityException, NoSuchMethodException, IOException { public void testCreateFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = AtmosStorageAsyncClient.class.getMethod("createFile", String.class, Method method = AtmosStorageAsyncClient.class.getMethod("createFile", String.class, AtmosObject.class);
AtmosObject.class);
HttpRequest request = processor.createRequest(method, "dir", blobToObject HttpRequest request = processor.createRequest(method, "dir", blobToObject
.apply(BindBlobToMultipartFormTest.TEST_BLOB)); .apply(BindBlobToMultipartFormTest.TEST_BLOB));
assertRequestLineEquals(request, assertRequestLineEquals(request, "POST https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1");
"POST https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT
+ ": */*\n");
assertPayloadEquals(request, "hello", "text/plain", false); assertPayloadEquals(request, "hello", "text/plain", false);
assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class); assertResponseParserClassEquals(method, request, ParseURIFromListOrLocationHeaderIf20x.class);
@ -183,15 +165,12 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
} }
public void testUpdateFile() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = AtmosStorageAsyncClient.class.getMethod("updateFile", String.class, Method method = AtmosStorageAsyncClient.class.getMethod("updateFile", String.class, AtmosObject.class);
AtmosObject.class);
HttpRequest request = processor.createRequest(method, "dir", blobToObject HttpRequest request = processor.createRequest(method, "dir", blobToObject
.apply(BindBlobToMultipartFormTest.TEST_BLOB)); .apply(BindBlobToMultipartFormTest.TEST_BLOB));
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1");
"PUT https://accesspoint.atmosonline.com/rest/namespace/dir/hello HTTP/1.1"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT
+ ": */*\n");
assertPayloadEquals(request, "hello", "text/plain", false); assertPayloadEquals(request, "hello", "text/plain", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -202,12 +181,11 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
} }
public void testReadFile() throws SecurityException, NoSuchMethodException, IOException { public void testReadFile() throws SecurityException, NoSuchMethodException, IOException {
Method method = AtmosStorageAsyncClient.class.getMethod("readFile", String.class, Array Method method = AtmosStorageAsyncClient.class.getMethod("readFile", String.class, Array.newInstance(
.newInstance(GetOptions.class, 0).getClass()); GetOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "dir/file"); HttpRequest request = processor.createRequest(method, "dir/file");
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
"GET https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -222,8 +200,7 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
Method method = AtmosStorageAsyncClient.class.getMethod("getSystemMetadata", String.class); Method method = AtmosStorageAsyncClient.class.getMethod("getSystemMetadata", String.class);
HttpRequest request = processor.createRequest(method, "dir/file"); HttpRequest request = processor.createRequest(method, "dir/file");
assertRequestLineEquals(request, assertRequestLineEquals(request, "HEAD https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
"HEAD https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -238,8 +215,7 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
Method method = AtmosStorageAsyncClient.class.getMethod("deletePath", String.class); Method method = AtmosStorageAsyncClient.class.getMethod("deletePath", String.class);
HttpRequest request = processor.createRequest(method, "dir/file"); HttpRequest request = processor.createRequest(method, "dir/file");
assertRequestLineEquals(request, assertRequestLineEquals(request, "DELETE https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
"DELETE https://accesspoint.atmosonline.com/rest/namespace/dir/file HTTP/1.1");
assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n"); assertNonPayloadHeadersEqual(request, HttpHeaders.ACCEPT + ": */*\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -295,8 +271,7 @@ public class AtmosStorageAsyncClientTest extends RestClientTest<AtmosStorageAsyn
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", return new RestContextFactory().createContextSpec("atmosonline", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -130,39 +130,31 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Singleton @Singleton
@Named("PRESENT") @Named("PRESENT")
protected Predicate<RunningInstance> instancePresent(InstancePresent present) { protected Predicate<RunningInstance> instancePresent(InstancePresent present) {
return new RetryablePredicate<RunningInstance>(present, 3000, 200, return new RetryablePredicate<RunningInstance>(present, 3000, 200, TimeUnit.MILLISECONDS);
TimeUnit.MILLISECONDS);
} }
@Override @Override
protected void configure() { protected void configure() {
install(new ComputeServiceTimeoutsModule()); install(new ComputeServiceTimeoutsModule());
bind(Location.class).toProvider(DefaultLocationProvider.class).in( bind(Location.class).toProvider(DefaultLocationProvider.class).in(Scopes.SINGLETON);
Scopes.SINGLETON);
bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class); bind(TemplateBuilder.class).to(EC2TemplateBuilderImpl.class);
bind(TemplateOptions.class).to(EC2TemplateOptions.class); bind(TemplateOptions.class).to(EC2TemplateOptions.class);
bind(ComputeService.class).to(EC2ComputeService.class); bind(ComputeService.class).to(EC2ComputeService.class);
bind(new TypeLiteral<ComputeServiceContext>() { bind(new TypeLiteral<ComputeServiceContext>() {
}) }).to(new TypeLiteral<ComputeServiceContextImpl<EC2Client, EC2AsyncClient>>() {
.to(
new TypeLiteral<ComputeServiceContextImpl<EC2Client, EC2AsyncClient>>() {
}).in(Scopes.SINGLETON); }).in(Scopes.SINGLETON);
bind(new TypeLiteral<RestContext<EC2Client, EC2AsyncClient>>() { bind(new TypeLiteral<RestContext<EC2Client, EC2AsyncClient>>() {
}).to(new TypeLiteral<RestContextImpl<EC2Client, EC2AsyncClient>>() { }).to(new TypeLiteral<RestContextImpl<EC2Client, EC2AsyncClient>>() {
}).in(Scopes.SINGLETON); }).in(Scopes.SINGLETON);
bind(LoadBalanceNodesStrategy.class) bind(LoadBalanceNodesStrategy.class).to(EC2LoadBalanceNodesStrategy.class);
.to(EC2LoadBalanceNodesStrategy.class); bind(DestroyLoadBalancerStrategy.class).to(EC2DestroyLoadBalancerStrategy.class);
bind(DestroyLoadBalancerStrategy.class).to( bind(RunNodesAndAddToSetStrategy.class).to(EC2RunNodesAndAddToSetStrategy.class);
EC2DestroyLoadBalancerStrategy.class);
bind(RunNodesAndAddToSetStrategy.class).to(
EC2RunNodesAndAddToSetStrategy.class);
bind(ListNodesStrategy.class).to(EC2ListNodesStrategy.class); bind(ListNodesStrategy.class).to(EC2ListNodesStrategy.class);
bind(GetNodeMetadataStrategy.class).to(EC2GetNodeMetadataStrategy.class); bind(GetNodeMetadataStrategy.class).to(EC2GetNodeMetadataStrategy.class);
bind(RebootNodeStrategy.class).to(EC2RebootNodeStrategy.class); bind(RebootNodeStrategy.class).to(EC2RebootNodeStrategy.class);
bind(DestroyNodeStrategy.class).to(EC2DestroyNodeStrategy.class); bind(DestroyNodeStrategy.class).to(EC2DestroyNodeStrategy.class);
bind(new TypeLiteral<Function<RunningInstance, Map<String, String>>>() { bind(new TypeLiteral<Function<RunningInstance, Map<String, String>>>() {
}).annotatedWith(Names.named("volumeMapping")).to( }).annotatedWith(Names.named("volumeMapping")).to(RunningInstanceToStorageMappingUnix.class).in(Scopes.SINGLETON);
RunningInstanceToStorageMappingUnix.class).in(Scopes.SINGLETON);
} }
@Provides @Provides
@ -181,11 +173,9 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Named("DEFAULT") @Named("DEFAULT")
protected TemplateBuilder provideTemplate(@Region String region, protected TemplateBuilder provideTemplate(@Region String region, TemplateBuilder template) {
TemplateBuilder template) { return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() : template.architecture(
return "Eucalyptus".equals(region) ? template.osFamily(CENTOS).smallest() Architecture.X86_32).osFamily(UBUNTU).imageNameMatches(".*10\\.?04.*").osDescriptionMatches(
: template.architecture(Architecture.X86_32).osFamily(UBUNTU)
.imageNameMatches(".*10\\.?04.*").osDescriptionMatches(
"^ubuntu-images.*"); "^ubuntu-images.*");
} }
@ -204,8 +194,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
private final ExecutorService executor; private final ExecutorService executor;
@Inject @Inject
protected EC2ListNodesStrategy(EC2Client client, protected EC2ListNodesStrategy(EC2Client client, @Region Map<String, URI> regionMap,
@Region Map<String, URI> regionMap,
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) { @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) {
this.client = client; this.client = client;
@ -220,45 +209,37 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
} }
@Override @Override
public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching( public Iterable<? extends NodeMetadata> listDetailsOnNodesMatching(Predicate<ComputeMetadata> filter) {
Predicate<ComputeMetadata> filter) {
final Set<NodeMetadata> nodes = Sets.newHashSet(); final Set<NodeMetadata> nodes = Sets.newHashSet();
Map<String, ListenableFuture<?>> parallelResponses = Maps.newHashMap(); Map<String, ListenableFuture<?>> parallelResponses = Maps.newHashMap();
for (final String region : regionMap.keySet()) { for (final String region : regionMap.keySet()) {
parallelResponses.put(region, ConcurrentUtils.makeListenable( parallelResponses.put(region, ConcurrentUtils.makeListenable(executor.submit(new Callable<Void>() {
executor.submit(new Callable<Void>() {
@Override @Override
public Void call() throws Exception { public Void call() throws Exception {
Iterables.addAll(nodes, Iterables.transform(Iterables Iterables.addAll(nodes, Iterables.transform(Iterables.concat(client.getInstanceServices()
.concat(client.getInstanceServices() .describeInstancesInRegion(region)), runningInstanceToNodeMetadata));
.describeInstancesInRegion(region)),
runningInstanceToNodeMetadata));
return null; return null;
} }
}), executor)); }), executor));
} }
Map<String, Exception> exceptions = awaitCompletion(parallelResponses, Map<String, Exception> exceptions = awaitCompletion(parallelResponses, executor, null, logger, "nodes");
executor, null, logger, "nodes");
if (exceptions.size() > 0) if (exceptions.size() > 0)
throw new RuntimeException(String.format( throw new RuntimeException(String.format("error parsing nodes in regions: %s", exceptions));
"error parsing nodes in regions: %s", exceptions));
return Iterables.filter(nodes, filter); return Iterables.filter(nodes, filter);
} }
} }
@Singleton @Singleton
public static class EC2GetNodeMetadataStrategy implements public static class EC2GetNodeMetadataStrategy implements GetNodeMetadataStrategy {
GetNodeMetadataStrategy {
private final EC2Client client; private final EC2Client client;
private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata; private final RunningInstanceToNodeMetadata runningInstanceToNodeMetadata;
@Inject @Inject
protected EC2GetNodeMetadataStrategy(EC2Client client, protected EC2GetNodeMetadataStrategy(EC2Client client, RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) {
RunningInstanceToNodeMetadata runningInstanceToNodeMetadata) {
this.client = client; this.client = client;
this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata; this.runningInstanceToNodeMetadata = runningInstanceToNodeMetadata;
} }
@ -269,8 +250,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
String region = parts[0]; String region = parts[0];
String instanceId = parts[1]; String instanceId = parts[1];
try { try {
RunningInstance runningInstance = Iterables RunningInstance runningInstance = Iterables.getOnlyElement(getAllRunningInstancesInRegion(client
.getOnlyElement(getAllRunningInstancesInRegion(client
.getInstanceServices(), region, instanceId)); .getInstanceServices(), region, instanceId));
return runningInstanceToNodeMetadata.apply(runningInstance); return runningInstanceToNodeMetadata.apply(runningInstance);
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
@ -286,8 +266,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
private final GetNodeMetadataStrategy getNode; private final GetNodeMetadataStrategy getNode;
@Inject @Inject
protected EC2RebootNodeStrategy(EC2Client client, protected EC2RebootNodeStrategy(EC2Client client, GetNodeMetadataStrategy getNode) {
GetNodeMetadataStrategy getNode) {
this.client = client.getInstanceServices(); this.client = client.getInstanceServices();
this.getNode = getNode; this.getNode = getNode;
} }
@ -305,8 +284,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
protected final Map<RegionAndName, KeyPair> credentialsMap( protected final Map<RegionAndName, KeyPair> credentialsMap(CreateUniqueKeyPair in) {
CreateUniqueKeyPair in) {
// doesn't seem to clear when someone issues remove(key) // doesn't seem to clear when someone issues remove(key)
// return new MapMaker().makeComputingMap(in); // return new MapMaker().makeComputingMap(in);
return Maps.newLinkedHashMap(); return Maps.newLinkedHashMap();
@ -314,8 +292,7 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
protected final Map<RegionAndName, String> securityGroupMap( protected final Map<RegionAndName, String> securityGroupMap(CreateSecurityGroupIfNeeded in) {
CreateSecurityGroupIfNeeded in) {
// doesn't seem to clear when someone issues remove(key) // doesn't seem to clear when someone issues remove(key)
// return new MapMaker().makeComputingMap(in); // return new MapMaker().makeComputingMap(in);
return Maps.newLinkedHashMap(); return Maps.newLinkedHashMap();
@ -334,45 +311,36 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
Set<? extends Size> provideSizes(Set<? extends Location> locations, Set<? extends Size> provideSizes(Set<? extends Location> locations, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis) {
Set<Size> sizes = Sets.newHashSet(); Set<Size> sizes = Sets.newHashSet();
for (String ccAmi : ccAmis) { for (String ccAmi : ccAmis) {
final String region = ccAmi.split("/")[0]; final String region = ccAmi.split("/")[0];
Location location = Iterables.find(locations, Location location = Iterables.find(locations, new Predicate<Location>() {
new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
return input.getScope() == LocationScope.REGION return input.getScope() == LocationScope.REGION && input.getId().equals(region);
&& input.getId().equals(region);
} }
}); });
sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, sizes.add(new EC2Size(location, InstanceType.CC1_4XLARGE, 33.5, 23 * 1024, 1690, ccAmis));
23 * 1024, 1690, ccAmis));
} }
sizes.addAll(ImmutableSet.<Size> of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, sizes.addAll(ImmutableSet.<Size> of(EC2Size.C1_MEDIUM, EC2Size.C1_XLARGE, EC2Size.M1_LARGE, EC2Size.M1_SMALL,
EC2Size.M1_LARGE, EC2Size.M1_SMALL, EC2Size.M1_XLARGE, EC2Size.M1_XLARGE, EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE));
EC2Size.M2_XLARGE, EC2Size.M2_2XLARGE, EC2Size.M2_4XLARGE));
return sizes; return sizes;
} }
@Provides @Provides
@Singleton @Singleton
Set<? extends Location> provideLocations( Set<? extends Location> provideLocations(Map<String, String> availabilityZoneToRegionMap,
Map<String, String> availabilityZoneToRegionMap,
@Provider String providerName) { @Provider String providerName) {
Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, Location ec2 = new LocationImpl(LocationScope.PROVIDER, providerName, providerName, null);
providerName, null);
Set<Location> locations = Sets.newLinkedHashSet(); Set<Location> locations = Sets.newLinkedHashSet();
for (String zone : availabilityZoneToRegionMap.keySet()) { for (String zone : availabilityZoneToRegionMap.keySet()) {
Location region = new LocationImpl(LocationScope.REGION, Location region = new LocationImpl(LocationScope.REGION, availabilityZoneToRegionMap.get(zone),
availabilityZoneToRegionMap.get(zone),
availabilityZoneToRegionMap.get(zone), ec2); availabilityZoneToRegionMap.get(zone), ec2);
locations.add(region); locations.add(region);
locations locations.add(new LocationImpl(LocationScope.ZONE, zone, zone, region));
.add(new LocationImpl(LocationScope.ZONE, zone, zone, region));
} }
return locations; return locations;
} }
@ -402,29 +370,24 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
} }
@Provides @Provides
protected Set<? extends Image> provideImages( protected Set<? extends Image> provideImages(Map<RegionAndName, ? extends Image> map) {
Map<RegionAndName, ? extends Image> map) {
return ImmutableSet.copyOf(map.values()); return ImmutableSet.copyOf(map.values());
} }
@Provides @Provides
@Singleton @Singleton
protected ConcurrentMap<RegionAndName, Image> provideImageMap( protected ConcurrentMap<RegionAndName, Image> provideImageMap(RegionAndIdToImage regionAndIdToImage) {
RegionAndIdToImage regionAndIdToImage) {
return new MapMaker().makeComputingMap(regionAndIdToImage); return new MapMaker().makeComputingMap(regionAndIdToImage);
} }
@Provides @Provides
@Singleton @Singleton
protected Map<RegionAndName, ? extends Image> provideImages( protected Map<RegionAndName, ? extends Image> provideImages(final EC2Client sync,
final EC2Client sync, @Region Map<String, URI> regionMap, @Region Map<String, URI> regionMap, final LogHolder holder, Function<ComputeMetadata, String> indexer,
final LogHolder holder, Function<ComputeMetadata, String> indexer, @Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, @Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners,
@Named(PROPERTY_EC2_CC_AMIs) String[] ccAmis, final ImageParser parser, final ConcurrentMap<RegionAndName, Image> images,
@Named(PROPERTY_EC2_AMI_OWNERS) final String[] amiOwners, @Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor) throws InterruptedException,
final ImageParser parser, ExecutionException, TimeoutException {
final ConcurrentMap<RegionAndName, Image> images,
@Named(Constants.PROPERTY_USER_THREADS) ExecutorService executor)
throws InterruptedException, ExecutionException, TimeoutException {
if (amiOwners.length == 0) { if (amiOwners.length == 0) {
holder.logger.debug(">> no owners specified, skipping image parsing"); holder.logger.debug(">> no owners specified, skipping image parsing");
} else { } else {
@ -437,40 +400,33 @@ public class EC2ComputeServiceContextModule extends AbstractModule {
else else
options = ownedBy(amiOwners); options = ownedBy(amiOwners);
for (final String region : regionMap.keySet()) { for (final String region : regionMap.keySet()) {
parallelResponses.put(region, ConcurrentUtils.makeListenable( parallelResponses.put(region, ConcurrentUtils.makeListenable(executor.submit(new Callable<Void>() {
executor.submit(new Callable<Void>() {
@Override @Override
public Void call() throws Exception { public Void call() throws Exception {
for (final org.jclouds.aws.ec2.domain.Image from : sync Set<org.jclouds.aws.ec2.domain.Image> matchingImages = sync.getAMIServices().describeImagesInRegion(
.getAMIServices().describeImagesInRegion(region, region, options);
options)) { for (final org.jclouds.aws.ec2.domain.Image from : matchingImages) {
Image image = parser.apply(from); Image image = parser.apply(from);
if (image != null) if (image != null)
images.put(new RegionAndName(region, image images.put(new RegionAndName(region, image.getProviderId()), image);
.getProviderId()), image);
else if (from.getImageType() == ImageType.MACHINE) else if (from.getImageType() == ImageType.MACHINE)
holder.logger.trace("<< image(%s) didn't parse", holder.logger.trace("<< image(%s) didn't parse", from.getId());
from.getId());
} }
return null; return null;
} }
}), executor)); }), executor));
} }
Map<String, Exception> exceptions = awaitCompletion(parallelResponses, Map<String, Exception> exceptions = awaitCompletion(parallelResponses, executor, null, holder.logger, "images");
executor, null, holder.logger, "images");
for (String ccAmi : ccAmis) { for (String ccAmi : ccAmis) {
String region = ccAmi.split("/")[0]; String region = ccAmi.split("/")[0];
org.jclouds.aws.ec2.domain.Image from = Iterables org.jclouds.aws.ec2.domain.Image from = Iterables.getOnlyElement(sync.getAMIServices()
.getOnlyElement(sync.getAMIServices().describeImagesInRegion( .describeImagesInRegion(region, imageIds(ccAmi.split("/")[1])));
region, imageIds(ccAmi.split("/")[1])));
Image image = parser.apply(from); Image image = parser.apply(from);
if (image != null) if (image != null)
images.put(new RegionAndName(region, image.getProviderId()), images.put(new RegionAndName(region, image.getProviderId()), image);
image);
} }
if (exceptions.size() > 0) if (exceptions.size() > 0)
throw new RuntimeException(String.format( throw new RuntimeException(String.format("error parsing images in regions: %s", exceptions));
"error parsing images in regions: %s", exceptions));
holder.logger.debug("<< images(%d)", images.size()); holder.logger.debug("<< images(%d)", images.size());
} }

View File

@ -1,6 +1,25 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.aws.ec2.compute.internal; package org.jclouds.aws.ec2.compute.internal;
import java.util.List; import static com.google.common.base.Preconditions.checkArgument;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
@ -18,7 +37,7 @@ import org.jclouds.compute.internal.TemplateBuilderImpl;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet;
/** /**
* *
@ -29,15 +48,11 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
private final ConcurrentMap<RegionAndName, Image> imageMap; private final ConcurrentMap<RegionAndName, Image> imageMap;
@Inject @Inject
protected EC2TemplateBuilderImpl( protected EC2TemplateBuilderImpl(Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images,
Provider<Set<? extends Location>> locations, Provider<Set<? extends Size>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider,
Provider<Set<? extends Image>> images,
Provider<Set<? extends Size>> sizes, Location defaultLocation,
Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider, @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider,
ConcurrentMap<RegionAndName, Image> imageMap) { ConcurrentMap<RegionAndName, Image> imageMap) {
super(locations, images, sizes, defaultLocation, optionsProvider, super(locations, images, sizes, defaultLocation, optionsProvider, defaultTemplateProvider);
defaultTemplateProvider);
this.imageMap = imageMap; this.imageMap = imageMap;
} }
@ -47,37 +62,62 @@ public class EC2TemplateBuilderImpl extends TemplateBuilderImpl {
if (from instanceof EC2TemplateOptions) { if (from instanceof EC2TemplateOptions) {
EC2TemplateOptions eFrom = EC2TemplateOptions.class.cast(from); EC2TemplateOptions eFrom = EC2TemplateOptions.class.cast(from);
EC2TemplateOptions eTo = EC2TemplateOptions.class.cast(to); EC2TemplateOptions eTo = EC2TemplateOptions.class.cast(to);
if (eFrom.getGroupIds().size() >0) if (eFrom.getGroupIds().size() > 0)
eTo.securityGroups(eFrom.getGroupIds()); eTo.securityGroups(eFrom.getGroupIds());
if (eFrom.getKeyPair() != null) if (eFrom.getKeyPair() != null)
eTo.keyPair(eFrom.getKeyPair()); eTo.keyPair(eFrom.getKeyPair());
if (!eFrom.shouldAutomaticallyCreateKeyPair()) if (!eFrom.shouldAutomaticallyCreateKeyPair())
eTo.noKeyPair(); eTo.noKeyPair();
if(eFrom.getSubnetId() != null) if (eFrom.getSubnetId() != null)
eTo.subnetId(eFrom.getSubnetId()); eTo.subnetId(eFrom.getSubnetId());
} }
} }
final Provider<Image> lazyImageProvider = new Provider<Image>() {
@Override
public Image get() {
if (imageId != null) {
String[] regionName = imageId.split("/");
checkArgument(regionName.length == 2,
"amazon image ids must include the region. ex. us-east-1/ami-7ea24a17");
RegionAndName key = new RegionAndName(regionName[0], regionName[1]);
try {
return imageMap.get(key);
} catch (NullPointerException nex) {
throw new NoSuchElementException(String.format("image %s/%s not found", key.getRegion(), key.getName()));
}
}
return null;
}
};
/** /**
* @throws NoSuchElementException * @throws NoSuchElementException
* if the image is not found * if the image is not found
*/ */
@Override @Override
protected List<? extends Image> resolveImages() { protected Image resolveImage(Size size) {
try { try {
return super.resolveImages(); return super.resolveImage(size);
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
if (locationId != null && imageId != null) { Image returnVal = lazyImageProvider.get();
RegionAndName key = new RegionAndName(this.locationId, this.imageId); if (returnVal != null)
try { return returnVal;
return ImmutableList.of(imageMap.get(key));
} catch (NullPointerException nex) {
throw new NoSuchElementException(String.format(
"image %s/%s not found", key.getRegion(), key.getName()));
}
}
throw e; throw e;
} }
} }
@Override
protected Set<? extends Image> getImages() {
Set<? extends Image> images = this.images.get();
if (images.size() == 0) {
Image toReturn = lazyImageProvider.get();
if (toReturn != null)
return ImmutableSet.of(lazyImageProvider.get());
}
return images;
}
} }

View File

@ -21,7 +21,9 @@ package org.jclouds.aws.ec2.xml;
import java.util.Set; import java.util.Set;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject;
import org.jclouds.aws.Region;
import org.jclouds.aws.ec2.domain.AvailabilityZoneInfo; import org.jclouds.aws.ec2.domain.AvailabilityZoneInfo;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
@ -33,9 +35,9 @@ import com.google.common.collect.Sets;
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
public class DescribeAvailabilityZonesResponseHandler extends public class DescribeAvailabilityZonesResponseHandler extends ParseSax.HandlerWithResult<Set<AvailabilityZoneInfo>> {
ParseSax.HandlerWithResult<Set<AvailabilityZoneInfo>> {
private StringBuilder currentText = new StringBuilder(); private StringBuilder currentText = new StringBuilder();
private final String defaultRegion;
private Set<AvailabilityZoneInfo> availablilityZones = Sets.newLinkedHashSet(); private Set<AvailabilityZoneInfo> availablilityZones = Sets.newLinkedHashSet();
private String zone; private String zone;
@ -46,6 +48,15 @@ public class DescribeAvailabilityZonesResponseHandler extends
private boolean inMessageSet; private boolean inMessageSet;
private Set<String> messages = Sets.newHashSet(); private Set<String> messages = Sets.newHashSet();
/**
* Eucalyptus 1.6 doesn't return region in the XML output
*/
@Inject
DescribeAvailabilityZonesResponseHandler(@Region String defaultRegion) {
this.defaultRegion = defaultRegion;
region = defaultRegion;
}
public Set<AvailabilityZoneInfo> getResult() { public Set<AvailabilityZoneInfo> getResult() {
return availablilityZones; return availablilityZones;
} }
@ -75,7 +86,7 @@ public class DescribeAvailabilityZonesResponseHandler extends
} else if (qName.equals("item") && !inMessageSet) { } else if (qName.equals("item") && !inMessageSet) {
availablilityZones.add(new AvailabilityZoneInfo(zone, zoneState, region, messages)); availablilityZones.add(new AvailabilityZoneInfo(zone, zoneState, region, messages));
this.zone = null; this.zone = null;
this.region = null; this.region = defaultRegion;
this.zoneState = null; this.zoneState = null;
this.messages = Sets.newHashSet(); this.messages = Sets.newHashSet();
} }

View File

@ -49,8 +49,7 @@ import com.google.common.collect.Sets;
* @see <a href="http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html" * @see <a href="http://docs.amazonwebservices.com/AWSEC2/latest/APIReference/ApiReference-query-DescribeImages.html"
* /> * />
*/ */
public class DescribeImagesResponseHandler extends public class DescribeImagesResponseHandler extends ParseSax.HandlerForGeneratedRequestWithResult<Set<Image>> {
ParseSax.HandlerForGeneratedRequestWithResult<Set<Image>> {
@Inject @Inject
public DescribeImagesResponseHandler(@Region String defaultRegion) { public DescribeImagesResponseHandler(@Region String defaultRegion) {
@ -79,7 +78,10 @@ public class DescribeImagesResponseHandler extends
private String ramdiskId; private String ramdiskId;
private boolean inProductCodes; private boolean inProductCodes;
private boolean inBlockDeviceMapping; private boolean inBlockDeviceMapping;
private RootDeviceType rootDeviceType; /**
* Eucalyptus 1.6 doesn't set rootDeviceType
*/
private RootDeviceType rootDeviceType = RootDeviceType.INSTANCE_STORE;
private Map<String, EbsBlockDevice> ebsBlockDevices = Maps.newHashMap(); private Map<String, EbsBlockDevice> ebsBlockDevices = Maps.newHashMap();
private String deviceName; private String deviceName;
private String snapshotId; private String snapshotId;
@ -149,8 +151,7 @@ public class DescribeImagesResponseHandler extends
virtualizationType = currentText.toString().trim(); virtualizationType = currentText.toString().trim();
} else if (qName.equals("item")) { } else if (qName.equals("item")) {
if (inBlockDeviceMapping) { if (inBlockDeviceMapping) {
ebsBlockDevices.put(deviceName, new Image.EbsBlockDevice(snapshotId, volumeSize, ebsBlockDevices.put(deviceName, new Image.EbsBlockDevice(snapshotId, volumeSize, deleteOnTermination));
deleteOnTermination));
this.deviceName = null; this.deviceName = null;
this.snapshotId = null; this.snapshotId = null;
this.volumeSize = 0; this.volumeSize = 0;
@ -160,10 +161,9 @@ public class DescribeImagesResponseHandler extends
String region = EC2Utils.findRegionInArgsOrNull((GeneratedHttpRequest<?>) request); String region = EC2Utils.findRegionInArgsOrNull((GeneratedHttpRequest<?>) request);
if (region == null) if (region == null)
region = defaultRegion; region = defaultRegion;
contents.add(new Image(region, architecture, this.name, description, imageId, contents.add(new Image(region, architecture, this.name, description, imageId, imageLocation,
imageLocation, imageOwnerId, imageState, imageType, isPublic, productCodes, imageOwnerId, imageState, imageType, isPublic, productCodes, kernelId, platform, ramdiskId,
kernelId, platform, ramdiskId, rootDeviceType, rootDeviceName, rootDeviceType, rootDeviceName, ebsBlockDevices, virtualizationType));
ebsBlockDevices, virtualizationType));
} catch (NullPointerException e) { } catch (NullPointerException e) {
logger.warn(e, "malformed image: %s", imageId); logger.warn(e, "malformed image: %s", imageId);
} }
@ -180,7 +180,7 @@ public class DescribeImagesResponseHandler extends
this.platform = null; this.platform = null;
this.productCodes = Sets.newHashSet(); this.productCodes = Sets.newHashSet();
this.ramdiskId = null; this.ramdiskId = null;
this.rootDeviceType = null; this.rootDeviceType = RootDeviceType.INSTANCE_STORE;
this.rootDeviceName = null; this.rootDeviceName = null;
this.ebsBlockDevices = Maps.newHashMap(); this.ebsBlockDevices = Maps.newHashMap();
this.virtualizationType = "paravirtual"; this.virtualizationType = "paravirtual";

View File

@ -66,31 +66,31 @@ public class ParseAWSErrorFromXmlContent implements HttpErrorHandler {
try { try {
AWSError error = utils.parseAWSErrorFromContent(request, response); AWSError error = utils.parseAWSErrorFromContent(request, response);
exception = error != null ? new AWSResponseException(command, response, error) : exception; exception = error != null ? new AWSResponseException(command, response, error) : exception;
String notFoundMessage = error != null ? error.getMessage() : String.format("%s -> %s", request
.getRequestLine(), response.getStatusLine());
switch (response.getStatusCode()) { switch (response.getStatusCode()) {
case 400: case 400:
if (error.getCode().endsWith(".NotFound")) if (error.getCode().endsWith(".NotFound"))
exception = new ResourceNotFoundException(error.getMessage(), exception); exception = new ResourceNotFoundException(notFoundMessage, exception);
else if (error.getCode().equals("IncorrectState")) else if (error.getCode().equals("IncorrectState"))
exception = new IllegalStateException(error.getMessage(), exception); exception = new IllegalStateException(error.getMessage(), exception);
else if (error.getCode().equals("AuthFailure")) else if (error.getCode().equals("AuthFailure"))
exception = new AuthorizationException(command.getRequest(), exception = new AuthorizationException(command.getRequest(), error != null ? error.getMessage()
error != null ? error.getMessage() : response.getStatusLine()); : response.getStatusLine());
break; break;
case 401: case 401:
case 403: case 403:
exception = new AuthorizationException(command.getRequest(), error != null ? error exception = new AuthorizationException(command.getRequest(), error != null ? error.getMessage() : response
.getMessage() : response.getStatusLine()); .getStatusLine());
break; break;
case 404: case 404:
if (!command.getRequest().getMethod().equals("DELETE")) { if (!command.getRequest().getMethod().equals("DELETE")) {
String message = error != null ? error.getMessage() : String.format("%s -> %s",
request.getRequestLine(), response.getStatusLine());
String container = request.getEndpoint().getHost(); String container = request.getEndpoint().getHost();
String key = request.getEndpoint().getPath(); String key = request.getEndpoint().getPath();
if (key == null || key.equals("/")) if (key == null || key.equals("/"))
exception = new ContainerNotFoundException(container, message); exception = new ContainerNotFoundException(container, notFoundMessage);
else else
exception = new KeyNotFoundException(container, key, message); exception = new KeyNotFoundException(container, key, notFoundMessage);
} }
break; break;
} }

View File

@ -33,8 +33,10 @@ import org.jclouds.aws.ec2.services.InstanceClient;
import org.jclouds.aws.ec2.services.KeyPairClient; import org.jclouds.aws.ec2.services.KeyPairClient;
import org.jclouds.aws.ec2.services.SecurityGroupClient; import org.jclouds.aws.ec2.services.SecurityGroupClient;
import org.jclouds.compute.BaseComputeServiceLiveTest; import org.jclouds.compute.BaseComputeServiceLiveTest;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.Image;
import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.NodeMetadata;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Size; import org.jclouds.compute.domain.Size;
import org.jclouds.compute.domain.Template; import org.jclouds.compute.domain.Template;
import org.jclouds.compute.options.TemplateOptions; import org.jclouds.compute.options.TemplateOptions;
@ -66,7 +68,32 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
} }
@Test(enabled = true, dependsOnMethods = "testCorrectAuthException") @Test(enabled = true, dependsOnMethods = "testCorrectAuthException")
public void testImagesResolveCorrectly() {
Template defaultTemplate = client.templateBuilder().build();
assertEquals(defaultTemplate.getImage().getId(), defaultTemplate.getImage().getLocation().getId() + "/"
+ defaultTemplate.getImage().getProviderId());
Template byId = client.templateBuilder().imageId(defaultTemplate.getImage().getId()).build();
assertEquals(byId.getImage(), defaultTemplate.getImage());
}
@Test(enabled = true, dependsOnMethods = "testImagesResolveCorrectly")
public void testDefaultTemplateBuilder() {
assertDefaultWorks();
}
protected void assertDefaultWorks() {
Template defaultTemplate = client.templateBuilder().build();
assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_32);
assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.UBUNTU);
assertEquals(defaultTemplate.getSize().getCores(), 1.0d);
}
@Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder")
public void testTemplateChoiceForInstanceByCCSizeId() throws Exception { public void testTemplateChoiceForInstanceByCCSizeId() throws Exception {
assertCCsizeWorks();
}
protected void assertCCsizeWorks() {
Set<? extends Size> sizes = context.getComputeService().listSizes(); Set<? extends Size> sizes = context.getComputeService().listSizes();
assert Iterables.any(sizes, new Predicate<Size>() { assert Iterables.any(sizes, new Predicate<Size>() {
@ -85,24 +112,21 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
} }
}) : images; }) : images;
Template template = context.getComputeService().templateBuilder() Template template = context.getComputeService().templateBuilder().fastest().build();
.fastest().build();
assert template != null : "The returned template was null, but it should have a value."; assert template != null : "The returned template was null, but it should have a value.";
assertEquals(template.getSize().getProviderId(), InstanceType.CC1_4XLARGE); assertEquals(template.getSize().getProviderId(), InstanceType.CC1_4XLARGE);
assertEquals(template.getImage().getId(), "us-east-1/ami-7ea24a17"); assertEquals(template.getImage().getId(), "us-east-1/ami-7ea24a17");
} }
@Test(enabled = true, dependsOnMethods = "testTemplateChoiceForInstanceByCCSizeId") @Test(enabled = true, dependsOnMethods = "testDefaultTemplateBuilder")
public void testExtendedOptionsAndLogin() throws Exception { public void testExtendedOptionsAndLogin() throws Exception {
SecurityGroupClient securityGroupClient = EC2Client.class.cast( SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getSecurityGroupServices(); .getSecurityGroupServices();
KeyPairClient keyPairClient = EC2Client.class.cast( KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi()).getKeyPairServices(); .getKeyPairServices();
InstanceClient instanceClient = EC2Client.class.cast( InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getInstanceServices(); .getInstanceServices();
String tag = this.tag + "optionsandlogin"; String tag = this.tag + "optionsandlogin";
@ -119,14 +143,12 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
// create a security group that allows ssh in so that our scripts later // create a security group that allows ssh in so that our scripts later
// will work // will work
securityGroupClient.createSecurityGroupInRegion(null, tag, tag); securityGroupClient.createSecurityGroupInRegion(null, tag, tag);
securityGroupClient.authorizeSecurityGroupIngressInRegion(null, tag, securityGroupClient.authorizeSecurityGroupIngressInRegion(null, tag, IpProtocol.TCP, 22, 22, "0.0.0.0/0");
IpProtocol.TCP, 22, 22, "0.0.0.0/0");
// create a keypair to pass in as well // create a keypair to pass in as well
KeyPair result = keyPairClient.createKeyPairInRegion(null, tag); KeyPair result = keyPairClient.createKeyPairInRegion(null, tag);
Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
options);
NodeMetadata first = Iterables.get(nodes, 0); NodeMetadata first = Iterables.get(nodes, 0);
assert first.getCredentials() != null : first; assert first.getCredentials() != null : first;
assert first.getCredentials().identity != null : first; assert first.getCredentials().identity != null : first;
@ -138,27 +160,23 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
assertEquals(instance.getKeyName(), tag); assertEquals(instance.getKeyName(), tag);
// make sure we made our dummy group and also let in the user's group // make sure we made our dummy group and also let in the user's group
assertEquals(instance.getGroupIds(), ImmutableSet.<String> of(tag, assertEquals(instance.getGroupIds(), ImmutableSet.<String> of(tag, "jclouds#" + tag));
"jclouds#" + tag));
// make sure our dummy group has no rules // make sure our dummy group has no rules
SecurityGroup group = Iterables.getOnlyElement(securityGroupClient SecurityGroup group = Iterables.getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(null,
.describeSecurityGroupsInRegion(null, "jclouds#" + tag)); "jclouds#" + tag));
assert group.getIpPermissions().size() == 0 : group; assert group.getIpPermissions().size() == 0 : group;
// try to run a script with the original keyPair // try to run a script with the original keyPair
runScriptWithCreds(tag, first.getImage().getOsFamily(), runScriptWithCreds(tag, first.getImage().getOsFamily(), new Credentials(first.getCredentials().identity,
new Credentials(first.getCredentials().identity, result result.getKeyMaterial()));
.getKeyMaterial()));
} finally { } finally {
client.destroyNodesMatching(NodePredicates.withTag(tag)); client.destroyNodesMatching(NodePredicates.withTag(tag));
if (startedId != null) { if (startedId != null) {
// ensure we didn't delete these resources! // ensure we didn't delete these resources!
assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag) assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag).size(), 1);
.size(), 1); assertEquals(securityGroupClient.describeSecurityGroupsInRegion(null, tag).size(), 1);
assertEquals(securityGroupClient.describeSecurityGroupsInRegion(
null, tag).size(), 1);
} }
cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); cleanupExtendedStuff(securityGroupClient, keyPairClient, tag);
} }
@ -166,15 +184,13 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
@Test(enabled = true, dependsOnMethods = "testTemplateChoiceForInstanceByCCSizeId") @Test(enabled = true, dependsOnMethods = "testTemplateChoiceForInstanceByCCSizeId")
public void testExtendedOptionsNoKeyPair() throws Exception { public void testExtendedOptionsNoKeyPair() throws Exception {
SecurityGroupClient securityGroupClient = EC2Client.class.cast( SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getSecurityGroupServices(); .getSecurityGroupServices();
KeyPairClient keyPairClient = EC2Client.class.cast( KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi()).getKeyPairServices(); .getKeyPairServices();
InstanceClient instanceClient = EC2Client.class.cast( InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getInstanceServices(); .getInstanceServices();
String tag = this.tag + "optionsnokey"; String tag = this.tag + "optionsnokey";
@ -191,8 +207,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
// create the security group // create the security group
securityGroupClient.createSecurityGroupInRegion(null, tag, tag); securityGroupClient.createSecurityGroupInRegion(null, tag, tag);
Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
options);
Credentials creds = nodes.iterator().next().getCredentials(); Credentials creds = nodes.iterator().next().getCredentials();
assert creds == null; assert creds == null;
@ -203,20 +218,18 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
assertEquals(instance.getKeyName(), null); assertEquals(instance.getKeyName(), null);
// make sure we made our dummy group and also let in the user's group // make sure we made our dummy group and also let in the user's group
assertEquals(instance.getGroupIds(), ImmutableSet.<String> of(tag, assertEquals(instance.getGroupIds(), ImmutableSet.<String> of(tag, "jclouds#" + tag));
"jclouds#" + tag));
// make sure our dummy group has no rules // make sure our dummy group has no rules
SecurityGroup group = Iterables.getOnlyElement(securityGroupClient SecurityGroup group = Iterables.getOnlyElement(securityGroupClient.describeSecurityGroupsInRegion(null,
.describeSecurityGroupsInRegion(null, "jclouds#" + tag)); "jclouds#" + tag));
assert group.getIpPermissions().size() == 0 : group; assert group.getIpPermissions().size() == 0 : group;
} finally { } finally {
client.destroyNodesMatching(NodePredicates.withTag(tag)); client.destroyNodesMatching(NodePredicates.withTag(tag));
if (startedId != null) { if (startedId != null) {
// ensure we didn't delete these resources! // ensure we didn't delete these resources!
assertEquals(securityGroupClient.describeSecurityGroupsInRegion( assertEquals(securityGroupClient.describeSecurityGroupsInRegion(null, tag).size(), 1);
null, tag).size(), 1);
} }
cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); cleanupExtendedStuff(securityGroupClient, keyPairClient, tag);
} }
@ -230,15 +243,13 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
// Skip test and return // Skip test and return
return; return;
} }
SecurityGroupClient securityGroupClient = EC2Client.class.cast( SecurityGroupClient securityGroupClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getSecurityGroupServices(); .getSecurityGroupServices();
KeyPairClient keyPairClient = EC2Client.class.cast( KeyPairClient keyPairClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi()).getKeyPairServices(); .getKeyPairServices();
InstanceClient instanceClient = EC2Client.class.cast( InstanceClient instanceClient = EC2Client.class.cast(context.getProviderSpecificContext().getApi())
context.getProviderSpecificContext().getApi())
.getInstanceServices(); .getInstanceServices();
String tag = this.tag + "optionswithsubnetid"; String tag = this.tag + "optionswithsubnetid";
@ -260,8 +271,7 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
// create a keypair to pass in as well // create a keypair to pass in as well
keyPairClient.createKeyPairInRegion(null, tag); keyPairClient.createKeyPairInRegion(null, tag);
Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, Set<? extends NodeMetadata> nodes = client.runNodesWithTag(tag, 1, options);
options);
NodeMetadata first = Iterables.get(nodes, 0); NodeMetadata first = Iterables.get(nodes, 0);
assert first.getCredentials() != null : first; assert first.getCredentials() != null : first;
@ -279,22 +289,19 @@ public class EC2ComputeServiceLiveTest extends BaseComputeServiceLiveTest {
client.destroyNode(nodeId); client.destroyNode(nodeId);
if (startedId != null) { if (startedId != null) {
// ensure we didn't delete these resources! // ensure we didn't delete these resources!
assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag) assertEquals(keyPairClient.describeKeyPairsInRegion(null, tag).size(), 1);
.size(), 1);
} }
cleanupExtendedStuff(securityGroupClient, keyPairClient, tag); cleanupExtendedStuff(securityGroupClient, keyPairClient, tag);
} }
} }
private RunningInstance getInstance(InstanceClient instanceClient, String id) { private RunningInstance getInstance(InstanceClient instanceClient, String id) {
RunningInstance instance = Iterables RunningInstance instance = Iterables.getOnlyElement(Iterables.getOnlyElement(instanceClient
.getOnlyElement(Iterables.getOnlyElement(instanceClient
.describeInstancesInRegion(null, id))); .describeInstancesInRegion(null, id)));
return instance; return instance;
} }
private void cleanupExtendedStuff(SecurityGroupClient securityGroupClient, private void cleanupExtendedStuff(SecurityGroupClient securityGroupClient, KeyPairClient keyPairClient, String tag) {
KeyPairClient keyPairClient, String tag) {
try { try {
securityGroupClient.deleteSecurityGroupInRegion(null, tag); securityGroupClient.deleteSecurityGroupInRegion(null, tag);
} catch (Exception e) { } catch (Exception e) {

View File

@ -18,6 +18,11 @@
*/ */
package org.jclouds.aws.ec2.compute; package org.jclouds.aws.ec2.compute;
import static org.testng.Assert.assertEquals;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -35,4 +40,17 @@ public class EucalyptusComputeServiceLiveTest extends EC2ComputeServiceLiveTest
tag = "euc"; tag = "euc";
} }
@Override
protected void assertDefaultWorks() {
Template defaultTemplate = client.templateBuilder().build();
assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_64);
assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.CENTOS);
// 64 bit implied 4 ecus
assertEquals(defaultTemplate.getSize().getCores(), 4.0d);
}
@Override
protected void assertCCsizeWorks() {
// no CC size in eucalyptus
}
} }

View File

@ -49,54 +49,41 @@ import com.google.common.collect.Iterables;
public class ImageParserTest extends BaseEC2HandlerTest { public class ImageParserTest extends BaseEC2HandlerTest {
public void testParseAlesticCanonicalImage() { public void testParseAlesticCanonicalImage() {
InputStream is = getClass().getResourceAsStream( InputStream is = getClass().getResourceAsStream("/ec2/alestic_canonical.xml");
"/ec2/alestic_canonical.xml");
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
assertEquals(result.size(), 7); assertEquals(result.size(), 7);
ImageParser parser = new ImageParser( ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet
new EC2PopulateDefaultLoginCredentialsForImageStrategy(), .<Location> of(defaultLocation), defaultLocation);
ImmutableSet.<Location> of(defaultLocation), defaultLocation); org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables.get(result, 0));
org.jclouds.compute.domain.Image ubuntuHardy = parser.apply(Iterables
.get(result, 0));
assertEquals(ubuntuHardy.getArchitecture(), assertEquals(ubuntuHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuHardy.getDescription(), "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getDescription(),
"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getProviderId(), "ami-7e28ca17"); assertEquals(ubuntuHardy.getProviderId(), "ami-7e28ca17");
assertEquals(ubuntuHardy.getLocation(), defaultLocation); assertEquals(ubuntuHardy.getLocation(), defaultLocation);
assertEquals(ubuntuHardy.getName(), "8.04"); assertEquals(ubuntuHardy.getName(), "8.04");
assertEquals(ubuntuHardy.getOsDescription(), assertEquals(ubuntuHardy.getOsDescription(),
"ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml"); "ubuntu-images-us/ubuntu-hardy-8.04-i386-server-20091130.manifest.xml");
assertEquals(ubuntuHardy.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuHardy.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap assertEquals(ubuntuHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuHardy.getVersion(), "20091130"); assertEquals(ubuntuHardy.getVersion(), "20091130");
org.jclouds.compute.domain.Image alesticKarmic = parser.apply(Iterables org.jclouds.compute.domain.Image alesticKarmic = parser.apply(Iterables.get(result, 1));
.get(result, 1));
assertEquals(alesticKarmic.getArchitecture(), assertEquals(alesticKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32); assertEquals(alesticKarmic.getDescription(), "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
assertEquals(alesticKarmic.getDescription(),
"alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
assertEquals(alesticKarmic.getProviderId(), "ami-19a34270"); assertEquals(alesticKarmic.getProviderId(), "ami-19a34270");
assertEquals(alesticKarmic.getLocation(), defaultLocation); assertEquals(alesticKarmic.getLocation(), defaultLocation);
assertEquals(alesticKarmic.getName(), "9.10"); assertEquals(alesticKarmic.getName(), "9.10");
assertEquals(alesticKarmic.getOsDescription(), assertEquals(alesticKarmic.getOsDescription(), "alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
"alestic/ubuntu-9.10-karmic-base-20090623.manifest.xml");
assertEquals(alesticKarmic.getOsFamily(), OsFamily.UBUNTU); assertEquals(alesticKarmic.getOsFamily(), OsFamily.UBUNTU);
assertEquals(alesticKarmic.getUserMetadata(), ImmutableMap assertEquals(alesticKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "063491364108"));
.<String, String> of("owner", "063491364108"));
assertEquals(alesticKarmic.getVersion(), "20090623"); assertEquals(alesticKarmic.getVersion(), "20090623");
org.jclouds.compute.domain.Image ubuntuKarmic = parser.apply(Iterables org.jclouds.compute.domain.Image ubuntuKarmic = parser.apply(Iterables.get(result, 2));
.get(result, 2));
assertEquals(ubuntuKarmic.getArchitecture(), assertEquals(ubuntuKarmic.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32);
assertEquals(ubuntuKarmic.getDescription(), assertEquals(ubuntuKarmic.getDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2"); assertEquals(ubuntuKarmic.getProviderId(), "ami-bb709dd2");
@ -105,178 +92,128 @@ public class ImageParserTest extends BaseEC2HandlerTest {
assertEquals(ubuntuKarmic.getOsDescription(), assertEquals(ubuntuKarmic.getOsDescription(),
"ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml"); "ubuntu-images-us/ubuntu-karmic-9.10-i386-server-20100121.manifest.xml");
assertEquals(ubuntuKarmic.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuKarmic.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap assertEquals(ubuntuKarmic.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuKarmic.getVersion(), "20100121"); assertEquals(ubuntuKarmic.getVersion(), "20100121");
// should skip testing image // should skip testing image
assert parser.apply(Iterables.get(result, 3)) == null; assert parser.apply(Iterables.get(result, 3)) == null;
org.jclouds.compute.domain.Image alesticHardy = parser.apply(Iterables org.jclouds.compute.domain.Image alesticHardy = parser.apply(Iterables.get(result, 4));
.get(result, 4));
assertEquals(alesticHardy.getArchitecture(), assertEquals(alesticHardy.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32); assertEquals(alesticHardy.getDescription(), "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
assertEquals(alesticHardy.getDescription(),
"alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
assertEquals(alesticHardy.getProviderId(), "ami-c0fa1ea9"); assertEquals(alesticHardy.getProviderId(), "ami-c0fa1ea9");
assertEquals(alesticHardy.getLocation(), defaultLocation); assertEquals(alesticHardy.getLocation(), defaultLocation);
assertEquals(alesticHardy.getName(), "8.04"); assertEquals(alesticHardy.getName(), "8.04");
assertEquals(alesticHardy.getOsDescription(), assertEquals(alesticHardy.getOsDescription(), "alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
"alestic/ubuntu-8.04-hardy-base-20080905.manifest.xml");
assertEquals(alesticHardy.getOsFamily(), OsFamily.UBUNTU); assertEquals(alesticHardy.getOsFamily(), OsFamily.UBUNTU);
assertEquals(alesticHardy.getUserMetadata(), ImmutableMap assertEquals(alesticHardy.getUserMetadata(), ImmutableMap.<String, String> of("owner", "063491364108"));
.<String, String> of("owner", "063491364108"));
assertEquals(alesticHardy.getVersion(), "20080905"); assertEquals(alesticHardy.getVersion(), "20080905");
org.jclouds.compute.domain.Image ubuntuLucid = parser.apply(Iterables org.jclouds.compute.domain.Image ubuntuLucid = parser.apply(Iterables.get(result, 5));
.get(result, 5));
assertEquals(ubuntuLucid.getArchitecture(), assertEquals(ubuntuLucid.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32); assertEquals(ubuntuLucid.getDescription(),
assertEquals(
ubuntuLucid.getDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680"); assertEquals(ubuntuLucid.getProviderId(), "ami-c597c680");
assertEquals(ubuntuLucid.getLocation(), defaultLocation); assertEquals(ubuntuLucid.getLocation(), defaultLocation);
assertEquals(ubuntuLucid.getName(), "10.04"); assertEquals(ubuntuLucid.getName(), "10.04");
assertEquals( assertEquals(ubuntuLucid.getOsDescription(),
ubuntuLucid.getOsDescription(),
"ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml"); "ubuntu-images-us-west-1/ubuntu-lucid-10.04-i386-server-20100427.1.manifest.xml");
assertEquals(ubuntuLucid.getOsFamily(), OsFamily.UBUNTU); assertEquals(ubuntuLucid.getOsFamily(), OsFamily.UBUNTU);
assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap assertEquals(ubuntuLucid.getUserMetadata(), ImmutableMap.<String, String> of("owner", "099720109477"));
.<String, String> of("owner", "099720109477"));
assertEquals(ubuntuLucid.getVersion(), "20100427.1"); assertEquals(ubuntuLucid.getVersion(), "20100427.1");
// should skip kernel // should skip kernel
assert parser.apply(Iterables.get(result, 6)) == null; assert parser.apply(Iterables.get(result, 6)) == null;
} }
private Location defaultLocation = new LocationImpl(LocationScope.REGION, private Location defaultLocation = new LocationImpl(LocationScope.REGION, "us-east-1", "us-east-1", null);
"us-east-1", "us-east-1", null);
public void testParseVostokImage() { public void testParseVostokImage() {
InputStream is = getClass().getResourceAsStream("/ec2/vostok.xml"); InputStream is = getClass().getResourceAsStream("/ec2/vostok.xml");
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
ImageParser parser = new ImageParser( ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet
new EC2PopulateDefaultLoginCredentialsForImageStrategy(), .<Location> of(defaultLocation), defaultLocation);
ImmutableSet.<Location> of(defaultLocation), defaultLocation);
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
result, 0));
assertEquals(image.getArchitecture(), assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_32);
org.jclouds.compute.domain.Architecture.X86_32); assertEquals(image.getDescription(), "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
assertEquals(image.getDescription(),
"vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
assertEquals(image.getProviderId(), "ami-870de2ee"); assertEquals(image.getProviderId(), "ami-870de2ee");
assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), ""); assertEquals(image.getName(), "");
assertEquals(image.getOsDescription(), assertEquals(image.getOsDescription(), "vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
"vostok-builds/vostok-0.95-5622/vostok-0.95-5622.manifest.xml");
assertEquals(image.getOsFamily(), null); assertEquals(image.getOsFamily(), null);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of( assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "133804938231"));
"owner", "133804938231"));
assertEquals(image.getVersion(), ""); assertEquals(image.getVersion(), "");
} }
public void testParseRightScaleImage() { public void testParseRightScaleImage() {
InputStream is = getClass().getResourceAsStream( InputStream is = getClass().getResourceAsStream("/ec2/rightscale_images.xml");
"/ec2/rightscale_images.xml");
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
ImageParser parser = new ImageParser( ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet
new EC2PopulateDefaultLoginCredentialsForImageStrategy(), .<Location> of(defaultLocation), defaultLocation);
ImmutableSet.<Location> of(defaultLocation), defaultLocation);
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
result, 0));
assertEquals(image.getArchitecture(), assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64);
org.jclouds.compute.domain.Architecture.X86_64); assertEquals(image.getDescription(), "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
assertEquals(image.getDescription(),
"rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
assertEquals(image.getProviderId(), "ami-ccb35ea5"); assertEquals(image.getProviderId(), "ami-ccb35ea5");
assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), "5.4"); assertEquals(image.getName(), "5.4");
assertEquals(image.getOsDescription(), assertEquals(image.getOsDescription(), "rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
"rightscale-us-east/CentOS_5.4_x64_v4.4.10.manifest.xml");
assertEquals(image.getOsFamily(), OsFamily.CENTOS); assertEquals(image.getOsFamily(), OsFamily.CENTOS);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of( assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "411009282317"));
"owner", "411009282317"));
assertEquals(image.getVersion(), "4.4.10"); assertEquals(image.getVersion(), "4.4.10");
image = parser.apply(Iterables.get(result, 1)); image = parser.apply(Iterables.get(result, 1));
assertEquals(image.getArchitecture(), assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64);
org.jclouds.compute.domain.Architecture.X86_64); assertEquals(image.getDescription(), "RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
assertEquals(image.getDescription(),
"RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
assertEquals(image.getProviderId(), "ami-c19db6b5"); assertEquals(image.getProviderId(), "ami-c19db6b5");
assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), "9.10"); assertEquals(image.getName(), "9.10");
assertEquals(image.getOsDescription(), assertEquals(image.getOsDescription(), "411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
"411009282317/RightImage_Ubuntu_9.10_x64_v4.5.3_EBS_Alpha");
assertEquals(image.getOsFamily(), OsFamily.UBUNTU); assertEquals(image.getOsFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of( assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "411009282317"));
"owner", "411009282317"));
assertEquals(image.getVersion(), "4.5.3_EBS_Alpha"); assertEquals(image.getVersion(), "4.5.3_EBS_Alpha");
} }
public void testParseEucalyptusImage() { public void testParseEucalyptusImage() {
InputStream is = getClass().getResourceAsStream( InputStream is = getClass().getResourceAsStream("/ec2/eucalyptus_images.xml");
"/ec2/eucalyptus_images.xml");
Set<Image> result = parseImages(is); Set<Image> result = parseImages(is);
assertEquals(result.size(), 11); assertEquals(result.size(), 4);
ImageParser parser = new ImageParser( ImageParser parser = new ImageParser(new EC2PopulateDefaultLoginCredentialsForImageStrategy(), ImmutableSet
new EC2PopulateDefaultLoginCredentialsForImageStrategy(), .<Location> of(defaultLocation), defaultLocation);
ImmutableSet.<Location> of(defaultLocation), defaultLocation);
org.jclouds.compute.domain.Image image = parser.apply(Iterables.get( org.jclouds.compute.domain.Image image = parser.apply(Iterables.get(result, 0));
result, 0));
assertEquals(image.getArchitecture(), assertEquals(image.getArchitecture(), org.jclouds.compute.domain.Architecture.X86_64);
org.jclouds.compute.domain.Architecture.X86_64); assertEquals(image.getDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
assertEquals(image.getDescription(),
"centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
assertEquals(image.getProviderId(), "emi-9ACB1363"); assertEquals(image.getProviderId(), "emi-9ACB1363");
assertEquals(image.getLocation(), defaultLocation); assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), "5.3"); assertEquals(image.getName(), "5.3");
assertEquals(image.getOsDescription(), assertEquals(image.getOsDescription(), "centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
"centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml");
assertEquals(image.getOsFamily(), OsFamily.CENTOS); assertEquals(image.getOsFamily(), OsFamily.CENTOS);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of( assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of("owner", "admin"));
"owner", "admin"));
assertEquals(image.getVersion(), ""); assertEquals(image.getVersion(), "");
image = parser.apply(Iterables.get(result, 6)); // should skip test images
assertEquals(image.getDescription(), image = parser.apply(Iterables.get(result, 3));
"Lean/ubuntu.9-04.x86-64.img.manifest.xml"); assertEquals(image, null);
assertEquals(image.getArchitecture(),
org.jclouds.compute.domain.Architecture.X86_64);
assertEquals(image.getDescription(),
"Lean/ubuntu.9-04.x86-64.img.manifest.xml");
assertEquals(image.getProviderId(), "emi-CBEA100C");
assertEquals(image.getLocation(), defaultLocation);
assertEquals(image.getName(), "9.04");
assertEquals(image.getOsDescription(),
"Lean/ubuntu.9-04.x86-64.img.manifest.xml");
assertEquals(image.getOsFamily(), OsFamily.UBUNTU);
assertEquals(image.getUserMetadata(), ImmutableMap.<String, String> of(
"owner", "mashaobing1"));
assertEquals(image.getVersion(), "");
} }
private Set<Image> parseImages(InputStream is) { private Set<Image> parseImages(InputStream is) {
DescribeImagesResponseHandler handler = injector DescribeImagesResponseHandler handler = injector.getInstance(DescribeImagesResponseHandler.class);
.getInstance(DescribeImagesResponseHandler.class);
addDefaultRegionToHandler(handler); addDefaultRegionToHandler(handler);
Set<Image> result = factory.create(handler).parse(is); Set<Image> result = factory.create(handler).parse(is);
return result; return result;

View File

@ -64,8 +64,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
RegionAndName knownRegionAndName = new RegionAndName("region", "ami"); RegionAndName knownRegionAndName = new RegionAndName("region", "ami");
Image knownImage = createNiceMock(Image.class); Image knownImage = createNiceMock(Image.class);
ConcurrentMap<RegionAndName, Image> imageMap = new MapMaker() ConcurrentMap<RegionAndName, Image> imageMap = new MapMaker().makeComputingMap(new Function<RegionAndName, Image>() {
.makeComputingMap(new Function<RegionAndName, Image>() {
@Override @Override
public Image apply(RegionAndName from) { public Image apply(RegionAndName from) {
return from.equals(knownRegionAndName) ? knownImage : null; return from.equals(knownRegionAndName) ? knownImage : null;
@ -84,56 +83,89 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
} }
@Override @Override
protected EC2TemplateBuilderImpl createTemplateBuilder( protected EC2TemplateBuilderImpl createTemplateBuilder(Provider<Set<? extends Location>> locations,
Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images, Provider<Set<? extends Size>> sizes, Location defaultLocation,
Provider<Set<? extends Image>> images, Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
Provider<Set<? extends Size>> sizes, Location defaultLocation, return new EC2TemplateBuilderImpl(locations, images, sizes, defaultLocation, optionsProvider,
Provider<TemplateOptions> optionsProvider, templateBuilderProvider, imageMap);
Provider<TemplateBuilder> templateBuilderProvider) {
return new EC2TemplateBuilderImpl(locations, images, sizes,
defaultLocation, optionsProvider, templateBuilderProvider, imageMap);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test @Test
public void testParseOnDemand() { public void testParseOnDemand() {
Location location = new LocationImpl(LocationScope.REGION, "region", Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
"region", null);
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1",
Provider<Set<? extends Size>> sizes = Providers "1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any())));
.<Set<? extends Size>> of(ImmutableSet
.<Size> of(new SizeImpl("1", "1", "region/1", location, null,
ImmutableMap.<String, String> of(), 1, 1, 1,
ImagePredicates.any())));
Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateOptions defaultOptions = createMock(TemplateOptions.class); TemplateOptions defaultOptions = createMock(TemplateOptions.class);
knownImage = createMock(Image.class); knownImage = createMock(Image.class);
expect(defaultLocation.getId()).andReturn("region");
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32);
expect(knownImage.getId()).andReturn("region/ami");
expect(knownImage.getLocation()).andReturn(location).atLeastOnce();
expect(knownImage.getOsFamily()).andReturn(null);
expect(knownImage.getName()).andReturn(null);
expect(knownImage.getDescription()).andReturn(null);
expect(knownImage.getOsDescription()).andReturn(null);
expect(knownImage.getVersion()).andReturn(null);
expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce();
replay(knownImage); replay(knownImage);
replay(defaultOptions); replay(defaultOptions);
replay(defaultLocation);
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
assertEquals(template.imageId("ami").build().getImage(), knownImage); assertEquals(template.imageId("region/ami").build().getImage(), knownImage);
verify(knownImage); verify(knownImage);
verify(defaultOptions); verify(defaultOptions);
verify(defaultLocation); verify(optionsProvider);
verify(templateBuilderProvider);
}
@SuppressWarnings("unchecked")
@Test
public void testParseOnDemandWithoutRegionEncodedIntoId() {
Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Location> of(location));
Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1",
"1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any())));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateOptions defaultOptions = createMock(TemplateOptions.class);
knownImage = createMock(Image.class);
expect(optionsProvider.get()).andReturn(defaultOptions);
replay(knownImage);
replay(defaultOptions);
replay(optionsProvider);
replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, location, optionsProvider,
templateBuilderProvider);
try {
template.imageId("ami").build();
assert false;
} catch (IllegalArgumentException e) {
}
verify(knownImage);
verify(defaultOptions);
verify(optionsProvider); verify(optionsProvider);
verify(templateBuilderProvider); verify(templateBuilderProvider);
} }
@ -141,18 +173,13 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Test(expectedExceptions = NoSuchElementException.class) @Test(expectedExceptions = NoSuchElementException.class)
public void testParseOnDemandNotFound() { public void testParseOnDemandNotFound() {
Location location = new LocationImpl(LocationScope.REGION, "region", Location location = new LocationImpl(LocationScope.REGION, "region", "region", null);
"region", null);
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet.<Location> of(location)); .<Location> of(location));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(new SizeImpl("1",
Provider<Set<? extends Size>> sizes = Providers "1", "region/1", location, null, ImmutableMap.<String, String> of(), 1, 1, 1, ImagePredicates.any())));
.<Set<? extends Size>> of(ImmutableSet
.<Size> of(new SizeImpl("1", "1", "region/1", location, null,
ImmutableMap.<String, String> of(), 1, 1, 1,
ImagePredicates.any())));
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
@ -162,8 +189,7 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
expect(defaultLocation.getId()).andReturn("region"); expect(defaultLocation.getId()).andReturn("region");
expect(optionsProvider.get()).andReturn(defaultOptions); expect(optionsProvider.get()).andReturn(defaultOptions);
expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32) expect(knownImage.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce();
.atLeastOnce();
replay(knownImage); replay(knownImage);
replay(defaultOptions); replay(defaultOptions);
@ -171,10 +197,10 @@ public class EC2TemplateBuilderImplTest extends TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
assertEquals(template.imageId("bad").build().getImage(), knownImage); assertEquals(template.imageId("region/bad").build().getImage(), knownImage);
verify(knownImage); verify(knownImage);
verify(defaultOptions); verify(defaultOptions);

View File

@ -51,15 +51,13 @@ import com.google.inject.TypeLiteral;
public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> { public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException { public void testCreateImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, String.class, String.class,
String.class, String.class, Array.newInstance(CreateImageOptions.class, 0) Array.newInstance(CreateImageOptions.class, 0).getClass());
.getClass());
HttpRequest request = processor.createRequest(method, null, "name", "instanceId"); HttpRequest request = processor.createRequest(method, null, "name", "instanceId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name",
"Version=2010-06-15&Action=CreateImage&InstanceId=instanceId&Name=name",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class);
@ -68,13 +66,11 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, public void testCreateImageOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, String.class, String.class,
Method method = AMIAsyncClient.class.getMethod("createImageInRegion", String.class, Array.newInstance(CreateImageOptions.class, 0).getClass());
String.class, String.class, Array.newInstance(CreateImageOptions.class, 0) HttpRequest request = processor.createRequest(method, null, "name", "instanceId", new CreateImageOptions()
.getClass()); .withDescription("description").noReboot());
HttpRequest request = processor.createRequest(method, null, "name", "instanceId",
new CreateImageOptions().withDescription("description").noReboot());
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -91,14 +87,14 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
} }
public void testDescribeImages() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeImages() throws SecurityException, NoSuchMethodException, IOException {
Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array.newInstance(
.newInstance(DescribeImagesOptions.class, 0).getClass()); DescribeImagesOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeImages", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeImages", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
filter.filter(request); filter.filter(request);
assertPayloadEquals( assertPayloadEquals(
request, request,
@ -112,12 +108,11 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, public void testDescribeImagesOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array.newInstance(
Method method = AMIAsyncClient.class.getMethod("describeImagesInRegion", String.class, Array DescribeImagesOptions.class, 0).getClass());
.newInstance(DescribeImagesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, executableBy("me").ownedBy("fred", "nancy").imageIds(
HttpRequest request = processor.createRequest(method, null, executableBy("me").ownedBy( "1", "2"));
"fred", "nancy").imageIds("1", "2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -134,8 +129,7 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
} }
public void testDeregisterImage() throws SecurityException, NoSuchMethodException, IOException { public void testDeregisterImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = AMIAsyncClient.class.getMethod("deregisterImageInRegion", String.class, Method method = AMIAsyncClient.class.getMethod("deregisterImageInRegion", String.class, String.class);
String.class);
HttpRequest request = processor.createRequest(method, null, "imageId"); HttpRequest request = processor.createRequest(method, null, "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -150,17 +144,14 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, public void testRegisterImageFromManifest() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, String.class,
Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, Array.newInstance(RegisterImageOptions.class, 0).getClass());
String.class, String.class, String.class, Array.newInstance(
RegisterImageOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest"); HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name",
"Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, ImageIdHandler.class); assertSaxResponseParserClassEquals(method, ImageIdHandler.class);
@ -169,18 +160,15 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRegisterImageFromManifestOptions() throws SecurityException, public void testRegisterImageFromManifestOptions() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, String.class,
Method method = AMIAsyncClient.class.getMethod("registerImageFromManifestInRegion", String.class, Array.newInstance(RegisterImageOptions.class, 0).getClass());
String.class, String.class, String.class, Array.newInstance( HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest", new RegisterImageOptions()
RegisterImageOptions.class, 0).getClass()); .withDescription("description"));
HttpRequest request = processor.createRequest(method, null, "name", "pathToManifest",
new RegisterImageOptions().withDescription("description"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name&Description=description", "Version=2010-06-15&Action=RegisterImage&ImageLocation=pathToManifest&Name=name&Description=description",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -191,11 +179,9 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, public void testRegisterImageBackedByEBS() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class, String.class, Array.newInstance(RegisterImageBackedByEbsOptions.class, 0).getClass());
String.class, String.class, String.class, Array.newInstance(
RegisterImageBackedByEbsOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId"); HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -211,15 +197,12 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRegisterImageBackedByEBSOptions() throws SecurityException, public void testRegisterImageBackedByEBSOptions() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("registerUnixImageBackedByEbsInRegion", String.class, String.class, Array.newInstance(RegisterImageBackedByEbsOptions.class, 0).getClass());
String.class, String.class, String.class, Array.newInstance(
RegisterImageBackedByEbsOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId", HttpRequest request = processor.createRequest(method, null, "imageName", "snapshotId",
new RegisterImageBackedByEbsOptions().withDescription("description") new RegisterImageBackedByEbsOptions().withDescription("description").addBlockDeviceFromSnapshot(
.addBlockDeviceFromSnapshot("/dev/device", null, "snapshot") "/dev/device", null, "snapshot").addNewBlockDevice("/dev/newdevice", "newblock", 100));
.addNewBlockDevice("/dev/newdevice", "newblock", 100));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -235,16 +218,13 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testGetProductCodesForImage() throws SecurityException, NoSuchMethodException, public void testGetProductCodesForImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("getProductCodesForImageInRegion", String.class, String.class);
Method method = AMIAsyncClient.class.getMethod("getProductCodesForImageInRegion",
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "imageId"); HttpRequest request = processor.createRequest(method, null, "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeImageAttribute&Attribute=productCodes&ImageId=imageId", "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=productCodes&ImageId=imageId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -255,16 +235,14 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testGetBlockDeviceMappingsForImage() throws SecurityException, public void testGetBlockDeviceMappingsForImage() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = AMIAsyncClient.class.getMethod("getBlockDeviceMappingsForImageInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("getBlockDeviceMappingsForImageInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "imageId"); HttpRequest request = processor.createRequest(method, null, "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeImageAttribute&Attribute=blockDeviceMapping&ImageId=imageId", "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=blockDeviceMapping&ImageId=imageId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -275,16 +253,13 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, public void testGetLaunchPermissionForImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("getLaunchPermissionForImageInRegion", String.class, String.class);
Method method = AMIAsyncClient.class.getMethod("getLaunchPermissionForImageInRegion",
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "imageId"); HttpRequest request = processor.createRequest(method, null, "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeImageAttribute&Attribute=launchPermission&ImageId=imageId", "Version=2010-06-15&Action=DescribeImageAttribute&Attribute=launchPermission&ImageId=imageId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -295,12 +270,11 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, public void testAddLaunchPermissionsToImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("addLaunchPermissionsToImageInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("addLaunchPermissionsToImageInRegion", Iterable.class, Iterable.class, String.class);
String.class, Iterable.class, Iterable.class, String.class); HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList
HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), .of("all"), "imageId");
ImmutableList.of("all"), "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -321,12 +295,11 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRemoveLaunchPermissionsFromImage() throws SecurityException, public void testRemoveLaunchPermissionsFromImage() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = AMIAsyncClient.class.getMethod("removeLaunchPermissionsFromImageInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("removeLaunchPermissionsFromImageInRegion", Iterable.class, Iterable.class, String.class);
String.class, Iterable.class, Iterable.class, String.class); HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList
HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), .of("all"), "imageId");
ImmutableList.of("all"), "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -341,16 +314,14 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, public void testResetLaunchPermissionsOnImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("resetLaunchPermissionsOnImageInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("resetLaunchPermissionsOnImageInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "imageId"); HttpRequest request = processor.createRequest(method, null, "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ResetImageAttribute&Attribute=launchPermission&ImageId=imageId", "Version=2010-06-15&Action=ResetImageAttribute&Attribute=launchPermission&ImageId=imageId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -360,12 +331,10 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testAddProductCodesToImage() throws SecurityException, NoSuchMethodException, public void testAddProductCodesToImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("addProductCodesToImageInRegion", String.class, Iterable.class,
Method method = AMIAsyncClient.class.getMethod("addProductCodesToImageInRegion", String.class);
String.class, Iterable.class, String.class); HttpRequest request = processor.createRequest(method, null, ImmutableList.of("code1", "code2"), "imageId");
HttpRequest request = processor.createRequest(method, null, ImmutableList
.of("code1", "code2"), "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -381,12 +350,10 @@ public class AMIAsyncClientTest extends BaseEC2AsyncClientTest<AMIAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testRemoveProductCodesFromImage() throws SecurityException, NoSuchMethodException, public void testRemoveProductCodesFromImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AMIAsyncClient.class.getMethod("removeProductCodesFromImageInRegion", String.class,
Method method = AMIAsyncClient.class.getMethod("removeProductCodesFromImageInRegion", Iterable.class, String.class);
String.class, Iterable.class, String.class); HttpRequest request = processor.createRequest(method, null, ImmutableList.of("code1", "code2"), "imageId");
HttpRequest request = processor.createRequest(method, null, ImmutableList
.of("code1", "code2"), "imageId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");

View File

@ -47,11 +47,9 @@ import com.google.inject.TypeLiteral;
public class AvailabilityZoneAndRegionAsyncClientTest extends public class AvailabilityZoneAndRegionAsyncClientTest extends
BaseEC2AsyncClientTest<AvailabilityZoneAndRegionAsyncClient> { BaseEC2AsyncClientTest<AvailabilityZoneAndRegionAsyncClient> {
public void testDescribeAvailabilityZones() throws SecurityException, NoSuchMethodException, public void testDescribeAvailabilityZones() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeAvailabilityZonesInRegion",
Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod( String.class, Array.newInstance(DescribeAvailabilityZonesOptions.class, 0).getClass());
"describeAvailabilityZonesInRegion", String.class, Array.newInstance(
DescribeAvailabilityZonesOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, Region.US_WEST_1); HttpRequest request = processor.createRequest(method, Region.US_WEST_1);
assertRequestLineEquals(request, "POST https://ec2.us-west-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-west-1.amazonaws.com/ HTTP/1.1");
@ -66,18 +64,15 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testDescribeAvailabilityZonesOptions() throws SecurityException, public void testDescribeAvailabilityZonesOptions() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeAvailabilityZonesInRegion",
Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod( String.class, Array.newInstance(DescribeAvailabilityZonesOptions.class, 0).getClass());
"describeAvailabilityZonesInRegion", String.class, Array.newInstance(
DescribeAvailabilityZonesOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, Region.US_EAST_1, availabilityZones( HttpRequest request = processor.createRequest(method, Region.US_EAST_1, availabilityZones(
AvailabilityZone.US_EAST_1A, AvailabilityZone.US_EAST_1B)); AvailabilityZone.US_EAST_1A, AvailabilityZone.US_EAST_1B));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeAvailabilityZones&ZoneName.1=us-east-1a&ZoneName.2=us-east-1b", "Version=2010-06-15&Action=DescribeAvailabilityZones&ZoneName.1=us-east-1a&ZoneName.2=us-east-1b",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -89,14 +84,14 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends
} }
public void testDescribeRegions() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeRegions() throws SecurityException, NoSuchMethodException, IOException {
Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array.newInstance(
.newInstance(DescribeRegionsOptions.class, 0).getClass()); DescribeRegionsOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeRegions", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeRegions", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class); assertSaxResponseParserClassEquals(method, DescribeRegionsResponseHandler.class);
@ -105,17 +100,14 @@ public class AvailabilityZoneAndRegionAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testDescribeRegionsOptions() throws SecurityException, NoSuchMethodException, public void testDescribeRegionsOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array.newInstance(
Method method = AvailabilityZoneAndRegionAsyncClient.class.getMethod("describeRegions", Array DescribeRegionsOptions.class, 0).getClass());
.newInstance(DescribeRegionsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, regions(Region.US_EAST_1, Region.US_WEST_1));
HttpRequest request = processor.createRequest(method, regions(Region.US_EAST_1,
Region.US_WEST_1));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeRegions&RegionName.1=us-east-1&RegionName.2=us-west-1", "Version=2010-06-15&Action=DescribeRegions&RegionName.1=us-east-1&RegionName.2=us-west-1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);

View File

@ -64,9 +64,8 @@ public abstract class BaseEC2AsyncClientTest<T> extends RestClientTest<T> {
@Override @Override
protected Map<String, URI> provideRegions(Injector client) { protected Map<String, URI> provideRegions(Injector client) {
return ImmutableMap.<String, URI> of(Region.EU_WEST_1, URI return ImmutableMap.<String, URI> of(Region.EU_WEST_1, URI.create("https://ec2.eu-west-1.amazonaws.com"),
.create("https://ec2.eu-west-1.amazonaws.com"), Region.US_EAST_1, URI Region.US_EAST_1, URI.create("https://ec2.us-east-1.amazonaws.com"), Region.US_WEST_1, URI
.create("https://ec2.us-east-1.amazonaws.com"), Region.US_WEST_1, URI
.create("https://ec2.us-west-1.amazonaws.com")); .create("https://ec2.us-west-1.amazonaws.com"));
} }
@ -103,8 +102,7 @@ public abstract class BaseEC2AsyncClientTest<T> extends RestClientTest<T> {
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("ec2", "identity", "credential", return new RestContextFactory().createContextSpec("ec2", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -51,18 +51,16 @@ import com.google.inject.TypeLiteral;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "ec2.ElasticBlockStoreAsyncClientTest") @Test(groups = "unit", testName = "ec2.ElasticBlockStoreAsyncClientTest")
public class ElasticBlockStoreAsyncClientTest extends public class ElasticBlockStoreAsyncClientTest extends BaseEC2AsyncClientTest<ElasticBlockStoreAsyncClient> {
BaseEC2AsyncClientTest<ElasticBlockStoreAsyncClient> {
public void testCreateVolume() throws SecurityException, NoSuchMethodException, IOException { public void testCreateVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod( Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeInAvailabilityZone", String.class,
"createVolumeInAvailabilityZone", String.class, int.class); int.class);
HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 20); HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 20);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&Size=20",
"Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&Size=20",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -72,17 +70,14 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testCreateVolumeFromSnapShot() throws SecurityException, NoSuchMethodException, public void testCreateVolumeFromSnapShot() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeFromSnapshotInAvailabilityZone",
Method method = ElasticBlockStoreAsyncClient.class.getMethod( String.class, String.class);
"createVolumeFromSnapshotInAvailabilityZone", String.class, String.class); HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, "snapshotId");
HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A,
"snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId", "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -93,17 +88,14 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testCreateVolumeFromSnapShotWithSize() throws SecurityException, public void testCreateVolumeFromSnapShotWithSize() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("createVolumeFromSnapshotInAvailabilityZone",
Method method = ElasticBlockStoreAsyncClient.class.getMethod( String.class, int.class, String.class);
"createVolumeFromSnapshotInAvailabilityZone", String.class, int.class, String.class); HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 15, "snapshotId");
HttpRequest request = processor.createRequest(method, AvailabilityZone.US_EAST_1A, 15,
"snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId&Size=15", "Version=2010-06-15&Action=CreateVolume&AvailabilityZone=us-east-1a&SnapshotId=snapshotId&Size=15",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -115,8 +107,7 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("deleteVolumeInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("deleteVolumeInRegion", String.class, String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "id"); HttpRequest request = processor.createRequest(method, null, "id");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -132,14 +123,14 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testDescribeVolumes() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeVolumes() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", String.class, Array
String.class, Array.newInstance(String.class, 0).getClass()); .newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeVolumes", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeVolumes", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class); assertSaxResponseParserClassEquals(method, DescribeVolumesResponseHandler.class);
@ -148,16 +139,14 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testDescribeVolumesArgs() throws SecurityException, NoSuchMethodException, public void testDescribeVolumesArgs() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", String.class, Array
Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeVolumesInRegion", .newInstance(String.class, 0).getClass());
String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeVolumes&VolumeId.1=1&VolumeId.2=2",
"Version=2010-06-15&Action=DescribeVolumes&VolumeId.1=1&VolumeId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -168,14 +157,13 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testAttachVolume() throws SecurityException, NoSuchMethodException, IOException { public void testAttachVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("attachVolumeInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("attachVolumeInRegion", String.class, String.class,
String.class, String.class, String.class, String.class); String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "id", "instanceId", "/device"); HttpRequest request = processor.createRequest(method, null, "id", "instanceId", "/device");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=AttachVolume&InstanceId=instanceId&VolumeId=id&Device=%2Fdevice", "Version=2010-06-15&Action=AttachVolume&InstanceId=instanceId&VolumeId=id&Device=%2Fdevice",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -187,15 +175,13 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testDetachVolume() throws SecurityException, NoSuchMethodException, IOException { public void testDetachVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", String.class, String.class,
String.class, String.class, boolean.class, Array.newInstance( boolean.class, Array.newInstance(DetachVolumeOptions.class, 0).getClass());
DetachVolumeOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "id", false); HttpRequest request = processor.createRequest(method, null, "id", false);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DetachVolume&Force=false&VolumeId=id",
"Version=2010-06-15&Action=DetachVolume&Force=false&VolumeId=id",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -205,18 +191,15 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testDetachVolumeOptions() throws SecurityException, NoSuchMethodException, public void testDetachVolumeOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", String.class, String.class,
Method method = ElasticBlockStoreAsyncClient.class.getMethod("detachVolumeInRegion", boolean.class, Array.newInstance(DetachVolumeOptions.class, 0).getClass());
String.class, String.class, boolean.class, Array.newInstance( HttpRequest request = processor.createRequest(method, null, "id", true, fromInstance("instanceId").fromDevice(
DetachVolumeOptions.class, 0).getClass()); "/device"));
HttpRequest request = processor.createRequest(method, null, "id", true, fromInstance(
"instanceId").fromDevice("/device"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DetachVolume&Force=true&VolumeId=id&InstanceId=instanceId&Device=%2Fdevice", "Version=2010-06-15&Action=DetachVolume&Force=true&VolumeId=id&InstanceId=instanceId&Device=%2Fdevice",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -228,9 +211,8 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testCreateSnapshot() throws SecurityException, NoSuchMethodException, IOException { public void testCreateSnapshot() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", String.class,
String.class, String.class, Array.newInstance(CreateSnapshotOptions.class, 0) String.class, Array.newInstance(CreateSnapshotOptions.class, 0).getClass());
.getClass());
HttpRequest request = processor.createRequest(method, null, "volumeId"); HttpRequest request = processor.createRequest(method, null, "volumeId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -245,18 +227,15 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testCreateSnapshotOptions() throws SecurityException, NoSuchMethodException, public void testCreateSnapshotOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", String.class,
Method method = ElasticBlockStoreAsyncClient.class.getMethod("createSnapshotInRegion", String.class, Array.newInstance(CreateSnapshotOptions.class, 0).getClass());
String.class, String.class, Array.newInstance(CreateSnapshotOptions.class, 0) HttpRequest request = processor.createRequest(method, null, "volumeId", CreateSnapshotOptions.Builder
.getClass()); .withDescription("description"));
HttpRequest request = processor.createRequest(method, null, "volumeId",
CreateSnapshotOptions.Builder.withDescription("description"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=CreateSnapshot&VolumeId=volumeId&Description=description", "Version=2010-06-15&Action=CreateSnapshot&VolumeId=volumeId&Description=description",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -268,14 +247,14 @@ public class ElasticBlockStoreAsyncClientTest extends
} }
public void testDescribeSnapshots() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeSnapshots() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", String.class, Array
String.class, Array.newInstance(DescribeSnapshotsOptions.class, 0).getClass()); .newInstance(DescribeSnapshotsOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeSnapshots", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeSnapshots", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class); assertSaxResponseParserClassEquals(method, DescribeSnapshotsResponseHandler.class);
@ -284,12 +263,11 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testDescribeSnapshotsArgs() throws SecurityException, NoSuchMethodException, public void testDescribeSnapshotsArgs() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", String.class, Array
Method method = ElasticBlockStoreAsyncClient.class.getMethod("describeSnapshotsInRegion", .newInstance(DescribeSnapshotsOptions.class, 0).getClass());
String.class, Array.newInstance(DescribeSnapshotsOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, ownedBy("o1", "o2").restorableBy("r1", "r2")
HttpRequest request = processor.createRequest(method, null, ownedBy("o1", "o2").restorableBy( .snapshotIds("s1", "s2"));
"r1", "r2").snapshotIds("s1", "s2"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -305,10 +283,9 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testGetCreateVolumePermissionForSnapshot() throws SecurityException, public void testGetCreateVolumePermissionForSnapshot() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("getCreateVolumePermissionForSnapshotInRegion",
Method method = ElasticBlockStoreAsyncClient.class.getMethod( String.class, String.class);
"getCreateVolumePermissionForSnapshotInRegion", String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "snapshotId"); HttpRequest request = processor.createRequest(method, null, "snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -325,13 +302,11 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testAddCreateVolumePermissionsToSnapshot() throws SecurityException, public void testAddCreateVolumePermissionsToSnapshot() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = ElasticBlockStoreAsyncClient.class.getMethod("addCreateVolumePermissionsToSnapshotInRegion",
Method method = ElasticBlockStoreAsyncClient.class.getMethod( String.class, Iterable.class, Iterable.class, String.class);
"addCreateVolumePermissionsToSnapshotInRegion", String.class, Iterable.class, HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList
Iterable.class, String.class); .of("all"), "snapshotId");
HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"),
ImmutableList.of("all"), "snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -347,13 +322,12 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testRemoveCreateVolumePermissionsFromSnapshot() throws SecurityException, public void testRemoveCreateVolumePermissionsFromSnapshot() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod( Method method = ElasticBlockStoreAsyncClient.class.getMethod("removeCreateVolumePermissionsFromSnapshotInRegion",
"removeCreateVolumePermissionsFromSnapshotInRegion", String.class, Iterable.class, String.class, Iterable.class, Iterable.class, String.class);
Iterable.class, String.class); HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), ImmutableList
HttpRequest request = processor.createRequest(method, null, ImmutableList.of("bob", "sue"), .of("all"), "snapshotId");
ImmutableList.of("all"), "snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -368,16 +342,15 @@ public class ElasticBlockStoreAsyncClientTest extends
checkFilters(request); checkFilters(request);
} }
public void testResetCreateVolumePermissionsOnSnapshot() throws SecurityException, public void testResetCreateVolumePermissionsOnSnapshot() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = ElasticBlockStoreAsyncClient.class.getMethod( Method method = ElasticBlockStoreAsyncClient.class.getMethod("resetCreateVolumePermissionsOnSnapshotInRegion",
"resetCreateVolumePermissionsOnSnapshotInRegion", String.class, String.class); String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "snapshotId"); HttpRequest request = processor.createRequest(method, null, "snapshotId");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ResetSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId", "Version=2010-06-15&Action=ResetSnapshotAttribute&Attribute=createVolumePermission&SnapshotId=snapshotId",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);

View File

@ -38,19 +38,16 @@ import com.google.inject.TypeLiteral;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Test(groups = "unit", testName = "ec2.ElasticIPAddressAsyncClientTest") @Test(groups = "unit", testName = "ec2.ElasticIPAddressAsyncClientTest")
public class ElasticIPAddressAsyncClientTest extends public class ElasticIPAddressAsyncClientTest extends BaseEC2AsyncClientTest<ElasticIPAddressAsyncClient> {
BaseEC2AsyncClientTest<ElasticIPAddressAsyncClient> {
public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, public void testDisassociateAddress() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = ElasticIPAddressAsyncClient.class.getMethod("disassociateAddressInRegion", String.class,
Method method = ElasticIPAddressAsyncClient.class.getMethod("disassociateAddressInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); HttpRequest request = processor.createRequest(method, null, "127.0.0.1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DisassociateAddress&PublicIp=127.0.0.1",
"Version=2010-06-15&Action=DisassociateAddress&PublicIp=127.0.0.1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -61,14 +58,13 @@ public class ElasticIPAddressAsyncClientTest extends
} }
public void testAssociateAddress() throws SecurityException, NoSuchMethodException, IOException { public void testAssociateAddress() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticIPAddressAsyncClient.class.getMethod("associateAddressInRegion", Method method = ElasticIPAddressAsyncClient.class.getMethod("associateAddressInRegion", String.class,
String.class, String.class, String.class); String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "127.0.0.1", "me"); HttpRequest request = processor.createRequest(method, null, "127.0.0.1", "me");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=AssociateAddress&InstanceId=me&PublicIp=127.0.0.1",
"Version=2010-06-15&Action=AssociateAddress&InstanceId=me&PublicIp=127.0.0.1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -79,8 +75,7 @@ public class ElasticIPAddressAsyncClientTest extends
} }
public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException { public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticIPAddressAsyncClient.class.getMethod("releaseAddressInRegion", Method method = ElasticIPAddressAsyncClient.class.getMethod("releaseAddressInRegion", String.class, String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); HttpRequest request = processor.createRequest(method, null, "127.0.0.1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -96,14 +91,13 @@ public class ElasticIPAddressAsyncClientTest extends
} }
public void testDescribeAddresses() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeAddresses() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticIPAddressAsyncClient.class.getMethod("describeAddressesInRegion", Method method = ElasticIPAddressAsyncClient.class.getMethod("describeAddressesInRegion", String.class, Array
String.class, Array.newInstance(String.class, 0).getClass()); .newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "127.0.0.1"); HttpRequest request = processor.createRequest(method, null, "127.0.0.1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeAddresses&PublicIp.1=127.0.0.1",
"Version=2010-06-15&Action=DescribeAddresses&PublicIp.1=127.0.0.1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -114,14 +108,13 @@ public class ElasticIPAddressAsyncClientTest extends
} }
public void testAllocateAddress() throws SecurityException, NoSuchMethodException, IOException { public void testAllocateAddress() throws SecurityException, NoSuchMethodException, IOException {
Method method = ElasticIPAddressAsyncClient.class.getMethod("allocateAddressInRegion", Method method = ElasticIPAddressAsyncClient.class.getMethod("allocateAddressInRegion", String.class);
String.class);
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=AllocateAddress", assertPayloadEquals(request, "Version=2010-06-15&Action=AllocateAddress", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, AllocateAddressResponseHandler.class); assertSaxResponseParserClassEquals(method, AllocateAddressResponseHandler.class);

View File

@ -54,13 +54,30 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit", testName = "ec2.InstanceAsyncClientTest") @Test(groups = "unit", testName = "ec2.InstanceAsyncClientTest")
public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyncClient> { public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyncClient> {
public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", String.class, Array.newInstance(
String.class, Array.newInstance(String.class, 0).getClass()); String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeInstances", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeInstances", "application/x-www-form-urlencoded",
false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testDescribeInstancesArgs() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", String.class, Array.newInstance(
String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -70,35 +87,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testDescribeInstancesArgs() throws SecurityException, NoSuchMethodException, public void testTerminateInstances() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("terminateInstancesInRegion", String.class, Array
Method method = InstanceAsyncClient.class.getMethod("describeInstancesInRegion", .newInstance(String.class, 0).getClass());
String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=TerminateInstances&InstanceId.1=1&InstanceId.2=2",
"Version=2010-06-15&Action=DescribeInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeInstancesResponseHandler.class);
assertExceptionParserClassEquals(method, null);
checkFilters(request);
}
public void testTerminateInstances() throws SecurityException, NoSuchMethodException,
IOException {
Method method = InstanceAsyncClient.class.getMethod("terminateInstancesInRegion",
String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request,
"Version=2010-06-15&Action=TerminateInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -109,15 +105,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
} }
public void testRunInstances() throws SecurityException, NoSuchMethodException, IOException { public void testRunInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("runInstancesInRegion", String.class, Method method = InstanceAsyncClient.class.getMethod("runInstancesInRegion", String.class, String.class,
String.class, String.class, int.class, int.class, Array.newInstance( String.class, int.class, int.class, Array.newInstance(RunInstancesOptions.class, 0).getClass());
RunInstancesOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, null, "ami-voo", 1, 1); HttpRequest request = processor.createRequest(method, null, null, "ami-voo", 1, 1);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=1",
"Version=2010-06-15&Action=RunInstances&ImageId=ami-voo&MinCount=1&MaxCount=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -127,14 +121,11 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testRunInstancesOptions() throws SecurityException, NoSuchMethodException, public void testRunInstancesOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("runInstancesInRegion", String.class, String.class,
Method method = InstanceAsyncClient.class.getMethod("runInstancesInRegion", String.class, String.class, int.class, int.class, Array.newInstance(RunInstancesOptions.class, 0).getClass());
String.class, String.class, int.class, int.class, Array.newInstance( HttpRequest request = processor.createRequest(method, Region.EU_WEST_1, AvailabilityZone.EU_WEST_1A, "ami-voo",
RunInstancesOptions.class, 0).getClass()); 1, 5, new RunInstancesOptions().withKernelId("kernelId").enableMonitoring().withSecurityGroups("group1",
HttpRequest request = processor.createRequest(method, Region.EU_WEST_1,
AvailabilityZone.EU_WEST_1A, "ami-voo", 1, 5, new RunInstancesOptions()
.withKernelId("kernelId").enableMonitoring().withSecurityGroups("group1",
"group2")); "group2"));
assertRequestLineEquals(request, "POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.eu-west-1.amazonaws.com/ HTTP/1.1");
@ -152,14 +143,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
} }
public void testStopInstances() throws SecurityException, NoSuchMethodException, IOException { public void testStopInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("stopInstancesInRegion", String.class, Method method = InstanceAsyncClient.class.getMethod("stopInstancesInRegion", String.class, boolean.class, Array
boolean.class, Array.newInstance(String.class, 0).getClass()); .newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, true, "1", "2"); HttpRequest request = processor.createRequest(method, null, true, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=StopInstances&Force=true&InstanceId.1=1&InstanceId.2=2",
"Version=2010-06-15&Action=StopInstances&Force=true&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -170,14 +160,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
} }
public void testRebootInstances() throws SecurityException, NoSuchMethodException, IOException { public void testRebootInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("rebootInstancesInRegion", String.class, Method method = InstanceAsyncClient.class.getMethod("rebootInstancesInRegion", String.class, Array.newInstance(
Array.newInstance(String.class, 0).getClass()); String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=RebootInstances&InstanceId.1=1&InstanceId.2=2",
"Version=2010-06-15&Action=RebootInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -188,14 +177,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
} }
public void testStartInstances() throws SecurityException, NoSuchMethodException, IOException { public void testStartInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod("startInstancesInRegion", String.class, Method method = InstanceAsyncClient.class.getMethod("startInstancesInRegion", String.class, Array.newInstance(
Array.newInstance(String.class, 0).getClass()); String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=StartInstances&InstanceId.1=1&InstanceId.2=2",
"Version=2010-06-15&Action=StartInstances&InstanceId.1=1&InstanceId.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -205,16 +193,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetUserDataForInstanceInRegion() throws SecurityException, public void testGetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("getUserDataForInstanceInRegion", String.class, String.class);
Method method = InstanceAsyncClient.class.getMethod("getUserDataForInstanceInRegion",
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=userData&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=userData&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -225,16 +210,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetRootDeviceNameForInstanceInRegion() throws SecurityException, public void testGetRootDeviceNameForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("getRootDeviceNameForInstanceInRegion", String.class,
Method method = InstanceAsyncClient.class.getMethod("getRootDeviceNameForInstanceInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=rootDeviceName&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=rootDeviceName&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -245,16 +228,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, public void testGetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("getRamdiskForInstanceInRegion", String.class, String.class);
Method method = InstanceAsyncClient.class.getMethod("getRamdiskForInstanceInRegion",
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=ramdisk&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=ramdisk&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -265,16 +245,15 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetDisableApiTerminationForInstanceInRegion() throws SecurityException, public void testGetDisableApiTerminationForInstanceInRegion() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("isApiTerminationDisabledForInstanceInRegion", String.class,
"isApiTerminationDisabledForInstanceInRegion", String.class, String.class); String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=disableApiTermination&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=disableApiTermination&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -285,16 +264,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, public void testGetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("getKernelForInstanceInRegion", String.class, String.class);
Method method = InstanceAsyncClient.class.getMethod("getKernelForInstanceInRegion",
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=kernel&InstanceId=1",
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=kernel&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -304,16 +280,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetInstanceTypeForInstanceInRegion() throws SecurityException, public void testGetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("getInstanceTypeForInstanceInRegion", String.class,
Method method = InstanceAsyncClient.class.getMethod("getInstanceTypeForInstanceInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=instanceType&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=instanceType&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -324,11 +298,10 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetInstanceInitiatedShutdownBehaviorForInstanceInRegion() public void testGetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,
throws SecurityException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("getInstanceInitiatedShutdownBehaviorForInstanceInRegion",
"getInstanceInitiatedShutdownBehaviorForInstanceInRegion", String.class, String.class, String.class);
String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -345,16 +318,15 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testGetBlockDeviceMappingForInstanceInRegion() throws SecurityException, public void testGetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("getBlockDeviceMappingForInstanceInRegion", String.class,
"getBlockDeviceMappingForInstanceInRegion", String.class, String.class); String.class);
HttpRequest request = processor.createRequest(method, null, "1"); HttpRequest request = processor.createRequest(method, null, "1");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=blockDeviceMapping&InstanceId=1", "Version=2010-06-15&Action=DescribeInstanceAttribute&Attribute=blockDeviceMapping&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -365,16 +337,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetUserDataForInstanceInRegion() throws SecurityException, public void testSetUserDataForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("setUserDataForInstanceInRegion", String.class, String.class,
Method method = InstanceAsyncClient.class.getMethod("setUserDataForInstanceInRegion", Array.newInstance(byte.class, 0).getClass());
String.class, String.class, Array.newInstance(byte.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "test".getBytes()); HttpRequest request = processor.createRequest(method, null, "1", "test".getBytes());
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=userData&Value=dGVzdA%3D%3D&InstanceId=1", "Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=userData&Value=dGVzdA%3D%3D&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
filter.filter(request);// ensure encoding worked properly filter.filter(request);// ensure encoding worked properly
@ -389,16 +359,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, public void testSetRamdiskForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("setRamdiskForInstanceInRegion", String.class, String.class,
Method method = InstanceAsyncClient.class.getMethod("setRamdiskForInstanceInRegion", String.class);
String.class, String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1", "test"); HttpRequest request = processor.createRequest(method, null, "1", "test");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=ramdisk&Value=test&InstanceId=1", "Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=ramdisk&Value=test&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -408,16 +376,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, public void testSetKernelForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = InstanceAsyncClient.class.getMethod("setKernelForInstanceInRegion", String.class, String.class,
Method method = InstanceAsyncClient.class.getMethod("setKernelForInstanceInRegion", String.class);
String.class, String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1", "test"); HttpRequest request = processor.createRequest(method, null, "1", "test");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=kernel&Value=test&InstanceId=1", "Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=kernel&Value=test&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -427,11 +393,10 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetApiTerminationDisabledForInstanceInRegion() throws SecurityException, public void testSetApiTerminationDisabledForInstanceInRegion() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("setApiTerminationDisabledForInstanceInRegion", String.class,
"setApiTerminationDisabledForInstanceInRegion", String.class, String.class, String.class, boolean.class);
boolean.class);
HttpRequest request = processor.createRequest(method, null, "1", true); HttpRequest request = processor.createRequest(method, null, "1", true);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -448,16 +413,14 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetInstanceTypeForInstanceInRegion() throws SecurityException, public void testSetInstanceTypeForInstanceInRegion() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = InstanceAsyncClient.class.getMethod("setInstanceTypeForInstanceInRegion", String.class,
Method method = InstanceAsyncClient.class.getMethod("setInstanceTypeForInstanceInRegion", String.class, String.class);
String.class, String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "1", InstanceType.C1_MEDIUM); HttpRequest request = processor.createRequest(method, null, "1", InstanceType.C1_MEDIUM);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=instanceType&Value=c1.medium&InstanceId=1", "Version=2010-06-15&Action=ModifyInstanceAttribute&Attribute=instanceType&Value=c1.medium&InstanceId=1",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -468,13 +431,11 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() public void testSetInstanceInitiatedShutdownBehaviorForInstanceInRegion() throws SecurityException,
throws SecurityException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("setInstanceInitiatedShutdownBehaviorForInstanceInRegion",
"setInstanceInitiatedShutdownBehaviorForInstanceInRegion", String.class, String.class, String.class, InstanceInitiatedShutdownBehavior.class);
String.class, InstanceInitiatedShutdownBehavior.class); HttpRequest request = processor.createRequest(method, null, "1", InstanceInitiatedShutdownBehavior.TERMINATE);
HttpRequest request = processor.createRequest(method, null, "1",
InstanceInitiatedShutdownBehavior.TERMINATE);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -490,15 +451,13 @@ public class InstanceAsyncClientTest extends BaseEC2AsyncClientTest<InstanceAsyn
checkFilters(request); checkFilters(request);
} }
public void testSetBlockDeviceMappingForInstanceInRegion() throws SecurityException, public void testSetBlockDeviceMappingForInstanceInRegion() throws SecurityException, NoSuchMethodException,
NoSuchMethodException, IOException { IOException {
Method method = InstanceAsyncClient.class.getMethod( Method method = InstanceAsyncClient.class.getMethod("setBlockDeviceMappingForInstanceInRegion", String.class,
"setBlockDeviceMappingForInstanceInRegion", String.class, String.class, String.class, BlockDeviceMapping.class);
BlockDeviceMapping.class);
BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping(); BlockDeviceMapping blockDeviceMapping = new BlockDeviceMapping();
blockDeviceMapping.addEbsBlockDevice("/dev/sda1", new RunningInstance.EbsBlockDevice( blockDeviceMapping.addEbsBlockDevice("/dev/sda1", new RunningInstance.EbsBlockDevice("vol-test1", true));
"vol-test1", true));
HttpRequest request = processor.createRequest(method, null, "1", blockDeviceMapping); HttpRequest request = processor.createRequest(method, null, "1", blockDeviceMapping);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");

View File

@ -40,8 +40,7 @@ import com.google.inject.TypeLiteral;
public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest<KeyPairAsyncClient> { public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest<KeyPairAsyncClient> {
public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteKeyPair() throws SecurityException, NoSuchMethodException, IOException {
Method method = KeyPairAsyncClient.class.getMethod("deleteKeyPairInRegion", String.class, Method method = KeyPairAsyncClient.class.getMethod("deleteKeyPairInRegion", String.class, String.class);
String.class);
HttpRequest request = processor.createRequest(method, null, "mykey"); HttpRequest request = processor.createRequest(method, null, "mykey");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -57,14 +56,14 @@ public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest<KeyPairAsyncC
} }
public void testDescribeKeyPairs() throws SecurityException, NoSuchMethodException, IOException { public void testDescribeKeyPairs() throws SecurityException, NoSuchMethodException, IOException {
Method method = KeyPairAsyncClient.class.getMethod("describeKeyPairsInRegion", String.class, Method method = KeyPairAsyncClient.class.getMethod("describeKeyPairsInRegion", String.class, Array.newInstance(
Array.newInstance(String.class, 0).getClass()); String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeKeyPairs", assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeKeyPairs", "application/x-www-form-urlencoded",
"application/x-www-form-urlencoded", false); false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class); assertSaxResponseParserClassEquals(method, DescribeKeyPairsResponseHandler.class);
@ -73,16 +72,14 @@ public class KeyPairAsyncClientTest extends BaseEC2AsyncClientTest<KeyPairAsyncC
checkFilters(request); checkFilters(request);
} }
public void testDescribeKeyPairsArgs() throws SecurityException, NoSuchMethodException, public void testDescribeKeyPairsArgs() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = KeyPairAsyncClient.class.getMethod("describeKeyPairsInRegion", String.class, Array.newInstance(
Method method = KeyPairAsyncClient.class.getMethod("describeKeyPairsInRegion", String.class, String.class, 0).getClass());
Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeKeyPairs&KeyName.1=1&KeyName.2=2",
"Version=2010-06-15&Action=DescribeKeyPairs&KeyName.1=1&KeyName.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);

View File

@ -38,10 +38,9 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit", testName = "ec2.MonitoringAsyncClientTest") @Test(groups = "unit", testName = "ec2.MonitoringAsyncClientTest")
public class MonitoringAsyncClientTest extends BaseEC2AsyncClientTest<MonitoringAsyncClient> { public class MonitoringAsyncClientTest extends BaseEC2AsyncClientTest<MonitoringAsyncClient> {
public void testUnmonitorInstances() throws SecurityException, NoSuchMethodException, public void testUnmonitorInstances() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = MonitoringAsyncClient.class.getMethod("unmonitorInstancesInRegion", String.class, String.class,
Method method = MonitoringAsyncClient.class.getMethod("unmonitorInstancesInRegion", Array.newInstance(String.class, 0).getClass());
String.class, String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "instance1", "instance2"); HttpRequest request = processor.createRequest(method, null, "instance1", "instance2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -57,14 +56,13 @@ public class MonitoringAsyncClientTest extends BaseEC2AsyncClientTest<Monitoring
} }
public void testMonitorInstances() throws SecurityException, NoSuchMethodException, IOException { public void testMonitorInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = MonitoringAsyncClient.class.getMethod("monitorInstancesInRegion", Method method = MonitoringAsyncClient.class.getMethod("monitorInstancesInRegion", String.class, String.class,
String.class, String.class, Array.newInstance(String.class, 0).getClass()); Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "instance1", "instance2"); HttpRequest request = processor.createRequest(method, null, "instance1", "instance2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=MonitorInstances&InstanceId.0=instance1&InstanceId.1=instance2", "Version=2010-06-15&Action=MonitorInstances&InstanceId.0=instance1&InstanceId.1=instance2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);

View File

@ -42,10 +42,9 @@ import com.google.inject.TypeLiteral;
@Test(groups = "unit", testName = "ec2.SecurityGroupAsyncClientTest") @Test(groups = "unit", testName = "ec2.SecurityGroupAsyncClientTest")
public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<SecurityGroupAsyncClient> { public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<SecurityGroupAsyncClient> {
public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, public void testDeleteSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SecurityGroupAsyncClient.class.getMethod("deleteSecurityGroupInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod("deleteSecurityGroupInRegion", String.class);
String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "name"); HttpRequest request = processor.createRequest(method, null, "name");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -60,16 +59,14 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testCreateSecurityGroup() throws SecurityException, NoSuchMethodException, public void testCreateSecurityGroup() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SecurityGroupAsyncClient.class.getMethod("createSecurityGroupInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod("createSecurityGroupInRegion", String.class, String.class);
String.class, String.class, String.class);
HttpRequest request = processor.createRequest(method, null, "name", "description"); HttpRequest request = processor.createRequest(method, null, "name", "description");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2010-06-15&Action=CreateSecurityGroup&GroupDescription=description&GroupName=name", "Version=2010-06-15&Action=CreateSecurityGroup&GroupDescription=description&GroupName=name",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -80,10 +77,9 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testDescribeSecurityGroups() throws SecurityException, NoSuchMethodException, public void testDescribeSecurityGroups() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SecurityGroupAsyncClient.class.getMethod("describeSecurityGroupsInRegion", String.class, Array
Method method = SecurityGroupAsyncClient.class.getMethod("describeSecurityGroupsInRegion", .newInstance(String.class, 0).getClass());
String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
@ -98,16 +94,14 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testDescribeSecurityGroupsArgs() throws SecurityException, NoSuchMethodException, public void testDescribeSecurityGroupsArgs() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SecurityGroupAsyncClient.class.getMethod("describeSecurityGroupsInRegion", String.class, Array
Method method = SecurityGroupAsyncClient.class.getMethod("describeSecurityGroupsInRegion", .newInstance(String.class, 0).getClass());
String.class, Array.newInstance(String.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "1", "2"); HttpRequest request = processor.createRequest(method, null, "1", "2");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "Version=2010-06-15&Action=DescribeSecurityGroups&GroupName.1=1&GroupName.2=2",
"Version=2010-06-15&Action=DescribeSecurityGroups&GroupName.1=1&GroupName.2=2",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, ParseSax.class); assertResponseParserClassEquals(method, request, ParseSax.class);
@ -117,13 +111,11 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testAuthorizeSecurityGroupIngressGroup() throws SecurityException, public void testAuthorizeSecurityGroupIngressGroup() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = SecurityGroupAsyncClient.class.getMethod("authorizeSecurityGroupIngressInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod( String.class, UserIdGroupPair.class);
"authorizeSecurityGroupIngressInRegion", String.class, String.class, HttpRequest request = processor.createRequest(method, null, "group", new UserIdGroupPair("sourceUser",
UserIdGroupPair.class); "sourceGroup"));
HttpRequest request = processor.createRequest(method, null, "group", new UserIdGroupPair(
"sourceUser", "sourceGroup"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -139,13 +131,10 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testAuthorizeSecurityGroupIngressCidr() throws SecurityException, public void testAuthorizeSecurityGroupIngressCidr() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = SecurityGroupAsyncClient.class.getMethod("authorizeSecurityGroupIngressInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod( String.class, IpProtocol.class, int.class, int.class, String.class);
"authorizeSecurityGroupIngressInRegion", String.class, String.class, HttpRequest request = processor.createRequest(method, null, "group", IpProtocol.TCP, 6000, 7000, "0.0.0.0/0");
IpProtocol.class, int.class, int.class, String.class);
HttpRequest request = processor.createRequest(method, null, "group", IpProtocol.TCP, 6000,
7000, "0.0.0.0/0");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -161,13 +150,11 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testRevokeSecurityGroupIngressGroup() throws SecurityException, public void testRevokeSecurityGroupIngressGroup() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = SecurityGroupAsyncClient.class.getMethod("revokeSecurityGroupIngressInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod( String.class, UserIdGroupPair.class);
"revokeSecurityGroupIngressInRegion", String.class, String.class, HttpRequest request = processor.createRequest(method, null, "group", new UserIdGroupPair("sourceUser",
UserIdGroupPair.class); "sourceGroup"));
HttpRequest request = processor.createRequest(method, null, "group", new UserIdGroupPair(
"sourceUser", "sourceGroup"));
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");
@ -183,13 +170,10 @@ public class SecurityGroupAsyncClientTest extends BaseEC2AsyncClientTest<Securit
checkFilters(request); checkFilters(request);
} }
public void testRevokeSecurityGroupIngressCidr() throws SecurityException, public void testRevokeSecurityGroupIngressCidr() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = SecurityGroupAsyncClient.class.getMethod("revokeSecurityGroupIngressInRegion", String.class,
Method method = SecurityGroupAsyncClient.class.getMethod( String.class, IpProtocol.class, int.class, int.class, String.class);
"revokeSecurityGroupIngressInRegion", String.class, String.class, IpProtocol.class, HttpRequest request = processor.createRequest(method, null, "group", IpProtocol.TCP, 6000, 7000, "0.0.0.0/0");
int.class, int.class, String.class);
HttpRequest request = processor.createRequest(method, null, "group", IpProtocol.TCP, 6000,
7000, "0.0.0.0/0");
assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://ec2.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: ec2.us-east-1.amazonaws.com\n");

View File

@ -27,9 +27,13 @@ import org.jclouds.aws.domain.Region;
import org.jclouds.aws.ec2.domain.AvailabilityZone; import org.jclouds.aws.ec2.domain.AvailabilityZone;
import org.jclouds.aws.ec2.domain.AvailabilityZoneInfo; import org.jclouds.aws.ec2.domain.AvailabilityZoneInfo;
import org.jclouds.http.functions.BaseHandlerTest; import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
/** /**
* Tests behavior of {@code DescribeAvailabilityZonesResponseHandler} * Tests behavior of {@code DescribeAvailabilityZonesResponseHandler}
@ -39,21 +43,36 @@ import com.google.common.collect.ImmutableSet;
@Test(groups = "unit", testName = "ec2.DescribeAvailabilityZonesResponseHandlerTest") @Test(groups = "unit", testName = "ec2.DescribeAvailabilityZonesResponseHandlerTest")
public class DescribeAvailabilityZonesResponseHandlerTest extends BaseHandlerTest { public class DescribeAvailabilityZonesResponseHandlerTest extends BaseHandlerTest {
@BeforeTest
protected void setUpInjector() {
injector = Guice.createInjector(new ParserModule() {
@Override
protected void configure() {
bindConstant().annotatedWith(org.jclouds.aws.Region.class).to("SHOULDNTSEETHISASXMLHASREGIONDATA");
super.configure();
}
});
factory = injector.getInstance(ParseSax.Factory.class);
assert factory != null;
}
public void testApplyInputStream() { public void testApplyInputStream() {
InputStream is = getClass().getResourceAsStream("/ec2/availabilityZones.xml"); InputStream is = getClass().getResourceAsStream("/ec2/availabilityZones.xml");
Set<AvailabilityZoneInfo> expected = ImmutableSet.<AvailabilityZoneInfo> of( Set<AvailabilityZoneInfo> expected = ImmutableSet.<AvailabilityZoneInfo> of(
new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1A, "available", Region.US_EAST_1, new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1A, "available", Region.US_EAST_1, ImmutableSet.<String> of()),
ImmutableSet.<String> of()), new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1B, new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1B, "available", Region.US_EAST_1, ImmutableSet
"available", Region.US_EAST_1, ImmutableSet.<String> of()), .<String> of()),
new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1C, "available", Region.US_EAST_1, new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1C, "available", Region.US_EAST_1, ImmutableSet
ImmutableSet.<String> of("our service is awesome")), .<String> of("our service is awesome")),
new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1D, "downlikeaclown", Region.US_EAST_1, new AvailabilityZoneInfo(AvailabilityZone.US_EAST_1D, "downlikeaclown", Region.US_EAST_1, ImmutableSet
ImmutableSet.<String> of())); .<String> of()));
Set<AvailabilityZoneInfo> result = factory.create( Set<AvailabilityZoneInfo> result = factory.create(
injector.getInstance(DescribeAvailabilityZonesResponseHandler.class)).parse(is); injector.getInstance(DescribeAvailabilityZonesResponseHandler.class)).parse(is);

View File

@ -39,7 +39,6 @@ public abstract class BaseS3AsyncClientTest extends RestClientTest<S3AsyncClient
protected BlobToObject blobToS3Object; protected BlobToObject blobToS3Object;
protected RequestAuthorizeSignature filter; protected RequestAuthorizeSignature filter;
@Override @Override
protected void checkFilters(HttpRequest request) { protected void checkFilters(HttpRequest request) {
assertEquals(request.getFilters().size(), 1); assertEquals(request.getFilters().size(), 1);
@ -66,9 +65,7 @@ public abstract class BaseS3AsyncClientTest extends RestClientTest<S3AsyncClient
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("s3", "identity", "credential", return new RestContextFactory().createContextSpec("s3", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -81,8 +81,8 @@ import com.google.inject.Module;
public class S3AsyncClientTest extends BaseS3AsyncClientTest { public class S3AsyncClientTest extends BaseS3AsyncClientTest {
public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException { public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance(
String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); PutBucketOptions.class, 0).getClass());
for (String region : Region.ALL_S3) { for (String region : Region.ALL_S3) {
processor.createRequest(method, region, "bucket-name"); processor.createRequest(method, region, "bucket-name");
} }
@ -115,8 +115,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
Method method = S3AsyncClient.class.getMethod("getBucketPayer", String.class); Method method = S3AsyncClient.class.getMethod("getBucketPayer", String.class);
HttpRequest request = processor.createRequest(method, "bucket"); HttpRequest request = processor.createRequest(method, "bucket");
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
"GET https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -127,13 +126,11 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testSetBucketPayerOwner() throws SecurityException, NoSuchMethodException, public void testSetBucketPayerOwner() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class); Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class);
HttpRequest request = processor.createRequest(method, "bucket", Payer.BUCKET_OWNER); HttpRequest request = processor.createRequest(method, "bucket", Payer.BUCKET_OWNER);
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
"PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(
request, request,
@ -147,13 +144,11 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testSetBucketPayerRequester() throws SecurityException, NoSuchMethodException, public void testSetBucketPayerRequester() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class); Method method = S3AsyncClient.class.getMethod("setBucketPayer", String.class, Payer.class);
HttpRequest request = processor.createRequest(method, "bucket", Payer.REQUESTER); HttpRequest request = processor.createRequest(method, "bucket", Payer.REQUESTER);
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
"PUT https://bucket.s3.amazonaws.com/?requestPayment HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(
request, request,
@ -199,26 +194,22 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
} }
@Test(expectedExceptions = IllegalArgumentException.class) @Test(expectedExceptions = IllegalArgumentException.class)
public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, public void testCopyObjectInvalidName() throws ArrayIndexOutOfBoundsException, SecurityException,
SecurityException, IllegalArgumentException, NoSuchMethodException, IOException { IllegalArgumentException, NoSuchMethodException, IOException {
Method method = S3AsyncClient.class Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class,
.getMethod("copyObject", String.class, String.class, String.class, String.class, String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass());
Array.newInstance(CopyObjectOptions.class, 0).getClass()); processor.createRequest(method, "sourceBucket", "sourceObject", "destinationBucket", "destinationObject");
processor.createRequest(method, "sourceBucket", "sourceObject", "destinationBucket",
"destinationObject");
} }
public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, public void testCopyObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
IllegalArgumentException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = S3AsyncClient.class Method method = S3AsyncClient.class.getMethod("copyObject", String.class, String.class, String.class,
.getMethod("copyObject", String.class, String.class, String.class, String.class, String.class, Array.newInstance(CopyObjectOptions.class, 0).getClass());
Array.newInstance(CopyObjectOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, "sourceBucket", "sourceObject", "destinationbucket",
HttpRequest request = processor.createRequest(method, "sourceBucket", "sourceObject", "destinationObject");
"destinationbucket", "destinationObject");
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://destinationbucket.s3.amazonaws.com/destinationObject HTTP/1.1");
"PUT https://destinationbucket.s3.amazonaws.com/destinationObject HTTP/1.1");
assertNonPayloadHeadersEqual(request, assertNonPayloadHeadersEqual(request,
"Host: destinationbucket.s3.amazonaws.com\nx-amz-copy-source: /sourceBucket/sourceObject\n"); "Host: destinationbucket.s3.amazonaws.com\nx-amz-copy-source: /sourceBucket/sourceObject\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -230,8 +221,7 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testDeleteBucketIfEmpty() throws SecurityException, NoSuchMethodException, public void testDeleteBucketIfEmpty() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = S3AsyncClient.class.getMethod("deleteBucketIfEmpty", String.class); Method method = S3AsyncClient.class.getMethod("deleteBucketIfEmpty", String.class);
HttpRequest request = processor.createRequest(method, "bucket"); HttpRequest request = processor.createRequest(method, "bucket");
@ -277,10 +267,10 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, public void testGetObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
IllegalArgumentException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("getObject", String.class, String.class, Array Method method = S3AsyncClient.class.getMethod("getObject", String.class, String.class, Array.newInstance(
.newInstance(GetOptions.class, 0).getClass()); GetOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "bucket", "object"); HttpRequest request = processor.createRequest(method, "bucket", "object");
assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/object HTTP/1.1"); assertRequestLineEquals(request, "GET https://bucket.s3.amazonaws.com/object HTTP/1.1");
@ -363,10 +353,9 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
} }
public void testPutBucketACL() throws SecurityException, NoSuchMethodException, IOException { public void testPutBucketACL() throws SecurityException, NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putBucketACL", String.class, Method method = S3AsyncClient.class.getMethod("putBucketACL", String.class, AccessControlList.class);
AccessControlList.class); HttpRequest request = processor.createRequest(method, "bucket", AccessControlList.fromCannedAccessPolicy(
HttpRequest request = processor.createRequest(method, "bucket", AccessControlList CannedAccessPolicy.PRIVATE, "1234"));
.fromCannedAccessPolicy(CannedAccessPolicy.PRIVATE, "1234"));
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?acl HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?acl HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
@ -384,8 +373,8 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException, public void testPutBucketDefault() throws ArrayIndexOutOfBoundsException, SecurityException,
IllegalArgumentException, NoSuchMethodException, IOException { IllegalArgumentException, NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance(
String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); PutBucketOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null, "bucket"); HttpRequest request = processor.createRequest(method, (String) null, "bucket");
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1");
@ -399,16 +388,15 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, public void testPutBucketEu() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
IllegalArgumentException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, Method method = S3AsyncClient.class.getMethod("putBucketInRegion", String.class, String.class, Array.newInstance(
String.class, Array.newInstance(PutBucketOptions.class, 0).getClass()); PutBucketOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "EU", "bucket"); HttpRequest request = processor.createRequest(method, "EU", "bucket");
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>", "<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>",
"text/xml", false); "text/xml", false);
@ -419,11 +407,11 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, public void testPutObject() throws ArrayIndexOutOfBoundsException, SecurityException, IllegalArgumentException,
IllegalArgumentException, NoSuchMethodException, IOException { NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putObject", String.class, S3Object.class, Method method = S3AsyncClient.class
PutObjectOptions[].class); .getMethod("putObject", String.class, S3Object.class, PutObjectOptions[].class);
HttpRequest request = processor.createRequest(method, "bucket", blobToS3Object HttpRequest request = processor.createRequest(method, "bucket", blobToS3Object
.apply(BindBlobToMultipartFormTest.TEST_BLOB)); .apply(BindBlobToMultipartFormTest.TEST_BLOB));
@ -439,10 +427,10 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
} }
public void testPutObjectACL() throws SecurityException, NoSuchMethodException, IOException { public void testPutObjectACL() throws SecurityException, NoSuchMethodException, IOException {
Method method = S3AsyncClient.class.getMethod("putObjectACL", String.class, String.class, Method method = S3AsyncClient.class
AccessControlList.class); .getMethod("putObjectACL", String.class, String.class, AccessControlList.class);
HttpRequest request = processor.createRequest(method, "bucket", "key", AccessControlList HttpRequest request = processor.createRequest(method, "bucket", "key", AccessControlList.fromCannedAccessPolicy(
.fromCannedAccessPolicy(CannedAccessPolicy.PRIVATE, "1234")); CannedAccessPolicy.PRIVATE, "1234"));
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/key?acl HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/key?acl HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
@ -473,15 +461,13 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testDisableBucketLogging() throws SecurityException, NoSuchMethodException, public void testDisableBucketLogging() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = S3AsyncClient.class.getMethod("disableBucketLogging", String.class); Method method = S3AsyncClient.class.getMethod("disableBucketLogging", String.class);
HttpRequest request = processor.createRequest(method, "bucket"); HttpRequest request = processor.createRequest(method, "bucket");
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals(request, assertPayloadEquals(request, "<BucketLoggingStatus xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"/>",
"<BucketLoggingStatus xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"/>",
"text/xml", false); "text/xml", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -491,18 +477,16 @@ public class S3AsyncClientTest extends BaseS3AsyncClientTest {
checkFilters(request); checkFilters(request);
} }
public void testEnableBucketLoggingOwner() throws SecurityException, NoSuchMethodException, public void testEnableBucketLoggingOwner() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = S3AsyncClient.class.getMethod("enableBucketLogging", String.class, BucketLogging.class);
Method method = S3AsyncClient.class.getMethod("enableBucketLogging", String.class, HttpRequest request = processor
BucketLogging.class); .createRequest(method, "bucket", new BucketLogging("mylogs", "access_log-", ImmutableSet
HttpRequest request = processor.createRequest(method, "bucket", new BucketLogging("mylogs", .<Grant> of(new Grant(new EmailAddressGrantee("adrian@jclouds.org"), Permission.FULL_CONTROL))));
"access_log-", ImmutableSet.<Grant> of(new Grant(new EmailAddressGrantee(
"adrian@jclouds.org"), Permission.FULL_CONTROL))));
assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1"); assertRequestLineEquals(request, "PUT https://bucket.s3.amazonaws.com/?logging HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: bucket.s3.amazonaws.com\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream( assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream("/s3/bucket_logging.xml")),
"/s3/bucket_logging.xml")), "text/xml", false); "text/xml", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);

View File

@ -74,16 +74,14 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
} }
} }
public void testListQueuesInRegion() throws SecurityException, NoSuchMethodException, public void testListQueuesInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array.newInstance(
Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array ListQueuesOptions.class, 0).getClass());
.newInstance(ListQueuesOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, (String) null); HttpRequest request = processor.createRequest(method, (String) null);
assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n");
assertPayloadEquals(request, "Version=2009-02-01&Action=ListQueues", assertPayloadEquals(request, "Version=2009-02-01&Action=ListQueues", "application/x-www-form-urlencoded", false);
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, request, RegexListQueuesResponseHandler.class); assertResponseParserClassEquals(method, request, RegexListQueuesResponseHandler.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -92,12 +90,10 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testListQueuesInRegionOptions() throws SecurityException, NoSuchMethodException, public void testListQueuesInRegionOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array.newInstance(
Method method = SQSAsyncClient.class.getMethod("listQueuesInRegion", String.class, Array ListQueuesOptions.class, 0).getClass());
.newInstance(ListQueuesOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, ListQueuesOptions.Builder.queuePrefix("prefix"));
HttpRequest request = processor.createRequest(method, null, ListQueuesOptions.Builder
.queuePrefix("prefix"));
assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n");
@ -111,10 +107,9 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testCreateQueueInRegion() throws SecurityException, NoSuchMethodException, public void testCreateQueueInRegion() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array
Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, .newInstance(CreateQueueOptions.class, 0).getClass());
String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, null, "queueName"); HttpRequest request = processor.createRequest(method, null, "queueName");
assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1");
@ -129,17 +124,15 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
checkFilters(request); checkFilters(request);
} }
public void testCreateQueueInRegionOptions() throws SecurityException, NoSuchMethodException, public void testCreateQueueInRegionOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array
Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, .newInstance(CreateQueueOptions.class, 0).getClass());
String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass()); HttpRequest request = processor.createRequest(method, null, "queueName", CreateQueueOptions.Builder
HttpRequest request = processor.createRequest(method, null, "queueName", .defaultVisibilityTimeout(45));
CreateQueueOptions.Builder.defaultVisibilityTimeout(45));
assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1"); assertRequestLineEquals(request, "POST https://sqs.us-east-1.amazonaws.com/ HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n"); assertNonPayloadHeadersEqual(request, "Host: sqs.us-east-1.amazonaws.com\n");
assertPayloadEquals( assertPayloadEquals(request,
request,
"Version=2009-02-01&Action=CreateQueue&QueueName=queueName&DefaultVisibilityTimeout=45", "Version=2009-02-01&Action=CreateQueue&QueueName=queueName&DefaultVisibilityTimeout=45",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -151,8 +144,8 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
} }
public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException { public void testAllRegions() throws SecurityException, NoSuchMethodException, IOException {
Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, Method method = SQSAsyncClient.class.getMethod("createQueueInRegion", String.class, String.class, Array
String.class, Array.newInstance(CreateQueueOptions.class, 0).getClass()); .newInstance(CreateQueueOptions.class, 0).getClass());
for (String region : Iterables.filter(Region.ALL_SQS, not(equalTo("us-standard")))) { for (String region : Iterables.filter(Region.ALL_SQS, not(equalTo("us-standard")))) {
processor.createRequest(method, region, "queueName"); processor.createRequest(method, region, "queueName");
} }
@ -177,8 +170,7 @@ public class SQSAsyncClientTest extends RestClientTest<SQSAsyncClient> {
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("sqs", "identity", "credential", return new RestContextFactory().createContextSpec("sqs", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -1,189 +1,49 @@
<DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2009-11-30/"> <DescribeImagesResponse xmlns="http://ec2.amazonaws.com/doc/2010-06-15/">
<requestId>7b893acf-7752-4e <requestId>2564fc86-9a73-4727-9298-f0b9eb9b57c8</requestId>
2c-8c1a-3287a011b0df</requestId>
<imagesSet> <imagesSet>
<item> <item>
<imageId>emi-9ACB1363</imageId> <imageId>emi-9ACB1363</imageId>
<imageLocation>centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml <imageLocation>centos-5.3-x86_64/centos.5-3.x86-64.img.manifest.xml</imageLocation>
</imageLocation> <imageState>available</imageState>
<imageState>available
</imageState>
<imageOwnerId>admin</imageOwnerId> <imageOwnerId>admin</imageOwnerId>
<isPublic>true</isPublic> <isPublic>true</isPublic>
<productCodes /> <productCodes />
<architecture>x86_64</architecture> <architecture>x86_64</architecture>
<imageType>
machine
</imageType>
<kernelId>eki-6CBD12F2</kernelId>
<ramdiskId>eri-A97113E4</ramdiskId>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>emi-D2D610D1</imageId>
<imageLocation>martin_try1/martin_try1.manifest.xml</imageLocation>
<imageState>
available
</imageState>
<imageOwnerId>dominic</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>x86_64</architecture>
<imageType>machine</imageType> <imageType>machine</imageType>
<kernelId>eki-6CBD12F2</kernelId> <kernelId>eki-6CBD12F2</kernelId>
<ramdiskId>eri-A97113E4</ramdiskId> <ramdiskId>eri-A97113E4</ramdiskId>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item> </item>
<item> <item>
<imageId>eri-A97113E4</imageId> <imageId>eri-A97113E4</imageId>
<imageLocation>initrd-64/initrd.img-2.6.28-11-generic.manifest.xml <imageLocation>initrd-64/initrd.img-2.6.28-11-generic.manifest.xml</imageLocation>
</imageLocation>
<imageState>available</imageState> <imageState>available</imageState>
<imageOwnerId>admin</imageOwnerId> <imageOwnerId>admin</imageOwnerId>
<isPublic>true</isPublic> <isPublic>true</isPublic>
<productCodes /> <productCodes />
<architecture>x86_64</architecture> <architecture>x86_64</architecture>
<imageType>ramdisk</imageType> <imageType>ramdisk</imageType>
<rootDeviceType>
instance-store
</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item> </item>
<item> <item>
<imageId>emi-B9A40FF6</imageId> <imageId>eki-6CBD12F2</imageId>
<imageLocation>ulteo4/ubuntu804-32-test.manifest.xml</imageLocation> <imageLocation>kernel-64/vmlinuz-2.6.28-11-generic.manifest.xml</imageLocation>
<imageState>available</imageState>
<imageOwnerId>gaelduval</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>
i386
</architecture>
<imageType>machine</imageType>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>
emi-D1991835
</imageId>
<imageLocation>jamestyj-test/Eucalyptus_Guest.x86_64-0.0.2.raw.manifest.xml
</imageLocation>
<imageState>available</imageState>
<imageOwnerId>jamestyj</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>x86_64</architecture>
<imageType>machine</imageType>
<rootDeviceType>
instance-store
</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>emi-D8AB1044</imageId>
<imageLocation>test/ubuntu.9-04.x86-64.img.manifest.xml
</imageLocation>
<imageState>available</imageState>
<imageOwnerId>mymq0206</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>
x86_64
</architecture>
<imageType>machine</imageType>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>
emi-CBEA100C
</imageId>
<imageLocation>Lean/ubuntu.9-04.x86-64.img.manifest.xml
</imageLocation>
<imageState>available</imageState>
<imageOwnerId>
mashaobing1
</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>x86_64</architecture>
<imageType>machine</imageType>
<kernelId>eki-6CBD12F2</kernelId>
<ramdiskId>eri-A97113E4</ramdiskId>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>emi-D176182B</imageId>
<imageLocation>jamestyj-test/Eucalyptus_Guest.x86_64-0.0.3.raw.manifest.xml
</imageLocation>
<imageState>available</imageState>
<imageOwnerId>
jamestyj
</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>x86_64</architecture>
<imageType>machine</imageType>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>emi-D25E10CA</imageId>
<imageLocation>
biolinux/biolinux.qcow2.manifest.xml
</imageLocation>
<imageState>available</imageState>
<imageOwnerId>brainstorm</imageOwnerId>
<isPublic>true</isPublic>
<productCodes />
<architecture>x86_64</architecture>
<imageType>machine</imageType>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item>
<item>
<imageId>
eki-6CBD12F2
</imageId>
<imageLocation>kernel-64/vmlinuz-2.6.28-11-generic.manifest.xml
</imageLocation>
<imageState>available</imageState> <imageState>available</imageState>
<imageOwnerId>admin</imageOwnerId> <imageOwnerId>admin</imageOwnerId>
<isPublic>true</isPublic> <isPublic>true</isPublic>
<productCodes /> <productCodes />
<architecture>x86_64</architecture> <architecture>x86_64</architecture>
<imageType>kernel</imageType> <imageType>kernel</imageType>
<rootDeviceType>instance-store</rootDeviceType>
<rootDeviceName>/dev/sda1</rootDeviceName>
<blockDeviceMapping />
</item> </item>
<item> <item>
<imageId>emi-2EDC1606</imageId> <imageId>emi-B5C5103A</imageId>
<imageLocation> <imageLocation>shashi-test/RTestSmall.manifest.xml</imageLocation>
ulteo2/Ulteo-SM-Scalability-Test-19feb2010.manifest.xml
</imageLocation>
<imageState>available</imageState> <imageState>available</imageState>
<imageOwnerId>gaelduval</imageOwnerId> <imageOwnerId>admin</imageOwnerId>
<isPublic>true</isPublic> <isPublic>true</isPublic>
<productCodes /> <productCodes />
<architecture>i386</architecture> <architecture>x86_64</architecture>
<imageType>machine</imageType> <imageType>machine</imageType>
<rootDeviceType>instance-store</rootDeviceType> <kernelId>eki-6CBD12F2</kernelId>
<rootDeviceName>/dev/sda1</rootDeviceName> <ramdiskId>eri-A97113E4</ramdiskId>
<blockDeviceMapping />
</item> </item>
</imagesSet> </imagesSet>
</DescribeImagesResponse> </DescribeImagesResponse>

View File

@ -64,8 +64,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
Method method = AzureBlobAsyncClient.class.getMethod("listContainers", ListOptions[].class); Method method = AzureBlobAsyncClient.class.getMethod("listContainers", ListOptions[].class);
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://identity.blob.core.windows.net/?comp=list HTTP/1.1");
"GET https://identity.blob.core.windows.net/?comp=list HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -75,14 +74,11 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
} }
public void testListContainersOptions() throws SecurityException, NoSuchMethodException, public void testListContainersOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = AzureBlobAsyncClient.class.getMethod("listContainers", ListOptions[].class); Method method = AzureBlobAsyncClient.class.getMethod("listContainers", ListOptions[].class);
HttpRequest request = processor.createRequest(method, maxResults(1).marker("marker").prefix( HttpRequest request = processor.createRequest(method, maxResults(1).marker("marker").prefix("prefix"));
"prefix"));
assertRequestLineEquals( assertRequestLineEquals(request,
request,
"GET https://identity.blob.core.windows.net/?comp=list&maxresults=1&marker=marker&prefix=prefix HTTP/1.1"); "GET https://identity.blob.core.windows.net/?comp=list&maxresults=1&marker=marker&prefix=prefix HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -121,12 +117,11 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class);
} }
public void testCreateContainerOptions() throws SecurityException, NoSuchMethodException, public void testCreateContainerOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = AzureBlobAsyncClient.class.getMethod("createContainer", String.class, Method method = AzureBlobAsyncClient.class.getMethod("createContainer", String.class,
CreateContainerOptions[].class); CreateContainerOptions[].class);
HttpRequest request = processor.createRequest(method, "container", withPublicAcl() HttpRequest request = processor.createRequest(method, "container", withPublicAcl().withMetadata(
.withMetadata(ImmutableMultimap.of("foo", "bar"))); ImmutableMultimap.of("foo", "bar")));
assertRequestLineEquals(request, assertRequestLineEquals(request,
"PUT https://identity.blob.core.windows.net/container?restype=container HTTP/1.1"); "PUT https://identity.blob.core.windows.net/container?restype=container HTTP/1.1");
@ -139,15 +134,12 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, ReturnFalseIfContainerAlreadyExists.class); assertExceptionParserClassEquals(method, ReturnFalseIfContainerAlreadyExists.class);
} }
public void testCreateRootContainer() throws SecurityException, NoSuchMethodException, public void testCreateRootContainer() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AzureBlobAsyncClient.class.getMethod("createRootContainer", CreateContainerOptions[].class);
Method method = AzureBlobAsyncClient.class.getMethod("createRootContainer",
CreateContainerOptions[].class);
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://identity.blob.core.windows.net/%24root?restype=container HTTP/1.1");
"PUT https://identity.blob.core.windows.net/%24root?restype=container HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -156,8 +148,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, ReturnFalseIfContainerAlreadyExists.class); assertExceptionParserClassEquals(method, ReturnFalseIfContainerAlreadyExists.class);
} }
public void testDeleteRootContainer() throws SecurityException, NoSuchMethodException, public void testDeleteRootContainer() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = AzureBlobAsyncClient.class.getMethod("deleteRootContainer"); Method method = AzureBlobAsyncClient.class.getMethod("deleteRootContainer");
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
@ -171,15 +162,12 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, ReturnTrueOn404.class); assertExceptionParserClassEquals(method, ReturnTrueOn404.class);
} }
public void testCreateRootContainerOptions() throws SecurityException, NoSuchMethodException, public void testCreateRootContainerOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AzureBlobAsyncClient.class.getMethod("createRootContainer", CreateContainerOptions[].class);
Method method = AzureBlobAsyncClient.class.getMethod("createRootContainer",
CreateContainerOptions[].class);
HttpRequest request = processor.createRequest(method, withPublicAcl().withMetadata( HttpRequest request = processor.createRequest(method, withPublicAcl().withMetadata(
ImmutableMultimap.of("foo", "bar"))); ImmutableMultimap.of("foo", "bar")));
assertRequestLineEquals(request, assertRequestLineEquals(request, "PUT https://identity.blob.core.windows.net/%24root?restype=container HTTP/1.1");
"PUT https://identity.blob.core.windows.net/%24root?restype=container HTTP/1.1");
assertNonPayloadHeadersEqual(request, assertNonPayloadHeadersEqual(request,
"x-ms-meta-foo: bar\nx-ms-prop-publicaccess: true\nx-ms-version: 2009-09-19\n"); "x-ms-meta-foo: bar\nx-ms-prop-publicaccess: true\nx-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -190,8 +178,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
} }
public void testListBlobs() throws SecurityException, NoSuchMethodException, IOException { public void testListBlobs() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureBlobAsyncClient.class.getMethod("listBlobs", String.class, Method method = AzureBlobAsyncClient.class.getMethod("listBlobs", String.class, ListBlobsOptions[].class);
ListBlobsOptions[].class);
HttpRequest request = processor.createRequest(method, "container"); HttpRequest request = processor.createRequest(method, "container");
assertRequestLineEquals(request, assertRequestLineEquals(request,
@ -218,8 +205,7 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
} }
public void testContainerProperties() throws SecurityException, NoSuchMethodException, public void testContainerProperties() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = AzureBlobAsyncClient.class.getMethod("getContainerProperties", String.class); Method method = AzureBlobAsyncClient.class.getMethod("getContainerProperties", String.class);
HttpRequest request = processor.createRequest(method, "container"); HttpRequest request = processor.createRequest(method, "container");
@ -233,12 +219,10 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
assertExceptionParserClassEquals(method, ReturnNullOnContainerNotFound.class); assertExceptionParserClassEquals(method, ReturnNullOnContainerNotFound.class);
} }
public void testSetResourceMetadata() throws SecurityException, NoSuchMethodException, public void testSetResourceMetadata() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AzureBlobAsyncClient.class.getMethod("setResourceMetadata", String.class, Map.class);
Method method = AzureBlobAsyncClient.class.getMethod("setResourceMetadata", String.class, HttpRequest request = processor.createRequest(method,
Map.class); new Object[] { "container", ImmutableMap.of("key", "value") });
HttpRequest request = processor.createRequest(method, new Object[] { "container",
ImmutableMap.of("key", "value") });
assertRequestLineEquals(request, assertRequestLineEquals(request,
"PUT https://identity.blob.core.windows.net/container?restype=container&comp=metadata HTTP/1.1"); "PUT https://identity.blob.core.windows.net/container?restype=container&comp=metadata HTTP/1.1");
@ -251,10 +235,8 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
} }
public void testSetBlobMetadata() throws SecurityException, NoSuchMethodException, IOException { public void testSetBlobMetadata() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureBlobAsyncClient.class.getMethod("setBlobMetadata", String.class, Method method = AzureBlobAsyncClient.class.getMethod("setBlobMetadata", String.class, String.class, Map.class);
String.class, Map.class); HttpRequest request = processor.createRequest(method, "container", "blob", ImmutableMap.of("key", "value"));
HttpRequest request = processor.createRequest(method, "container", "blob", ImmutableMap.of(
"key", "value"));
assertRequestLineEquals(request, assertRequestLineEquals(request,
"PUT https://identity.blob.core.windows.net/container/blob?comp=metadata HTTP/1.1"); "PUT https://identity.blob.core.windows.net/container/blob?comp=metadata HTTP/1.1");
@ -280,7 +262,6 @@ public class AzureBlobAsyncClientTest extends RestClientTest<AzureBlobAsyncClien
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", return new RestContextFactory().createContextSpec("azureblob", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -57,12 +57,10 @@ import com.google.inject.TypeLiteral;
public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncClient> { public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncClient> {
public void testGetMessages() throws SecurityException, NoSuchMethodException, IOException { public void testGetMessages() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, GetOptions[].class);
GetOptions[].class);
HttpRequest request = processor.createRequest(method, "myqueue"); HttpRequest request = processor.createRequest(method, "myqueue");
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://identity.queue.core.windows.net/myqueue/messages HTTP/1.1");
"GET https://identity.queue.core.windows.net/myqueue/messages HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -73,15 +71,11 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
checkFilters(request); checkFilters(request);
} }
public void testGetMessagesOptions() throws SecurityException, NoSuchMethodException, public void testGetMessagesOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, GetOptions[].class);
Method method = AzureQueueAsyncClient.class.getMethod("getMessages", String.class, HttpRequest request = processor.createRequest(method, "myqueue", maxMessages(1).visibilityTimeout(30));
GetOptions[].class);
HttpRequest request = processor.createRequest(method, "myqueue", maxMessages(1)
.visibilityTimeout(30));
assertRequestLineEquals( assertRequestLineEquals(request,
request,
"GET https://identity.queue.core.windows.net/myqueue/messages?numofmessages=1&visibilitytimeout=30 HTTP/1.1"); "GET https://identity.queue.core.windows.net/myqueue/messages?numofmessages=1&visibilitytimeout=30 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -97,8 +91,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
Method method = AzureQueueAsyncClient.class.getMethod("listQueues", ListOptions[].class); Method method = AzureQueueAsyncClient.class.getMethod("listQueues", ListOptions[].class);
HttpRequest request = processor.createRequest(method); HttpRequest request = processor.createRequest(method);
assertRequestLineEquals(request, assertRequestLineEquals(request, "GET https://identity.queue.core.windows.net/?comp=list HTTP/1.1");
"GET https://identity.queue.core.windows.net/?comp=list HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -111,11 +104,9 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
public void testListQueuesOptions() throws SecurityException, NoSuchMethodException, IOException { public void testListQueuesOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureQueueAsyncClient.class.getMethod("listQueues", ListOptions[].class); Method method = AzureQueueAsyncClient.class.getMethod("listQueues", ListOptions[].class);
HttpRequest request = processor.createRequest(method, maxResults(1).marker("marker").prefix( HttpRequest request = processor.createRequest(method, maxResults(1).marker("marker").prefix("prefix"));
"prefix"));
assertRequestLineEquals( assertRequestLineEquals(request,
request,
"GET https://identity.queue.core.windows.net/?comp=list&maxresults=1&marker=marker&prefix=prefix HTTP/1.1"); "GET https://identity.queue.core.windows.net/?comp=list&maxresults=1&marker=marker&prefix=prefix HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -128,8 +119,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
} }
public void testCreateQueue() throws SecurityException, NoSuchMethodException, IOException { public void testCreateQueue() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureQueueAsyncClient.class.getMethod("createQueue", String.class, Method method = AzureQueueAsyncClient.class.getMethod("createQueue", String.class, CreateOptions[].class);
CreateOptions[].class);
HttpRequest request = processor.createRequest(method, "queue"); HttpRequest request = processor.createRequest(method, "queue");
assertRequestLineEquals(request, "PUT https://identity.queue.core.windows.net/queue HTTP/1.1"); assertRequestLineEquals(request, "PUT https://identity.queue.core.windows.net/queue HTTP/1.1");
@ -143,13 +133,10 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
checkFilters(request); checkFilters(request);
} }
public void testCreateQueueOptions() throws SecurityException, NoSuchMethodException, public void testCreateQueueOptions() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = AzureQueueAsyncClient.class.getMethod("createQueue", String.class, Method method = AzureQueueAsyncClient.class.getMethod("createQueue", String.class, CreateOptions[].class);
CreateOptions[].class); HttpRequest request = processor.createRequest(method, "queue", withMetadata(ImmutableMultimap.of("foo", "bar")));
HttpRequest request = processor.createRequest(method, "queue", withMetadata(ImmutableMultimap
.of("foo", "bar")));
assertRequestLineEquals(request, "PUT https://identity.queue.core.windows.net/queue HTTP/1.1"); assertRequestLineEquals(request, "PUT https://identity.queue.core.windows.net/queue HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-meta-foo: bar\nx-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-meta-foo: bar\nx-ms-version: 2009-09-19\n");
@ -167,8 +154,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
Method method = AzureQueueAsyncClient.class.getMethod("deleteQueue", String.class); Method method = AzureQueueAsyncClient.class.getMethod("deleteQueue", String.class);
HttpRequest request = processor.createRequest(method, "queue"); HttpRequest request = processor.createRequest(method, "queue");
assertRequestLineEquals(request, assertRequestLineEquals(request, "DELETE https://identity.queue.core.windows.net/queue HTTP/1.1");
"DELETE https://identity.queue.core.windows.net/queue HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -182,15 +168,13 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
public void testPutMessage() throws SecurityException, NoSuchMethodException, IOException { public void testPutMessage() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureQueueAsyncClient.class.getMethod("putMessage", String.class, Method method = AzureQueueAsyncClient.class.getMethod("putMessage", String.class, String.class,
String.class, PutMessageOptions[].class); PutMessageOptions[].class);
HttpRequest request = processor.createRequest(method, "queue", "message"); HttpRequest request = processor.createRequest(method, "queue", "message");
assertRequestLineEquals(request, assertRequestLineEquals(request, "POST https://identity.queue.core.windows.net/queue/messages HTTP/1.1");
"POST https://identity.queue.core.windows.net/queue/messages HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, assertPayloadEquals(request, "<QueueMessage><MessageText>message</MessageText></QueueMessage>",
"<QueueMessage><MessageText>message</MessageText></QueueMessage>",
"application/unknown", false); "application/unknown", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -202,15 +186,14 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
public void testPutMessageOptions() throws SecurityException, NoSuchMethodException, IOException { public void testPutMessageOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = AzureQueueAsyncClient.class.getMethod("putMessage", String.class, Method method = AzureQueueAsyncClient.class.getMethod("putMessage", String.class, String.class,
String.class, PutMessageOptions[].class); PutMessageOptions[].class);
HttpRequest request = processor.createRequest(method, "queue", "message", withTTL(3)); HttpRequest request = processor.createRequest(method, "queue", "message", withTTL(3));
assertRequestLineEquals(request, assertRequestLineEquals(request,
"POST https://identity.queue.core.windows.net/queue/messages?messagettl=3 HTTP/1.1"); "POST https://identity.queue.core.windows.net/queue/messages?messagettl=3 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, assertPayloadEquals(request, "<QueueMessage><MessageText>message</MessageText></QueueMessage>",
"<QueueMessage><MessageText>message</MessageText></QueueMessage>",
"application/unknown", false); "application/unknown", false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
@ -225,8 +208,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
Method method = AzureQueueAsyncClient.class.getMethod("clearMessages", String.class); Method method = AzureQueueAsyncClient.class.getMethod("clearMessages", String.class);
HttpRequest request = processor.createRequest(method, "queue"); HttpRequest request = processor.createRequest(method, "queue");
assertRequestLineEquals(request, assertRequestLineEquals(request, "DELETE https://identity.queue.core.windows.net/queue/messages HTTP/1.1");
"DELETE https://identity.queue.core.windows.net/queue/messages HTTP/1.1");
assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n"); assertNonPayloadHeadersEqual(request, "x-ms-version: 2009-09-19\n");
assertPayloadEquals(request, null, null, false); assertPayloadEquals(request, null, null, false);
@ -251,8 +233,7 @@ public class AzureQueueAsyncClientTest extends RestClientTest<AzureQueueAsyncCli
@Override @Override
public ContextSpec<?, ?> createContextSpec() { public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", return new RestContextFactory().createContextSpec("azurequeue", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -45,8 +45,8 @@ import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
public class ParseSystemAndUserMetadataFromHeaders implements public class ParseSystemAndUserMetadataFromHeaders implements Function<HttpResponse, MutableBlobMetadata>,
Function<HttpResponse, MutableBlobMetadata>, InvocationContext { InvocationContext {
private final String metadataPrefix; private final String metadataPrefix;
private final DateService dateParser; private final DateService dateParser;
private final Provider<MutableBlobMetadata> metadataFactory; private final Provider<MutableBlobMetadata> metadataFactory;
@ -55,9 +55,8 @@ public class ParseSystemAndUserMetadataFromHeaders implements
private GeneratedHttpRequest<?> request; private GeneratedHttpRequest<?> request;
@Inject @Inject
public ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, public ParseSystemAndUserMetadataFromHeaders(Provider<MutableBlobMetadata> metadataFactory, DateService dateParser,
DateService dateParser, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix, @Named(PROPERTY_USER_METADATA_PREFIX) String metadataPrefix, @Named(PROPERTY_API_VERSION) String apiVersion) {
@Named(PROPERTY_API_VERSION) String apiVersion) {
this.metadataFactory = metadataFactory; this.metadataFactory = metadataFactory;
this.dateParser = dateParser; this.dateParser = dateParser;
this.metadataPrefix = metadataPrefix; this.metadataPrefix = metadataPrefix;
@ -81,8 +80,7 @@ public class ParseSystemAndUserMetadataFromHeaders implements
void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) { void addUserMetadataTo(HttpResponse from, MutableBlobMetadata metadata) {
for (Entry<String, String> header : from.getHeaders().entries()) { for (Entry<String, String> header : from.getHeaders().entries()) {
if (header.getKey() != null && header.getKey().startsWith(metadataPrefix)) if (header.getKey() != null && header.getKey().startsWith(metadataPrefix))
metadata.getUserMetadata().put( metadata.getUserMetadata().put((header.getKey().substring(metadataPrefix.length())).toLowerCase(),
(header.getKey().substring(metadataPrefix.length())).toLowerCase(),
header.getValue()); header.getValue());
} }
} }
@ -93,12 +91,10 @@ public class ParseSystemAndUserMetadataFromHeaders implements
} }
@VisibleForTesting @VisibleForTesting
void parseLastModifiedOrThrowException(HttpResponse from, MutableBlobMetadata metadata) void parseLastModifiedOrThrowException(HttpResponse from, MutableBlobMetadata metadata) throws HttpException {
throws HttpException {
String lastModified = from.getFirstHeaderOrNull(HttpHeaders.LAST_MODIFIED); String lastModified = from.getFirstHeaderOrNull(HttpHeaders.LAST_MODIFIED);
if (lastModified == null) if (lastModified == null)
throw new HttpException(HttpHeaders.LAST_MODIFIED + " header not present in response: " throw new HttpException(HttpHeaders.LAST_MODIFIED + " header not present in response: " + from.getStatusLine());
+ from.getStatusLine());
// Eucalyptus 1.6 returns iso8601 dates // Eucalyptus 1.6 returns iso8601 dates
if (apiVersion.indexOf("Walrus-1.6") != -1) { if (apiVersion.indexOf("Walrus-1.6") != -1) {
metadata.setLastModified(dateParser.iso8601DateParse(lastModified.replace("+0000", "Z"))); metadata.setLastModified(dateParser.iso8601DateParse(lastModified.replace("+0000", "Z")));
@ -107,8 +103,7 @@ public class ParseSystemAndUserMetadataFromHeaders implements
} }
if (metadata.getLastModified() == null) if (metadata.getLastModified() == null)
throw new HttpException("could not parse: " + HttpHeaders.LAST_MODIFIED + ": " throw new HttpException("could not parse: " + HttpHeaders.LAST_MODIFIED + ": " + lastModified);
+ lastModified);
} }
@VisibleForTesting @VisibleForTesting
@ -126,18 +121,16 @@ public class ParseSystemAndUserMetadataFromHeaders implements
} }
@VisibleForTesting @VisibleForTesting
void setContentTypeOrThrowException(HttpResponse from, MutableBlobMetadata metadata) void setContentTypeOrThrowException(HttpResponse from, MutableBlobMetadata metadata) throws HttpException {
throws HttpException {
if (from.getPayload() != null) if (from.getPayload() != null)
metadata.setContentType(from.getPayload().getContentType()); metadata.setContentType(from.getPayload().getContentType());
if (metadata.getContentType() == null if (from.getStatusCode() != 204 && (metadata.getContentType() == null
|| "application/unknown".equals(metadata.getContentType())) || "application/unknown".equals(metadata.getContentType())))
throw new HttpException(HttpHeaders.CONTENT_TYPE + " not found in headers"); throw new HttpException(HttpHeaders.CONTENT_TYPE + " not found in headers");
} }
public ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request) { public ParseSystemAndUserMetadataFromHeaders setContext(HttpRequest request) {
checkArgument(request instanceof GeneratedHttpRequest<?>, checkArgument(request instanceof GeneratedHttpRequest<?>, "note this handler requires a GeneratedHttpRequest");
"note this handler requires a GeneratedHttpRequest");
this.request = (GeneratedHttpRequest<?>) request; this.request = (GeneratedHttpRequest<?>) request;
return this; return this;
} }

View File

@ -43,7 +43,11 @@ import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableMultimap;
import com.google.common.collect.Multimap; import com.google.common.collect.Multimap;
public class ParseBlobMetadataFromHeadersTest { /**
* @author Adrian Cole
*/
@Test(sequential = true)
public class ParseSystemAndUserMetadataFromHeadersTest {
private ParseSystemAndUserMetadataFromHeaders parser; private ParseSystemAndUserMetadataFromHeaders parser;
private Provider<MutableBlobMetadata> blobMetadataProvider = new Provider<MutableBlobMetadata>() { private Provider<MutableBlobMetadata> blobMetadataProvider = new Provider<MutableBlobMetadata>() {
@ -57,8 +61,8 @@ public class ParseBlobMetadataFromHeadersTest {
@BeforeTest @BeforeTest
void setUp() { void setUp() {
parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, parser = new ParseSystemAndUserMetadataFromHeaders(blobMetadataProvider, new SimpleDateFormatDateService(),
new SimpleDateFormatDateService(), "prefix", "default"); "prefix", "default");
GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class); GeneratedHttpRequest<?> request = createMock(GeneratedHttpRequest.class);
expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes(); expect(request.getEndpoint()).andReturn(URI.create("http://localhost/key")).anyTimes();
@ -77,6 +81,13 @@ public class ParseBlobMetadataFromHeadersTest {
assertEquals(metadata.getName(), "key"); assertEquals(metadata.getName(), "key");
} }
@Test
public void testNoContentOn204IsOk() {
HttpResponse from = new HttpResponse(204, "ok", Payloads.newStringPayload(""));
from.getHeaders().put(HttpHeaders.LAST_MODIFIED, "Wed, 09 Sep 2009 19:50:23 GMT");
parser.apply(from);
}
@Test @Test
public void testSetContentLength() { public void testSetContentLength() {
HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload("")); HttpResponse from = new HttpResponse(200, "ok", Payloads.newStringPayload(""));

View File

@ -23,12 +23,10 @@
*/ */
package org.jclouds.boxdotnet; package org.jclouds.boxdotnet;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.core.MediaType;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
@ -47,7 +45,6 @@ import com.google.common.util.concurrent.ListenableFuture;
* @author Adrian Cole * @author Adrian Cole
*/ */
@RequestFilters(BasicAuthentication.class) @RequestFilters(BasicAuthentication.class)
@Consumes(MediaType.APPLICATION_JSON)
public interface BoxDotNetAsyncClient { public interface BoxDotNetAsyncClient {
/* /*
* TODO: define interface methods for BoxDotNet * TODO: define interface methods for BoxDotNet

View File

@ -57,7 +57,7 @@ public class BoxDotNetAsyncClientTest extends RestClientTest<BoxDotNetAsyncClien
GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
// now make sure request filters apply by replaying // now make sure request filters apply by replaying
@ -65,9 +65,10 @@ public class BoxDotNetAsyncClientTest extends RestClientTest<BoxDotNetAsyncClien
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items HTTP/1.1");
// for example, using basic authentication, we should get "only one" header // for example, using basic authentication, we should get "only one"
// header
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest,
"Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); "Authorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
// TODO: insert expected response class, which probably extends ParseJson // TODO: insert expected response class, which probably extends ParseJson
@ -84,7 +85,7 @@ public class BoxDotNetAsyncClientTest extends RestClientTest<BoxDotNetAsyncClien
GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method, 1); GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method, 1);
assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items/1 HTTP/1.1"); assertRequestLineEquals(httpRequest, "GET https://www.box.net/api/1.0/rest/items/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
// TODO: insert expected response class, which probably extends ParseJson // TODO: insert expected response class, which probably extends ParseJson
@ -101,9 +102,8 @@ public class BoxDotNetAsyncClientTest extends RestClientTest<BoxDotNetAsyncClien
Method method = BoxDotNetAsyncClient.class.getMethod("delete", long.class); Method method = BoxDotNetAsyncClient.class.getMethod("delete", long.class);
GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method, 1); GeneratedHttpRequest<BoxDotNetAsyncClient> httpRequest = processor.createRequest(method, 1);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "DELETE https://www.box.net/api/1.0/rest/items/1 HTTP/1.1");
"DELETE https://www.box.net/api/1.0/rest/items/1 HTTP/1.1"); assertNonPayloadHeadersEqual(httpRequest, "");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -128,7 +128,7 @@ public class BoxDotNetAsyncClientTest extends RestClientTest<BoxDotNetAsyncClien
@Override @Override
public ContextSpec<BoxDotNetClient, BoxDotNetAsyncClient> createContextSpec() { public ContextSpec<BoxDotNetClient, BoxDotNetAsyncClient> createContextSpec() {
return contextSpec("boxdotnet", "https://www.box.net/api/1.0/rest", "1.0", "identity", return contextSpec("boxdotnet", "https://www.box.net/api/1.0/rest", "1.0", "identity", "credential",
"credential", BoxDotNetClient.class, BoxDotNetAsyncClient.class); BoxDotNetClient.class, BoxDotNetAsyncClient.class);
} }
} }

View File

@ -40,21 +40,22 @@ import org.jclouds.chef.binders.BindChecksumsToJsonPayload;
import org.jclouds.chef.binders.BindClientnameToJsonPayload; import org.jclouds.chef.binders.BindClientnameToJsonPayload;
import org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload; import org.jclouds.chef.binders.BindGenerateKeyForClientToJsonPayload;
import org.jclouds.chef.binders.BindIsCompletedToJsonPayload; import org.jclouds.chef.binders.BindIsCompletedToJsonPayload;
import org.jclouds.chef.binders.NodeName;
import org.jclouds.chef.domain.CookbookVersion; import org.jclouds.chef.domain.CookbookVersion;
import org.jclouds.chef.domain.Node;
import org.jclouds.chef.domain.Sandbox; import org.jclouds.chef.domain.Sandbox;
import org.jclouds.chef.domain.UploadSandbox; import org.jclouds.chef.domain.UploadSandbox;
import org.jclouds.chef.filters.SignedHeaderAuth; import org.jclouds.chef.filters.SignedHeaderAuth;
import org.jclouds.chef.functions.ParseCookbookVersionFromJson;
import org.jclouds.chef.functions.ParseKeyFromJson; import org.jclouds.chef.functions.ParseKeyFromJson;
import org.jclouds.chef.functions.ParseKeySetFromJson; import org.jclouds.chef.functions.ParseKeySetFromJson;
import org.jclouds.chef.functions.ParseSandboxFromJson; import org.jclouds.http.functions.ReturnStringIf2xx;
import org.jclouds.chef.functions.ParseUploadSiteFromJson;
import org.jclouds.chef.functions.ParseValueSetFromJson;
import org.jclouds.rest.annotations.BinderParam; import org.jclouds.rest.annotations.BinderParam;
import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.Headers; import org.jclouds.rest.annotations.Headers;
import org.jclouds.rest.annotations.ParamParser;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.rest.binders.BindToJsonPayload; import org.jclouds.rest.binders.BindToJsonPayload;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
@ -71,8 +72,8 @@ import com.google.common.util.concurrent.ListenableFuture;
* @author Adrian Cole * @author Adrian Cole
*/ */
@RequestFilters(SignedHeaderAuth.class) @RequestFilters(SignedHeaderAuth.class)
@Consumes(MediaType.APPLICATION_JSON)
@Headers(keys = "X-Chef-Version", values = ChefAsyncClient.VERSION) @Headers(keys = "X-Chef-Version", values = ChefAsyncClient.VERSION)
@Consumes(MediaType.APPLICATION_JSON)
public interface ChefAsyncClient { public interface ChefAsyncClient {
public static final String VERSION = "0.9.6"; public static final String VERSION = "0.9.6";
@ -81,20 +82,17 @@ public interface ChefAsyncClient {
*/ */
@POST @POST
@Path("sandboxes") @Path("sandboxes")
@ResponseParser(ParseUploadSiteFromJson.class)
ListenableFuture<UploadSandbox> getUploadSandboxForChecksums( ListenableFuture<UploadSandbox> getUploadSandboxForChecksums(
@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s); @BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
@PUT @PUT
ListenableFuture<Void> uploadContent( ListenableFuture<Void> uploadContent(@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
/** /**
* @see ChefClient#commitSandbox * @see ChefClient#commitSandbox
*/ */
@PUT @PUT
@Path("sandboxes/{id}") @Path("sandboxes/{id}")
@ResponseParser(ParseSandboxFromJson.class)
ListenableFuture<Sandbox> commitSandbox(@PathParam("id") String id, ListenableFuture<Sandbox> commitSandbox(@PathParam("id") String id,
@BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted); @BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted);
@ -112,8 +110,7 @@ public interface ChefAsyncClient {
@PUT @PUT
@Path("cookbooks/{cookbookname}/{version}") @Path("cookbooks/{cookbookname}/{version}")
ListenableFuture<Void> updateCookbook(@PathParam("cookbookname") String cookbookName, ListenableFuture<Void> updateCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version, @PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);
@BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);
/** /**
* @see ChefCookbook#deleteCookbook(String) * @see ChefCookbook#deleteCookbook(String)
@ -129,17 +126,15 @@ public interface ChefAsyncClient {
*/ */
@GET @GET
@Path("cookbooks/{cookbookname}") @Path("cookbooks/{cookbookname}")
@ResponseParser(ParseValueSetFromJson.class) @Unwrap
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Set<String>> getVersionsOfCookbook( ListenableFuture<Set<String>> getVersionsOfCookbook(@PathParam("cookbookname") String cookbookName);
@PathParam("cookbookname") String cookbookName);
/** /**
* @see ChefCookbook#getCookbook * @see ChefCookbook#getCookbook
*/ */
@GET @GET
@Path("cookbooks/{cookbookname}/{version}") @Path("cookbooks/{cookbookname}/{version}")
@ResponseParser(ParseCookbookVersionFromJson.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<CookbookVersion> getCookbook(@PathParam("cookbookname") String cookbookName, ListenableFuture<CookbookVersion> getCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version); @PathParam("version") String version);
@ -150,8 +145,7 @@ public interface ChefAsyncClient {
@POST @POST
@Path("clients") @Path("clients")
@ResponseParser(ParseKeyFromJson.class) @ResponseParser(ParseKeyFromJson.class)
ListenableFuture<String> createClient( ListenableFuture<String> createClient(@BinderParam(BindClientnameToJsonPayload.class) String clientname);
@BinderParam(BindClientnameToJsonPayload.class) String clientname);
/** /**
* @see ChefClient#generateKeyForClient * @see ChefClient#generateKeyForClient
@ -184,6 +178,8 @@ public interface ChefAsyncClient {
@DELETE @DELETE
@Path("clients/{clientname}") @Path("clients/{clientname}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@ResponseParser(ReturnStringIf2xx.class)
// TODO: why string?
ListenableFuture<String> deleteClient(@PathParam("clientname") String clientname); ListenableFuture<String> deleteClient(@PathParam("clientname") String clientname);
/** /**
@ -194,4 +190,51 @@ public interface ChefAsyncClient {
@ResponseParser(ParseKeySetFromJson.class) @ResponseParser(ParseKeySetFromJson.class)
ListenableFuture<Set<String>> listClients(); ListenableFuture<Set<String>> listClients();
/**
* @see ChefClient#createNode
*/
@POST
@Path("nodes")
ListenableFuture<Node> createNode(@BinderParam(BindToJsonPayload.class) Node node);
/**
* @see ChefClient#updateNode
*/
@PUT
@Path("nodes/{nodename}")
ListenableFuture<Node> updateNode(
@PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node);
/**
* @see ChefNode#nodeExists
*/
@HEAD
@Path("nodes/{nodename}")
@ExceptionParser(ReturnFalseOnNotFoundOr404.class)
ListenableFuture<Boolean> nodeExists(@PathParam("nodename") String nodename);
/**
* @see ChefNode#getNode
*/
@GET
@Path("nodes/{nodename}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<Node> getNode(@PathParam("nodename") String nodename);
/**
* @see ChefNode#deleteNode
*/
@DELETE
@Path("nodes/{nodename}")
// TODO why string?!
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<String> deleteNode(@PathParam("nodename") String nodename);
/**
* @see ChefNode#listNodes
*/
@GET
@Path("nodes")
@ResponseParser(ParseKeySetFromJson.class)
ListenableFuture<Set<String>> listNodes();
} }

View File

@ -0,0 +1,38 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.chef.binders;
import javax.inject.Singleton;
import org.jclouds.chef.domain.Node;
import com.google.common.base.Function;
/**
*
* @author Adrian Cole
*/
@Singleton
public class NodeName implements Function<Object, String> {
public String apply(Object from) {
return ((Node) from).getName();
}
}

View File

@ -130,7 +130,6 @@ public class BaseChefRestClientModule<S, A> extends RestClientModule<S, A> {
@Override @Override
protected void configure() { protected void configure() {
install(new ChefTypeAdapterModule());
bind(DateAdapter.class).to(Iso8601DateAdapter.class); bind(DateAdapter.class).to(Iso8601DateAdapter.class);
super.configure(); super.configure();
} }

View File

@ -1,139 +0,0 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.config;
import static org.jclouds.Constants.PROPERTY_GSON_ADAPTERS;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.jclouds.encryption.EncryptionService;
import com.google.common.collect.Maps;
import com.google.common.primitives.Bytes;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import com.google.inject.AbstractModule;
import com.google.inject.Provides;
/**
* Configures the Chef connection.
*
* @author Adrian Cole
*/
public class ChefTypeAdapterModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
@Named(PROPERTY_GSON_ADAPTERS)
public Map<Type, Object> provideCustomAdapterBindings(HexByteListAdapter byteListAdapter,
HexByteArrayAdapter byteArrayAdapter) {
Map<Type, Object> bindings = Maps.newHashMap();
bindings.put(new TypeToken<List<Byte>>() {
}.getType(), byteListAdapter);
bindings.put(byte[].class, byteArrayAdapter);
return bindings;
}
@Singleton
public static class HexByteListAdapter implements JsonDeserializer<List<Byte>>,
JsonSerializer<List<Byte>> {
private final EncryptionService encryptionService;
@Inject
HexByteListAdapter(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
@Override
public List<Byte> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return Bytes.asList(encryptionService.fromHex(json.getAsString()));
}
@Override
public JsonElement serialize(List<Byte> src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(encryptionService.hex(Bytes.toArray(src)));
}
}
@Singleton
public static class HexByteArrayAdapter implements JsonDeserializer<byte[]>,
JsonSerializer<byte[]> {
private final EncryptionService encryptionService;
@Inject
HexByteArrayAdapter(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
@Override
public byte[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
return encryptionService.fromHex(json.getAsString());
}
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(encryptionService.hex(src));
}
}
}

View File

@ -0,0 +1,162 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.chef.domain;
import java.util.List;
import java.util.Map;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.gson.annotations.SerializedName;
/**
* Sandbox object.
*
* @author Adrian Cole
*/
public class Node {
private String name;
private Map<String, Attribute> normal = Maps.newLinkedHashMap();
private Map<String, Attribute> override = Maps.newLinkedHashMap();
@SerializedName("default")
private Map<String, Attribute> defaultA = Maps.newLinkedHashMap();
private Map<String, Attribute> automatic = Maps.newLinkedHashMap();
@SerializedName("run_list")
private List<String> runList = Lists.newArrayList();
// internal
@SuppressWarnings("unused")
@SerializedName("json_class")
private String _jsonClass = "Chef::Node";
public Node(String name, Map<String, Attribute> normal,
Map<String, Attribute> override, Map<String, Attribute> defaultA,
Map<String, Attribute> automatic, Iterable<String> runList) {
this.name = name;
this.normal.putAll(normal);
this.override.putAll(override);
this.defaultA.putAll(defaultA);
this.automatic.putAll(automatic);
Iterables.addAll(this.runList, runList);
}
@Override
public String toString() {
return "Node [name=" + name + ", runList=" + runList + ", normal="
+ normal + ", default=" + defaultA + ", override=" + override
+ ", automatic=" + automatic + "]";
}
public Node(String name, Iterable<String> runList) {
this.name = name;
Iterables.addAll(this.runList, runList);
}
// hidden but needs to be here for json deserialization to work
Node() {
}
public String getName() {
return name;
}
public Map<String, Attribute> getNormal() {
return normal;
}
public Map<String, Attribute> getOverride() {
return override;
}
public Map<String, Attribute> getDefault() {
return defaultA;
}
public Map<String, Attribute> getAutomatic() {
return automatic;
}
public List<String> getRunList() {
return runList;
}
@SerializedName("chef_type")
@SuppressWarnings("unused")
private String _chefType = "node";
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((automatic == null) ? 0 : automatic.hashCode());
result = prime * result + ((defaultA == null) ? 0 : defaultA.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((normal == null) ? 0 : normal.hashCode());
result = prime * result + ((override == null) ? 0 : override.hashCode());
result = prime * result + ((runList == null) ? 0 : runList.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (automatic == null) {
if (other.automatic != null)
return false;
} else if (!automatic.equals(other.automatic))
return false;
if (defaultA == null) {
if (other.defaultA != null)
return false;
} else if (!defaultA.equals(other.defaultA))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (normal == null) {
if (other.normal != null)
return false;
} else if (!normal.equals(other.normal))
return false;
if (override == null) {
if (other.override != null)
return false;
} else if (!override.equals(other.override))
return false;
if (runList == null) {
if (other.runList != null)
return false;
} else if (!runList.equals(other.runList))
return false;
return true;
}
}

View File

@ -1,58 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.chef.domain.CookbookVersion;
import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson;
/**
*
*
* @author Adrian Cole
*/
@Singleton
public class ParseCookbookVersionFromJson extends ParseJson<CookbookVersion> {
@Inject
public ParseCookbookVersionFromJson(Gson gson) {
super(gson);
}
@Override
protected CookbookVersion apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), CookbookVersion.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -41,41 +41,33 @@
*/ */
package org.jclouds.chef.functions; package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseKeySetFromJson extends ParseJson<Set<String>> { public class ParseKeySetFromJson implements Function<HttpResponse, Set<String>> {
private final ParseJson<Map<String, String>> json;
@Inject @Inject
public ParseKeySetFromJson(Gson gson) { ParseKeySetFromJson(ParseJson<Map<String, String>> json) {
super(gson); this.json = json;
} }
@SuppressWarnings("unchecked")
@Override @Override
protected Set<String> apply(InputStream stream) { public Set<String> apply(HttpResponse arg0) {
try { return json.apply(arg0).keySet();
Type map = new TypeToken<Map<String, String>>() {
}.getType();
return ((Map<String, String>) gson.fromJson(new InputStreamReader(stream, "UTF-8"), map))
.keySet();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -1,74 +0,0 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.chef.domain.Organization;
import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson;
/**
* @author Adrian Cole
*/
@Singleton
public class ParseOrganizationFromJson extends ParseJson<Organization> {
@Inject
public ParseOrganizationFromJson(Gson gson) {
super(gson);
}
@Override
protected Organization apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), Organization.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -1,58 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.chef.domain.Sandbox;
import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson;
/**
*
*
* @author Adrian Cole
*/
@Singleton
public class ParseSandboxFromJson extends ParseJson<Sandbox> {
@Inject
public ParseSandboxFromJson(Gson gson) {
super(gson);
}
@Override
protected Sandbox apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), Sandbox.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -1,58 +0,0 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.chef.domain.UploadSandbox;
import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson;
/**
*
*
* @author Adrian Cole
*/
@Singleton
public class ParseUploadSiteFromJson extends ParseJson<UploadSandbox> {
@Inject
public ParseUploadSiteFromJson(Gson gson) {
super(gson);
}
@Override
protected UploadSandbox apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), UploadSandbox.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -1,75 +0,0 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.chef.domain.User;
import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson;
/**
* @author Adrian Cole
*/
@Singleton
public class ParseUserFromJson extends ParseJson<User> {
@Inject
public ParseUserFromJson(Gson gson) {
super(gson);
}
@Override
protected User apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), User.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -1,83 +0,0 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.chef.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.http.functions.ParseJson;
import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* @author Adrian Cole
*/
@Singleton
public class ParseValueSetFromJson extends ParseJson<Set<String>> {
@Inject
public ParseValueSetFromJson(Gson gson) {
super(gson);
}
@SuppressWarnings("unchecked")
@Override
protected Set<String> apply(InputStream stream) {
try {
Type map = new TypeToken<Map<String, Set<String>>>() {
}.getType();
return Iterables.get(
((Map<String, Set<String>>) gson.fromJson(new InputStreamReader(stream, "UTF-8"),
map)).entrySet(), 0).getValue();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -34,15 +34,13 @@ import org.jclouds.chef.config.ChefRestClientModule;
import org.jclouds.chef.domain.CookbookVersion; import org.jclouds.chef.domain.CookbookVersion;
import org.jclouds.chef.filters.SignedHeaderAuth; import org.jclouds.chef.filters.SignedHeaderAuth;
import org.jclouds.chef.filters.SignedHeaderAuthTest; import org.jclouds.chef.filters.SignedHeaderAuthTest;
import org.jclouds.chef.functions.ParseCookbookVersionFromJson;
import org.jclouds.chef.functions.ParseKeyFromJson; import org.jclouds.chef.functions.ParseKeyFromJson;
import org.jclouds.chef.functions.ParseKeySetFromJson; import org.jclouds.chef.functions.ParseKeySetFromJson;
import org.jclouds.chef.functions.ParseSandboxFromJson;
import org.jclouds.chef.functions.ParseUploadSiteFromJson;
import org.jclouds.date.TimeStamp; import org.jclouds.date.TimeStamp;
import org.jclouds.encryption.EncryptionService; import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.RequiresHttp; import org.jclouds.http.RequiresHttp;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.ReturnStringIf2xx; import org.jclouds.http.functions.ReturnStringIf2xx;
import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.ReturnTrueIf2xx;
@ -81,7 +79,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(httpRequest, "{\"is_completed\":\"true\"}", "application/json", false); assertPayloadEquals(httpRequest, "{\"is_completed\":\"true\"}", "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseSandboxFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -89,17 +87,12 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
} }
public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, public void testGetUploadSandboxForChecksums() throws SecurityException, NoSuchMethodException, IOException {
IOException {
EncryptionService encryptionService = injector.getInstance(EncryptionService.class); EncryptionService encryptionService = injector.getInstance(EncryptionService.class);
Method method = ChefAsyncClient.class.getMethod("getUploadSandboxForChecksums", Set.class); Method method = ChefAsyncClient.class.getMethod("getUploadSandboxForChecksums", Set.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, ImmutableSet.of(Bytes
ImmutableSet .asList(encryptionService.fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes.asList(encryptionService
.of(Bytes.asList(encryptionService .fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes.asList(encryptionService
.fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes
.asList(encryptionService
.fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes
.asList(encryptionService
.fromHex("1dda05ed139664f1f89b9dec482b77c0")))); .fromHex("1dda05ed139664f1f89b9dec482b77c0"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1"); assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
@ -108,7 +101,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}", "{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}",
"application/json", false); "application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseUploadSiteFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -118,14 +111,12 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testGetCookbook() throws SecurityException, NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod("getCookbook", String.class, String.class); Method method = ChefAsyncClient.class.getMethod("getCookbook", String.class, String.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "cookbook", "1.0.0");
"cookbook", "1.0.0"); assertRequestLineEquals(httpRequest, "GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertRequestLineEquals(httpRequest,
"GET http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseCookbookVersionFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -135,10 +126,8 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteCookbook() throws SecurityException, NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod("deleteCookbook", String.class, String.class); Method method = ChefAsyncClient.class.getMethod("deleteCookbook", String.class, String.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "cookbook", "1.0.0");
"cookbook", "1.0.0"); assertRequestLineEquals(httpRequest, "DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertRequestLineEquals(httpRequest,
"DELETE http://localhost:4000/cookbooks/cookbook/1.0.0 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -153,11 +142,10 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException { public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod("updateCookbook", String.class, String.class, Method method = ChefAsyncClient.class.getMethod("updateCookbook", String.class, String.class,
CookbookVersion.class); CookbookVersion.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "cookbook", "1.0.1",
"cookbook", "1.0.1", new CookbookVersion("cookbook", "1.0.1")); new CookbookVersion("cookbook", "1.0.1"));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1");
"PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals( assertPayloadEquals(
httpRequest, httpRequest,
@ -217,14 +205,12 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
} }
public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, public void testGenerateKeyForClient() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = ChefAsyncClient.class.getMethod("generateKeyForClient", String.class); Method method = ChefAsyncClient.class.getMethod("generateKeyForClient", String.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "client"); GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "client");
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1"); assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/clients/client HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(httpRequest, "{\"clientname\":\"client\", \"private_key\": true}", assertPayloadEquals(httpRequest, "{\"clientname\":\"client\", \"private_key\": true}", "application/json", false);
"application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseKeyFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseKeyFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -295,7 +281,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
@Override @Override
public ContextSpec<ChefClient, ChefAsyncClient> createContextSpec() { public ContextSpec<ChefClient, ChefAsyncClient> createContextSpec() {
return new RestContextFactory().createContextSpec("chef", "user", return new RestContextFactory().createContextSpec("chef", "user", SignedHeaderAuthTest.PRIVATE_KEY,
SignedHeaderAuthTest.PRIVATE_KEY, new Properties()); new Properties());
} }
} }

View File

@ -6,7 +6,6 @@ import java.io.IOException;
import java.net.URI; import java.net.URI;
import java.util.Set; import java.util.Set;
import org.jclouds.chef.config.ChefTypeAdapterModule;
import org.jclouds.chef.domain.Attribute; import org.jclouds.chef.domain.Attribute;
import org.jclouds.chef.domain.CookbookVersion; import org.jclouds.chef.domain.CookbookVersion;
import org.jclouds.chef.domain.Metadata; import org.jclouds.chef.domain.Metadata;
@ -14,6 +13,7 @@ import org.jclouds.chef.domain.Resource;
import org.jclouds.encryption.EncryptionService; import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads; import org.jclouds.http.Payloads;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
@ -24,6 +24,8 @@ import com.google.common.collect.ImmutableSet;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code ParseCookbookVersionFromJson} * Tests behavior of {@code ParseCookbookVersionFromJson}
@ -33,50 +35,58 @@ import com.google.inject.Injector;
@Test(groups = "unit", sequential = true, testName = "chef.ParseCookbookVersionFromJsonTest") @Test(groups = "unit", sequential = true, testName = "chef.ParseCookbookVersionFromJsonTest")
public class ParseCookbookVersionFromJsonTest { public class ParseCookbookVersionFromJsonTest {
private ParseCookbookVersionFromJson handler; private ParseJson<CookbookVersion> handler;
private Injector injector; private Injector injector;
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new ParserModule(), new ChefTypeAdapterModule()); injector = Guice.createInjector(new ParserModule());
handler = injector.getInstance(ParseCookbookVersionFromJson.class); handler = injector.getInstance(Key
.get(new TypeLiteral<ParseJson<CookbookVersion>>() {
}));
} }
@Test(enabled = false) @Test(enabled = false)
public void testBrew() throws IOException { public void testBrew() throws IOException {
CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok",
.newPayload(ParseCookbookVersionFromJsonTest.class Payloads.newPayload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/brew-cookbook.json")))); .getResourceAsStream("/brew-cookbook.json"))));
assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads
.toInputStream(new Gson().toJson(cookbook)))))); .newPayload(Utils.toInputStream(new Gson().toJson(cookbook))))));
} }
@Test(enabled = false) @Test(enabled = false)
public void testTomcat() { public void testTomcat() {
CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok",
.newPayload(ParseCookbookVersionFromJsonTest.class Payloads.newPayload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/tomcat-cookbook.json")))); .getResourceAsStream("/tomcat-cookbook.json"))));
assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads
.toInputStream(new Gson().toJson(cookbook)))))); .newPayload(Utils.toInputStream(new Gson().toJson(cookbook))))));
} }
@Test(enabled = false) @Test(enabled = false)
public void testMysql() throws IOException { public void testMysql() throws IOException {
CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok", Payloads CookbookVersion cookbook = handler.apply(new HttpResponse(200, "ok",
.newPayload(ParseCookbookVersionFromJsonTest.class Payloads.newPayload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/mysql-cookbook.json")))); .getResourceAsStream("/mysql-cookbook.json"))));
assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils assertEquals(cookbook, handler.apply(new HttpResponse(200, "ok", Payloads
.toInputStream(new Gson().toJson(cookbook)))))); .newPayload(Utils.toInputStream(new Gson().toJson(cookbook))))));
} }
@Test(enabled = false) @Test(enabled = false)
public void testApache() { public void testApache() {
EncryptionService encryptionService = injector.getInstance(EncryptionService.class); EncryptionService encryptionService = injector
.getInstance(EncryptionService.class);
assertEquals( assertEquals(
handler.apply(new HttpResponse(200, "ok", Payloads handler
.apply(new HttpResponse(
200,
"ok",
Payloads
.newPayload(ParseCookbookVersionFromJsonTest.class .newPayload(ParseCookbookVersionFromJsonTest.class
.getResourceAsStream("/apache-chef-demo-cookbook.json")))), .getResourceAsStream("/apache-chef-demo-cookbook.json")))),
new CookbookVersion( new CookbookVersion(
@ -84,14 +94,14 @@ public class ParseCookbookVersionFromJsonTest {
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
ImmutableSet.<Resource> of(), ImmutableSet.<Resource> of(),
new Metadata("Apache v2.0", "Your Name", new Metadata("Apache v2.0", "Your Name", ImmutableMap
ImmutableMap.<String, String> of(), ImmutableMap .<String, String> of(), ImmutableMap
.<String, Set<String>> of(), "youremail@example.com", .<String, Set<String>> of(), "youremail@example.com",
ImmutableMap.<String, Set<String>> of(), ImmutableMap.<String, Set<String>> of(),
"A fabulous new cookbook", "A fabulous new cookbook", ImmutableMap
ImmutableMap.<String, Set<String>> of(), ImmutableMap .<String, Set<String>> of(), ImmutableMap
.<String, Set<String>> of(), "0.0.0", ImmutableMap .<String, Set<String>> of(), "0.0.0",
.<String, String> of(), ImmutableMap ImmutableMap.<String, String> of(), ImmutableMap
.<String, Set<String>> of(), "apache-chef-demo", .<String, Set<String>> of(), "apache-chef-demo",
ImmutableMap.<String, String> of(), "", ImmutableMap ImmutableMap.<String, String> of(), "", ImmutableMap
.<String, Attribute> of(), ImmutableMap .<String, Attribute> of(), ImmutableMap

View File

@ -25,6 +25,7 @@ import java.io.IOException;
import org.jclouds.chef.domain.Organization; import org.jclouds.chef.domain.Organization;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads; import org.jclouds.http.Payloads;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
@ -32,6 +33,8 @@ import org.testng.annotations.Test;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code ParseOrganizationFromJson} * Tests behavior of {@code ParseOrganizationFromJson}
@ -41,12 +44,14 @@ import com.google.inject.Injector;
@Test(groups = "unit", sequential = true, testName = "chef.ParseOrganizationFromJsonTest") @Test(groups = "unit", sequential = true, testName = "chef.ParseOrganizationFromJsonTest")
public class ParseOrganizationFromJsonTest { public class ParseOrganizationFromJsonTest {
private ParseOrganizationFromJson handler; private ParseJson<Organization> handler;
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
handler = injector.getInstance(ParseOrganizationFromJson.class); handler = injector.getInstance(Key
.get(new TypeLiteral<ParseJson<Organization>>() {
}));
} }
public void test() { public void test() {
@ -58,7 +63,7 @@ public class ParseOrganizationFromJsonTest {
String toParse = "{\"name\": \"opscode\",\"full_name\": \"Opscode, Inc.\", \"org_type\": \"Business\",\"clientname\": \"opscode-validator\" }"; String toParse = "{\"name\": \"opscode\",\"full_name\": \"Opscode, Inc.\", \"org_type\": \"Business\",\"clientname\": \"opscode-validator\" }";
assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads
.toInputStream(toParse)))), org); .newPayload(Utils.toInputStream(toParse)))), org);
} }
} }

View File

@ -8,6 +8,7 @@ import org.jclouds.chef.domain.Sandbox;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads; import org.jclouds.http.Payloads;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.http.functions.config.ParserModule.DateAdapter; import org.jclouds.http.functions.config.ParserModule.DateAdapter;
import org.jclouds.http.functions.config.ParserModule.Iso8601DateAdapter; import org.jclouds.http.functions.config.ParserModule.Iso8601DateAdapter;
@ -18,6 +19,8 @@ import com.google.common.collect.ImmutableSet;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code ParseSandboxFromJson} * Tests behavior of {@code ParseSandboxFromJson}
@ -27,12 +30,13 @@ import com.google.inject.Injector;
@Test(groups = "unit", sequential = true, testName = "chef.ParseSandboxFromJsonTest") @Test(groups = "unit", sequential = true, testName = "chef.ParseSandboxFromJsonTest")
public class ParseSandboxFromJsonTest { public class ParseSandboxFromJsonTest {
private ParseSandboxFromJson handler; private ParseJson<Sandbox> handler;
private DateService dateService; private DateService dateService;
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule(), new AbstractModule() { Injector injector = Guice.createInjector(new ParserModule(),
new AbstractModule() {
@Override @Override
protected void configure() { protected void configure() {
@ -40,16 +44,19 @@ public class ParseSandboxFromJsonTest {
} }
}); });
handler = injector.getInstance(ParseSandboxFromJson.class); handler = injector.getInstance(Key
.get(new TypeLiteral<ParseJson<Sandbox>>() {
}));
dateService = injector.getInstance(DateService.class); dateService = injector.getInstance(DateService.class);
} }
public void test() { public void test() {
assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads
.newPayload(ParseSandboxFromJsonTest.class.getResourceAsStream("/sandbox.json")))), .newPayload(ParseSandboxFromJsonTest.class
new Sandbox("1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, dateService .getResourceAsStream("/sandbox.json")))), new Sandbox(
.iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"), ImmutableSet "1-8c27b0ea4c2b7aaedbb44cfbdfcc11b2", false, dateService
.<String> of(), "f9d6d9b72bae465890aae87969f98a9c", .iso8601SecondsDateParse("2010-07-07T03:36:00+00:00"),
ImmutableSet.<String> of(), "f9d6d9b72bae465890aae87969f98a9c",
"f9d6d9b72bae465890aae87969f98a9c")); "f9d6d9b72bae465890aae87969f98a9c"));
} }
} }

View File

@ -0,0 +1,74 @@
package org.jclouds.chef.functions;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.jclouds.chef.domain.ChecksumStatus;
import org.jclouds.chef.domain.UploadSandbox;
import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Bytes;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseUploadSiteFromJson}
*
* @author Adrian Cole
*/
@Test(groups = "unit", sequential = true, testName = "chef.ParseUploadSiteFromJsonTest")
public class ParseUploadSandboxFromJsonTest {
private ParseJson<UploadSandbox> handler;
private Injector injector;
@BeforeTest
protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new ParserModule());
handler = injector.getInstance(Key
.get(new TypeLiteral<ParseJson<UploadSandbox>>() {
}));
}
public void test() {
EncryptionService encryptionService = injector
.getInstance(EncryptionService.class);
assertEquals(
handler.apply(new HttpResponse(200, "ok", Payloads
.newPayload(ParseUploadSandboxFromJsonTest.class
.getResourceAsStream("/upload-site.json")))),
new UploadSandbox(
URI
.create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"),
ImmutableMap
.<List<Byte>, ChecksumStatus> of(
Bytes
.asList(encryptionService
.fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")),
new ChecksumStatus(
URI
.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"),
true),
Bytes
.asList(encryptionService
.fromHex("0189e76ccc476701d6b374e5a1a27347")),
new ChecksumStatus(),
Bytes
.asList(encryptionService
.fromHex("1dda05ed139664f1f89b9dec482b77c0")),
new ChecksumStatus()),
"d454f71e2a5f400c808d0c5d04c2c88c"));
}
}

View File

@ -1,63 +0,0 @@
package org.jclouds.chef.functions;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.jclouds.chef.config.ChefTypeAdapterModule;
import org.jclouds.chef.domain.ChecksumStatus;
import org.jclouds.chef.domain.UploadSandbox;
import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Bytes;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseUploadSiteFromJson}
*
* @author Adrian Cole
*/
@Test(groups = "unit", sequential = true, testName = "chef.ParseUploadSiteFromJsonTest")
public class ParseUploadSiteFromJsonTest {
private ParseUploadSiteFromJson handler;
private Injector injector;
@BeforeTest
protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new ParserModule(), new ChefTypeAdapterModule());
handler = injector.getInstance(ParseUploadSiteFromJson.class);
}
public void test() {
EncryptionService encryptionService = injector.getInstance(EncryptionService.class);
assertEquals(
handler.apply(new HttpResponse(200, "ok", Payloads
.newPayload(ParseUploadSiteFromJsonTest.class
.getResourceAsStream("/upload-site.json")))),
new UploadSandbox(
URI
.create("https://api.opscode.com/organizations/jclouds/sandboxes/d454f71e2a5f400c808d0c5d04c2c88c"),
ImmutableMap
.<List<Byte>, ChecksumStatus> of(
Bytes.asList(encryptionService
.fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")),
new ChecksumStatus(
URI
.create("https://s3.amazonaws.com/opscode-platform-production-data/organization-486ca3ac66264fea926aa0b4ff74341c/sandbox-d454f71e2a5f400c808d0c5d04c2c88c/checksum-0c5ecd7788cf4f6c7de2a57193897a6c?AWSAccessKeyId=AKIAJOZTD2N26S7W6APA&Expires=1277344702&Signature=FtKyqvYEjhhEKmRY%2B0M8aGPMM7g%3D"),
true), Bytes.asList(encryptionService
.fromHex("0189e76ccc476701d6b374e5a1a27347")),
new ChecksumStatus(), Bytes.asList(encryptionService
.fromHex("1dda05ed139664f1f89b9dec482b77c0")),
new ChecksumStatus()), "d454f71e2a5f400c808d0c5d04c2c88c"));
}
}

View File

@ -7,6 +7,7 @@ import java.io.IOException;
import org.jclouds.chef.domain.User; import org.jclouds.chef.domain.User;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads; import org.jclouds.http.Payloads;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.Utils; import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
@ -14,6 +15,8 @@ import org.testng.annotations.Test;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/** /**
* Tests behavior of {@code ParseUserFromJson} * Tests behavior of {@code ParseUserFromJson}
@ -23,12 +26,14 @@ import com.google.inject.Injector;
@Test(groups = "unit", sequential = true, testName = "chef.ParseUserFromJsonTest") @Test(groups = "unit", sequential = true, testName = "chef.ParseUserFromJsonTest")
public class ParseUserFromJsonTest { public class ParseUserFromJsonTest {
private ParseUserFromJson handler; private ParseJson<User> handler;
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule()); Injector injector = Guice.createInjector(new ParserModule());
handler = injector.getInstance(ParseUserFromJson.class); handler = injector.getInstance(Key
.get(new TypeLiteral<ParseJson<User>>() {
}));
} }
public void test() { public void test() {
@ -42,7 +47,7 @@ public class ParseUserFromJsonTest {
String toParse = "{\n\"username\": \"bobo\",\n\"first_name\": \"Bobo\",\n\"middle_name\": \"Tiberion\",\n\"last_name\": \"Clown\",\n\"display_name\": \"Bobo T. Clown\",\n\"email\": \"bobo@clownco.com\" \n}"; String toParse = "{\n\"username\": \"bobo\",\n\"first_name\": \"Bobo\",\n\"middle_name\": \"Tiberion\",\n\"last_name\": \"Clown\",\n\"display_name\": \"Bobo T. Clown\",\n\"email\": \"bobo@clownco.com\" \n}";
assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads
.toInputStream(toParse)))), user); .newPayload(Utils.toInputStream(toParse)))), user);
} }
} }

View File

@ -1,39 +0,0 @@
package org.jclouds.chef.functions;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
/**
* Tests behavior of {@code ParseValueSetFromJson}
*
* @author Adrian Cole
*/
@Test(groups = "unit", sequential = true, testName = "chef.ParseValueSetFromJsonTest")
public class ParseValueSetFromJsonTest {
private ParseValueSetFromJson handler;
@BeforeTest
protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule());
handler = injector.getInstance(ParseValueSetFromJson.class);
}
public void testRegex() {
assertEquals(handler.apply(new HttpResponse(200, "ok", Payloads.newPayload(Utils
.toInputStream("{\"runit\":[\"0.7.0\",\"0.7.1\"]}")))), ImmutableSet.of("0.7.0",
"0.7.1"));
}
}

View File

@ -19,6 +19,11 @@
package org.jclouds.compute.internal; package org.jclouds.compute.internal;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Predicates.and;
import static com.google.common.collect.Iterables.filter;
import static com.google.common.collect.Iterables.find;
import static com.google.common.collect.Lists.newArrayList;
import static org.jclouds.util.Utils.multiMax;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -42,15 +47,12 @@ import org.jclouds.compute.options.TemplateOptions;
import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.compute.reference.ComputeServiceConstants;
import org.jclouds.domain.Location; import org.jclouds.domain.Location;
import org.jclouds.logging.Logger; import org.jclouds.logging.Logger;
import org.jclouds.util.Utils;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.ComparisonChain; import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Ordering; import com.google.common.collect.Ordering;
import com.google.common.primitives.Doubles; import com.google.common.primitives.Doubles;
@ -65,12 +67,12 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Named(ComputeServiceConstants.COMPUTE_LOGGER) @Named(ComputeServiceConstants.COMPUTE_LOGGER)
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
private final Provider<Set<? extends Image>> images; protected final Provider<Set<? extends Image>> images;
private final Provider<Set<? extends Size>> sizes; protected final Provider<Set<? extends Size>> sizes;
private final Provider<Set<? extends Location>> locations; protected final Provider<Set<? extends Location>> locations;
protected final Provider<TemplateOptions> optionsProvider; protected final Provider<TemplateOptions> optionsProvider;
private final Provider<TemplateBuilder> defaultTemplateProvider; protected final Provider<TemplateBuilder> defaultTemplateProvider;
private final Location defaultLocation; protected final Location defaultLocation;
@VisibleForTesting @VisibleForTesting
protected OsFamily os; protected OsFamily os;
@ -102,10 +104,8 @@ public class TemplateBuilderImpl implements TemplateBuilder {
protected TemplateOptions options; protected TemplateOptions options;
@Inject @Inject
protected TemplateBuilderImpl(Provider<Set<? extends Location>> locations, protected TemplateBuilderImpl(Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images,
Provider<Set<? extends Image>> images, Provider<Set<? extends Size>> sizes, Location defaultLocation, Provider<TemplateOptions> optionsProvider,
Provider<Set<? extends Size>> sizes, Location defaultLocation,
Provider<TemplateOptions> optionsProvider,
@Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) { @Named("DEFAULT") Provider<TemplateBuilder> defaultTemplateProvider) {
this.locations = locations; this.locations = locations;
this.images = images; this.images = images;
@ -172,15 +172,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
returnVal = false; returnVal = false;
else else
returnVal = input.getOsDescription().contains(osDescription) returnVal = input.getOsDescription().contains(osDescription)
|| input.getOsDescription().matches(osDescription); /* || input.getOsDescription().matches(osDescription);
* note:
* matches
* ()
* expects
* a
* regex
* !
*/
} }
return returnVal; return returnVal;
} }
@ -193,13 +185,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
if (input.getVersion() == null) if (input.getVersion() == null)
returnVal = false; returnVal = false;
else else
returnVal = input.getVersion().contains(imageVersion) returnVal = input.getVersion().contains(imageVersion) || input.getVersion().matches(imageVersion);
|| input.getVersion().matches(imageVersion); /*
* note:
* matches()
* expects a
* regex!
*/
} }
return returnVal; return returnVal;
} }
@ -212,11 +198,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
if (input.getName() == null) if (input.getName() == null)
returnVal = false; returnVal = false;
else else
returnVal = input.getName().contains(imageName) returnVal = input.getName().contains(imageName) || input.getName().matches(imageName);
|| input.getName().matches(imageName); /*
* note: matches()
* expects a regex!
*/
} }
return returnVal; return returnVal;
} }
@ -231,15 +213,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
else else
returnVal = input.getDescription().equals(imageDescription) returnVal = input.getDescription().equals(imageDescription)
|| input.getDescription().contains(imageDescription) || input.getDescription().contains(imageDescription)
|| input.getDescription().matches(imageDescription); /* || input.getDescription().matches(imageDescription);
* note:
* matches
* ()
* expects
* a
* regex
* !
*/
} }
return returnVal; return returnVal;
} }
@ -272,15 +246,13 @@ public class TemplateBuilderImpl implements TemplateBuilder {
return input.getRam() >= TemplateBuilderImpl.this.minRam; return input.getRam() >= TemplateBuilderImpl.this.minRam;
} }
}; };
private final Predicate<Size> sizePredicate = Predicates.and( private final Predicate<Size> sizePredicate = and(sizeIdPredicate, locationPredicate, sizeCoresPredicate,
sizeIdPredicate, locationPredicate, sizeCoresPredicate,
sizeRamPredicate); sizeRamPredicate);
static final Ordering<Size> DEFAULT_SIZE_ORDERING = new Ordering<Size>() { static final Ordering<Size> DEFAULT_SIZE_ORDERING = new Ordering<Size>() {
public int compare(Size left, Size right) { public int compare(Size left, Size right) {
return ComparisonChain.start().compare(left.getCores(), return ComparisonChain.start().compare(left.getCores(), right.getCores()).compare(left.getRam(),
right.getCores()).compare(left.getRam(), right.getRam()) right.getRam()).compare(left.getDisk(), right.getDisk()).result();
.compare(left.getDisk(), right.getDisk()).result();
} }
}; };
static final Ordering<Size> BY_CORES_ORDERING = new Ordering<Size>() { static final Ordering<Size> BY_CORES_ORDERING = new Ordering<Size>() {
@ -290,13 +262,11 @@ public class TemplateBuilderImpl implements TemplateBuilder {
}; };
static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() { static final Ordering<Image> DEFAULT_IMAGE_ORDERING = new Ordering<Image>() {
public int compare(Image left, Image right) { public int compare(Image left, Image right) {
return ComparisonChain.start().compare(left.getName(), return ComparisonChain.start().compare(left.getName(), right.getName(),
right.getName(), Ordering.<String> natural().nullsLast()) Ordering.<String> natural().nullsLast()).compare(left.getVersion(), right.getVersion(),
.compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsLast()).compare(left.getOsDescription(), right.getOsDescription(),
Ordering.<String> natural().nullsLast()).compare( Ordering.<String> natural().nullsLast()).compare(left.getArchitecture(), right.getArchitecture())
left.getOsDescription(), right.getOsDescription(), .result();
Ordering.<String> natural().nullsLast()).compare(
left.getArchitecture(), right.getArchitecture()).result();
} }
}; };
@ -415,17 +385,8 @@ public class TemplateBuilderImpl implements TemplateBuilder {
options = optionsProvider.get(); options = optionsProvider.get();
logger.debug(">> searching params(%s)", this); logger.debug(">> searching params(%s)", this);
Location location = resolveLocation(); Location location = resolveLocation();
List<? extends Image> images = resolveImages(); Size size = resolveSize(sizeSorter(), getImages());
final Size size = resolveSize(sizeSorter(), images); Image image = resolveImage(size);
Image image = Iterables.find(images, new Predicate<Image>() {
@Override
public boolean apply(Image input) {
return size.supportsImage(input);
}
});
logger.debug("<< matched image(%s)", image); logger.debug("<< matched image(%s)", image);
// ensure we have an architecture matching // ensure we have an architecture matching
@ -434,8 +395,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
} }
protected Location resolveLocation() { protected Location resolveLocation() {
Location location = Iterables.find(locations.get(), Location location = find(locations.get(), new Predicate<Location>() {
new Predicate<Location>() {
@Override @Override
public boolean apply(Location input) { public boolean apply(Location input) {
@ -447,39 +407,29 @@ public class TemplateBuilderImpl implements TemplateBuilder {
return location; return location;
} }
protected Size resolveSize(Ordering<Size> sizeOrdering, protected Size resolveSize(Ordering<Size> sizeOrdering, final Iterable<? extends Image> images) {
final List<? extends Image> images) {
Size size; Size size;
try { try {
Iterable<? extends Size> sizesThatAreCompatibleWithOurImages = Iterables Iterable<? extends Size> sizesThatAreCompatibleWithOurImages = filter(sizes.get(), new Predicate<Size>() {
.filter(sizes.get(), new Predicate<Size>() {
@Override @Override
public boolean apply(final Size size) { public boolean apply(final Size size) {
boolean returnVal = false; boolean returnVal = false;
if (size != null) if (size != null) {
returnVal = Iterables.any(images, returnVal = Iterables.any(images, new Predicate<Image>() {
new Predicate<Image>() {
@Override @Override
public boolean apply(Image input) { public boolean apply(Image input) {
boolean returnVal = size return size.supportsImage(input);
.supportsImage(input);
if (!returnVal && input.getId().equals("us-east-1/ami-7ea24a17")) {
System.err.println("goo");
}
return returnVal;
} }
}); });
}
return returnVal; return returnVal;
} }
}); });
size = sizeOrdering.max(Iterables.filter( size = sizeOrdering.max(filter(sizesThatAreCompatibleWithOurImages, sizePredicate));
sizesThatAreCompatibleWithOurImages, sizePredicate));
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
throw new NoSuchElementException("size didn't match: " + toString() throw new NoSuchElementException("size didn't match: " + toString() + "\n" + sizes.get());
+ "\n" + sizes.get());
} }
logger.debug("<< matched size(%s)", size); logger.debug("<< matched size(%s)", size);
return size; return size;
@ -490,36 +440,44 @@ public class TemplateBuilderImpl implements TemplateBuilder {
if (!biggest) if (!biggest)
sizeOrdering = sizeOrdering.reverse(); sizeOrdering = sizeOrdering.reverse();
if (fastest) if (fastest)
sizeOrdering = Ordering.compound(ImmutableList.of(BY_CORES_ORDERING, sizeOrdering = Ordering.compound(ImmutableList.of(BY_CORES_ORDERING, sizeOrdering));
sizeOrdering));
return sizeOrdering; return sizeOrdering;
} }
/** /**
* *
* @param size
* @throws NoSuchElementException * @throws NoSuchElementException
* if there's no image that matches the predicate * if there's no image that matches the predicate
*/ */
protected List<? extends Image> resolveImages() { protected Image resolveImage(final Size size) {
Predicate<Image> imagePredicate = buildImagePredicate(); Predicate<Image> imagePredicate = and(buildImagePredicate(), new Predicate<Image>() {
@Override
public boolean apply(Image arg0) {
return size.supportsImage(arg0);
}
});
try { try {
Iterable<? extends Image> matchingImages = Iterables.filter(images Iterable<? extends Image> matchingImages = filter(getImages(), imagePredicate);
.get(), imagePredicate);
if (logger.isTraceEnabled()) if (logger.isTraceEnabled())
logger.trace("<< matched images(%s)", matchingImages); logger.trace("<< matched images(%s)", matchingImages);
List<? extends Image> maxImages = Utils.multiMax( List<? extends Image> maxImages = multiMax(DEFAULT_IMAGE_ORDERING, matchingImages);
DEFAULT_IMAGE_ORDERING, matchingImages);
if (logger.isTraceEnabled()) if (logger.isTraceEnabled())
logger.trace("<< best images(%s)", maxImages); logger.trace("<< best images(%s)", maxImages);
return maxImages; return maxImages.get(maxImages.size() - 1);
} catch (NoSuchElementException exception) { } catch (NoSuchElementException exception) {
throw new NoSuchElementException("image didn't match: " + toString() throw new NoSuchElementException("image didn't match: " + toString() + "\n" + getImages());
+ "\n" + images.get());
} }
} }
protected Set<? extends Image> getImages() {
return images.get();
}
private Predicate<Image> buildImagePredicate() { private Predicate<Image> buildImagePredicate() {
List<Predicate<Image>> predicates = Lists.newArrayList(); List<Predicate<Image>> predicates = newArrayList();
if (imageId != null) { if (imageId != null) {
predicates.add(idPredicate); predicates.add(idPredicate);
} else { } else {
@ -539,7 +497,7 @@ public class TemplateBuilderImpl implements TemplateBuilder {
predicates.add(imageDescriptionPredicate); predicates.add(imageDescriptionPredicate);
} }
Predicate<Image> imagePredicate = Predicates.and(predicates); Predicate<Image> imagePredicate = and(predicates);
return imagePredicate; return imagePredicate;
} }
@ -650,11 +608,9 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@VisibleForTesting @VisibleForTesting
boolean nothingChangedExceptOptions() { boolean nothingChangedExceptOptions() {
return os == null && arch == null && locationId == null return os == null && arch == null && locationId == null && imageId == null && sizeId == null
&& imageId == null && sizeId == null && osDescription == null && osDescription == null && imageVersion == null && imageName == null && imageDescription == null
&& imageVersion == null && imageName == null && minCores == 0 && minRam == 0 && !biggest && !fastest;
&& imageDescription == null && minCores == 0 && minRam == 0
&& !biggest && !fastest;
} }
/** /**
@ -667,11 +623,9 @@ public class TemplateBuilderImpl implements TemplateBuilder {
@Override @Override
public String toString() { public String toString() {
return "[arch=" + arch + ", biggest=" + biggest + ", fastest=" + fastest return "[arch=" + arch + ", biggest=" + biggest + ", fastest=" + fastest + ", imageName=" + imageName
+ ", imageName=" + imageName + ", imageDescription=" + ", imageDescription=" + imageDescription + ", imageId=" + imageId + ", imageVersion=" + imageVersion
+ imageDescription + ", imageId=" + imageId + ", imageVersion=" + ", location=" + locationId + ", minCores=" + minCores + ", minRam=" + minRam + ", os=" + os
+ imageVersion + ", location=" + locationId + ", minCores="
+ minCores + ", minRam=" + minRam + ", os=" + os
+ ", osDescription=" + osDescription + ", sizeId=" + sizeId + "]"; + ", osDescription=" + osDescription + ", sizeId=" + sizeId + "]";
} }

View File

@ -58,17 +58,14 @@ public class TemplateBuilderImplTest {
Image image = createMock(Image.class); Image image = createMock(Image.class);
Image image2 = createMock(Image.class); Image image2 = createMock(Image.class);
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(),
ImmutableMap.<String, String> of(), 1.0, 0, 0, ImagePredicates 1.0, 0, 0, ImagePredicates.any());
.any());
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet
.<Set<? extends Image>> of(ImmutableSet.<Image> of(image, image2)); .<Image> of(image, image2));
Provider<Set<? extends Size>> sizes = Providers Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -79,10 +76,8 @@ public class TemplateBuilderImplTest {
expect(image2.getVersion()).andReturn("version"); expect(image2.getVersion()).andReturn("version");
expect(image.getOsDescription()).andReturn("osDescription"); expect(image.getOsDescription()).andReturn("osDescription");
expect(image2.getOsDescription()).andReturn("osDescription"); expect(image2.getOsDescription()).andReturn("osDescription");
expect(image.getArchitecture()).andReturn(Architecture.X86_64) expect(image.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce();
.atLeastOnce(); expect(image2.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce();
expect(image2.getArchitecture()).andReturn(Architecture.X86_64)
.atLeastOnce();
replay(image); replay(image);
replay(image2); replay(image2);
@ -91,10 +86,10 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
assertEquals(template.resolveImages(), images.get()); assertEquals(template.resolveImage(size), image2);
verify(image); verify(image);
verify(image2); verify(image2);
@ -111,17 +106,14 @@ public class TemplateBuilderImplTest {
Image image = createMock(Image.class); Image image = createMock(Image.class);
Image image2 = createMock(Image.class); Image image2 = createMock(Image.class);
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(),
ImmutableMap.<String, String> of(), 1.0, 0, 0, ImagePredicates 1.0, 0, 0, ImagePredicates.any());
.any());
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet
.<Set<? extends Image>> of(ImmutableSet.<Image> of(image, image2)); .<Image> of(image, image2));
Provider<Set<? extends Size>> sizes = Providers Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -130,12 +122,10 @@ public class TemplateBuilderImplTest {
expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(optionsProvider.get()).andReturn(new TemplateOptions());
expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce(); expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce();
expect(image.getArchitecture()).andReturn(Architecture.X86_32) expect(image.getArchitecture()).andReturn(Architecture.X86_32).atLeastOnce();
.atLeastOnce();
expect(image2.getLocation()).andReturn(defaultLocation).atLeastOnce(); expect(image2.getLocation()).andReturn(defaultLocation).atLeastOnce();
expect(image2.getArchitecture()).andReturn(Architecture.X86_64) expect(image2.getArchitecture()).andReturn(Architecture.X86_64).atLeastOnce();
.atLeastOnce();
replay(image); replay(image);
replay(image2); replay(image2);
@ -144,11 +134,10 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
assertEquals(template.smallest().architecture(Architecture.X86_32) assertEquals(template.smallest().architecture(Architecture.X86_32).build().getImage(), image);
.build().getImage(), image);
verify(image); verify(image);
verify(image2); verify(image2);
@ -163,17 +152,13 @@ public class TemplateBuilderImplTest {
public void testSizeWithImageIdPredicateOnlyAcceptsImage() { public void testSizeWithImageIdPredicateOnlyAcceptsImage() {
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0,
ImmutableMap.<String, String> of(), 0, 0, 0, ImagePredicates 0, 0, ImagePredicates.idEquals("imageId"));
.idEquals("imageId"));
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of(image));
.<Set<? extends Image>> of(ImmutableSet.<Image> of(image)); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -195,8 +180,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
template.imageId("imageId").build(); template.imageId("imageId").build();
@ -212,17 +197,13 @@ public class TemplateBuilderImplTest {
public void testSizeWithImageIdPredicateOnlyDoesntImage() { public void testSizeWithImageIdPredicateOnlyDoesntImage() {
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Image image = createMock(Image.class); Image image = createMock(Image.class);
Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, Size size = new SizeImpl("sizeId", null, "sizeId", defaultLocation, null, ImmutableMap.<String, String> of(), 0,
ImmutableMap.<String, String> of(), 0, 0, 0, ImagePredicates 0, 0, ImagePredicates.idEquals("imageId"));
.idEquals("imageId"));
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers.<Set<? extends Location>> of(ImmutableSet
.<Set<? extends Location>> of(ImmutableSet
.<Location> of(defaultLocation)); .<Location> of(defaultLocation));
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of(image));
.<Set<? extends Image>> of(ImmutableSet.<Image> of(image)); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of(size));
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class); TemplateBuilder defaultTemplate = createMock(TemplateBuilder.class);
@ -230,13 +211,6 @@ public class TemplateBuilderImplTest {
expect(defaultLocation.getId()).andReturn("locationId").atLeastOnce(); expect(defaultLocation.getId()).andReturn("locationId").atLeastOnce();
expect(optionsProvider.get()).andReturn(new TemplateOptions()); expect(optionsProvider.get()).andReturn(new TemplateOptions());
expect(image.getId()).andReturn("notImageId").atLeastOnce(); expect(image.getId()).andReturn("notImageId").atLeastOnce();
expect(image.getLocation()).andReturn(defaultLocation).atLeastOnce();
expect(image.getOsFamily()).andReturn(null);
expect(image.getName()).andReturn(null);
expect(image.getDescription()).andReturn(null);
expect(image.getOsDescription()).andReturn(null);
expect(image.getVersion()).andReturn(null);
expect(image.getArchitecture()).andReturn(null).atLeastOnce();
replay(image); replay(image);
replay(defaultTemplate); replay(defaultTemplate);
@ -244,8 +218,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("notImageId").build(); template.imageId("notImageId").build();
assert false; assert false;
@ -266,10 +240,8 @@ public class TemplateBuilderImplTest {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -285,8 +257,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
template.options(options).build(); template.options(options).build();
@ -302,10 +274,8 @@ public class TemplateBuilderImplTest {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
@ -320,8 +290,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
template.build(); template.build();
@ -331,14 +301,11 @@ public class TemplateBuilderImplTest {
verify(templateBuilderProvider); verify(templateBuilderProvider);
} }
protected TemplateBuilderImpl createTemplateBuilder( protected TemplateBuilderImpl createTemplateBuilder(Provider<Set<? extends Location>> locations,
Provider<Set<? extends Location>> locations, Provider<Set<? extends Image>> images, Provider<Set<? extends Size>> sizes, Location defaultLocation,
Provider<Set<? extends Image>> images, Provider<TemplateOptions> optionsProvider, Provider<TemplateBuilder> templateBuilderProvider) {
Provider<Set<? extends Size>> sizes, Location defaultLocation, TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images, sizes, defaultLocation,
Provider<TemplateOptions> optionsProvider, optionsProvider, templateBuilderProvider);
Provider<TemplateBuilder> templateBuilderProvider) {
TemplateBuilderImpl template = new TemplateBuilderImpl(locations, images,
sizes, defaultLocation, optionsProvider, templateBuilderProvider);
return template; return template;
} }
@ -347,10 +314,8 @@ public class TemplateBuilderImplTest {
public void testSuppliedLocationWithNoOptions() { public void testSuppliedLocationWithNoOptions() {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -363,8 +328,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("foo").locationId("location").build(); template.imageId("foo").locationId("location").build();
@ -386,10 +351,8 @@ public class TemplateBuilderImplTest {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -400,12 +363,11 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("foo").options(provideTemplateOptions()).locationId( template.imageId("foo").options(provideTemplateOptions()).locationId("location").build();
"location").build();
assert false; assert false;
} catch (NoSuchElementException e) { } catch (NoSuchElementException e) {
@ -421,10 +383,8 @@ public class TemplateBuilderImplTest {
public void testDefaultLocationWithNoOptionsNoSuchElement() { public void testDefaultLocationWithNoOptionsNoSuchElement() {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -438,8 +398,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("foo").build(); template.imageId("foo").build();
@ -463,10 +423,8 @@ public class TemplateBuilderImplTest {
public void testDefaultLocationWithOptions() { public void testDefaultLocationWithOptions() {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
TemplateOptions from = provideTemplateOptions(); TemplateOptions from = provideTemplateOptions();
@ -489,8 +447,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
try { try {
template.imageId("foo").options(provideTemplateOptions()).build(); template.imageId("foo").options(provideTemplateOptions()).build();
@ -509,10 +467,8 @@ public class TemplateBuilderImplTest {
public void testImageIdNullsEverythingElse() { public void testImageIdNullsEverythingElse() {
Provider<Set<? extends Location>> locations = Providers Provider<Set<? extends Location>> locations = Providers
.<Set<? extends Location>> of(ImmutableSet.<Location> of()); .<Set<? extends Location>> of(ImmutableSet.<Location> of());
Provider<Set<? extends Image>> images = Providers Provider<Set<? extends Image>> images = Providers.<Set<? extends Image>> of(ImmutableSet.<Image> of());
.<Set<? extends Image>> of(ImmutableSet.<Image> of()); Provider<Set<? extends Size>> sizes = Providers.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Provider<Set<? extends Size>> sizes = Providers
.<Set<? extends Size>> of(ImmutableSet.<Size> of());
Location defaultLocation = createMock(Location.class); Location defaultLocation = createMock(Location.class);
Provider<TemplateOptions> optionsProvider = createMock(Provider.class); Provider<TemplateOptions> optionsProvider = createMock(Provider.class);
Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class); Provider<TemplateBuilder> templateBuilderProvider = createMock(Provider.class);
@ -521,8 +477,8 @@ public class TemplateBuilderImplTest {
replay(optionsProvider); replay(optionsProvider);
replay(templateBuilderProvider); replay(templateBuilderProvider);
TemplateBuilderImpl template = createTemplateBuilder(locations, images, TemplateBuilderImpl template = createTemplateBuilder(locations, images, sizes, defaultLocation, optionsProvider,
sizes, defaultLocation, optionsProvider, templateBuilderProvider); templateBuilderProvider);
template.architecture(Architecture.X86_32); template.architecture(Architecture.X86_32);
template.imageDescriptionMatches("imageDescriptionMatches"); template.imageDescriptionMatches("imageDescriptionMatches");

View File

@ -89,8 +89,7 @@ public class HttpUtils {
@Inject(optional = true) @Inject(optional = true)
@Named(Constants.PROPERTY_PROXY_SYSTEM) @Named(Constants.PROPERTY_PROXY_SYSTEM)
private boolean systemProxies = System.getProperty("java.net.useSystemProxies") != null ? Boolean private boolean systemProxies = System.getProperty("java.net.useSystemProxies") != null ? Boolean
.parseBoolean(System.getProperty("java.net.useSystemProxies")) .parseBoolean(System.getProperty("java.net.useSystemProxies")) : false;
: false;
private final int globalMaxConnections; private final int globalMaxConnections;
private final int globalMaxConnectionsPerHost; private final int globalMaxConnectionsPerHost;
@ -176,20 +175,20 @@ public class HttpUtils {
} }
/** /**
* keys to the map are only used for socket information, not path. In this case, you should * keys to the map are only used for socket information, not path. In this
* remove any path or query details from the URI. * case, you should remove any path or query details from the URI.
*/ */
public static URI createBaseEndpointFor(URI endpoint) { public static URI createBaseEndpointFor(URI endpoint) {
if (endpoint.getPort() == -1) { if (endpoint.getPort() == -1) {
return URI.create(String.format("%s://%s", endpoint.getScheme(), endpoint.getHost())); return URI.create(String.format("%s://%s", endpoint.getScheme(), endpoint.getHost()));
} else { } else {
return URI.create(String.format("%s://%s:%d", endpoint.getScheme(), endpoint.getHost(), return URI.create(String.format("%s://%s:%d", endpoint.getScheme(), endpoint.getHost(), endpoint.getPort()));
endpoint.getPort()));
} }
} }
/** /**
* Web browsers do not always handle '+' characters well, use the well-supported '%20' instead. * Web browsers do not always handle '+' characters well, use the
* well-supported '%20' instead.
*/ */
public static String urlEncode(String in, char... skipEncode) { public static String urlEncode(String in, char... skipEncode) {
if (isUrlEncoded(in)) if (isUrlEncoded(in))
@ -235,7 +234,8 @@ public class HttpUtils {
} }
/** /**
* Content stream may need to be read. However, we should always close the http stream. * Content stream may need to be read. However, we should always close the
* http stream.
* *
* @throws IOException * @throws IOException
*/ */
@ -256,11 +256,10 @@ public class HttpUtils {
checkState(redirectURI.getScheme().startsWith("http"), String.format( checkState(redirectURI.getScheme().startsWith("http"), String.format(
"header %s didn't parse an http scheme: [%s]", hostHeader, scheme)); "header %s didn't parse an http scheme: [%s]", hostHeader, scheme));
int port = redirectURI.getPort() > 0 ? redirectURI.getPort() : redirectURI.getScheme() int port = redirectURI.getPort() > 0 ? redirectURI.getPort() : redirectURI.getScheme().equals("https") ? 443 : 80;
.equals("https") ? 443 : 80;
String host = redirectURI.getHost(); String host = redirectURI.getHost();
checkState(host.indexOf('/') == -1, String.format( checkState(host.indexOf('/') == -1, String.format("header %s didn't parse an http host correctly: [%s]",
"header %s didn't parse an http host correctly: [%s]", hostHeader, host)); hostHeader, host));
URI endPoint = URI.create(String.format("%s://%s:%d", scheme, host, port)); URI endPoint = URI.create(String.format("%s://%s:%d", scheme, host, port));
return endPoint; return endPoint;
} }
@ -270,10 +269,11 @@ public class HttpUtils {
} }
/** /**
* Used to extract the URI and authentication data from a String. Note that the java URI class * Used to extract the URI and authentication data from a String. Note that
* breaks, if there are special characters like '/' present. Otherwise, we wouldn't need this * the java URI class breaks, if there are special characters like '/'
* class, and we could simply use URI.create("uri").getUserData(); Also, URI breaks if there are * present. Otherwise, we wouldn't need this class, and we could simply use
* curly braces. * URI.create("uri").getUserData(); Also, URI breaks if there are curly
* braces.
* *
*/ */
public static URI createUri(String uriPath) { public static URI createUri(String uriPath) {
@ -305,8 +305,7 @@ public class HttpUtils {
String rest = matcher.group(4); String rest = matcher.group(4);
String identity = matcher.group(2); String identity = matcher.group(2);
String key = matcher.group(3); String key = matcher.group(3);
return URI.create(String.format("%s://%s:%s@%s", scheme, urlEncode(identity), return URI.create(String.format("%s://%s:%s@%s", scheme, urlEncode(identity), urlEncode(key), rest));
urlEncode(key), rest));
} else { } else {
throw new IllegalArgumentException("bad syntax"); throw new IllegalArgumentException("bad syntax");
} }
@ -329,14 +328,12 @@ public class HttpUtils {
} }
if (message.getPayload() != null) { if (message.getPayload() != null) {
if (message.getPayload().getContentType() != null) if (message.getPayload().getContentType() != null)
logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_TYPE, message.getPayload() logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_TYPE, message.getPayload().getContentType());
.getContentType());
if (message.getPayload().getContentLength() != null) if (message.getPayload().getContentLength() != null)
logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_LENGTH, message.getPayload() logger.debug("%s %s: %s", prefix, HttpHeaders.CONTENT_LENGTH, message.getPayload().getContentLength());
.getContentLength());
if (message.getPayload().getContentMD5() != null) if (message.getPayload().getContentMD5() != null)
logger.debug("%s %s: %s", prefix, "Content-MD5", encryptionService.base64(message logger.debug("%s %s: %s", prefix, "Content-MD5", encryptionService.base64(message.getPayload()
.getPayload().getContentMD5())); .getContentMD5()));
} }
} }
@ -359,12 +356,13 @@ public class HttpUtils {
} }
/** /**
* change the destination of the current http command. typically used in handling redirects. * change the destination of the current http command. typically used in
* handling redirects.
* *
* @param string * @param string
*/ */
public static void changeSchemeHostAndPortTo(HttpRequest request, String scheme, String host, public static void changeSchemeHostAndPortTo(HttpRequest request, String scheme, String host, int port,
int port, UriBuilder builder) { UriBuilder builder) {
builder.uri(request.getEndpoint()); builder.uri(request.getEndpoint());
builder.scheme(scheme); builder.scheme(scheme);
builder.host(host); builder.host(host);
@ -389,18 +387,16 @@ public class HttpUtils {
request.setMethod(HttpMethod.GET); request.setMethod(HttpMethod.GET);
} }
public static void addQueryParamTo(HttpRequest request, String key, Object value, public static void addQueryParamTo(HttpRequest request, String key, Object value, UriBuilder builder) {
UriBuilder builder) {
addQueryParamTo(request, key, ImmutableSet.<Object> of(value), builder, request.getSkips()); addQueryParamTo(request, key, ImmutableSet.<Object> of(value), builder, request.getSkips());
} }
public static void addQueryParamTo(HttpRequest request, String key, Iterable<?> values, public static void addQueryParamTo(HttpRequest request, String key, Iterable<?> values, UriBuilder builder) {
UriBuilder builder) {
addQueryParamTo(request, key, values, builder, request.getSkips()); addQueryParamTo(request, key, values, builder, request.getSkips());
} }
public static void addQueryParamTo(HttpRequest request, String key, Iterable<?> values, public static void addQueryParamTo(HttpRequest request, String key, Iterable<?> values, UriBuilder builder,
UriBuilder builder, char... skips) { char... skips) {
builder.uri(request.getEndpoint()); builder.uri(request.getEndpoint());
Multimap<String, String> map = parseQueryToMap(request.getEndpoint().getQuery()); Multimap<String, String> map = parseQueryToMap(request.getEndpoint().getQuery());
for (Object o : values) for (Object o : values)
@ -409,13 +405,11 @@ public class HttpUtils {
request.setEndpoint(builder.build()); request.setEndpoint(builder.build());
} }
public static void replaceMatrixParam(HttpRequest request, String name, Object value, public static void replaceMatrixParam(HttpRequest request, String name, Object value, UriBuilder builder) {
UriBuilder builder) {
replaceMatrixParam(request, name, new Object[] { value }, builder); replaceMatrixParam(request, name, new Object[] { value }, builder);
} }
public static void replaceMatrixParam(HttpRequest request, String name, Object[] values, public static void replaceMatrixParam(HttpRequest request, String name, Object[] values, UriBuilder builder) {
UriBuilder builder) {
builder.uri(request.getEndpoint()); builder.uri(request.getEndpoint());
builder.replaceMatrixParam(name, values); builder.replaceMatrixParam(name, values);
request.setEndpoint(builder.build()); request.setEndpoint(builder.build());
@ -451,19 +445,16 @@ public class HttpUtils {
return map; return map;
} }
public static void parseKeyValueFromStringToMap(String stringToParse, public static void parseKeyValueFromStringToMap(String stringToParse, Multimap<String, String> map) {
Multimap<String, String> map) {
// note that '=' can be a valid part of the value // note that '=' can be a valid part of the value
int indexOfFirstEquals = stringToParse.indexOf('='); int indexOfFirstEquals = stringToParse.indexOf('=');
String key = indexOfFirstEquals == -1 ? stringToParse : stringToParse.substring(0, String key = indexOfFirstEquals == -1 ? stringToParse : stringToParse.substring(0, indexOfFirstEquals);
indexOfFirstEquals); String value = indexOfFirstEquals == -1 ? null : stringToParse.substring(indexOfFirstEquals + 1);
String value = indexOfFirstEquals == -1 ? null : stringToParse
.substring(indexOfFirstEquals + 1);
map.put(key, value); map.put(key, value);
} }
public static SortedSet<Entry<String, String>> sortEntries( public static SortedSet<Entry<String, String>> sortEntries(Collection<Map.Entry<String, String>> in,
Collection<Map.Entry<String, String>> in, Comparator<Map.Entry<String, String>> sorter) { Comparator<Map.Entry<String, String>> sorter) {
SortedSet<Entry<String, String>> entries = newTreeSet(sorter); SortedSet<Entry<String, String>> entries = newTreeSet(sorter);
entries.addAll(in); entries.addAll(in);
return entries; return entries;
@ -471,8 +462,8 @@ public class HttpUtils {
public static String makeQueryLine(Multimap<String, String> params, public static String makeQueryLine(Multimap<String, String> params,
@Nullable Comparator<Map.Entry<String, String>> sorter, char... skips) { @Nullable Comparator<Map.Entry<String, String>> sorter, char... skips) {
Iterator<Map.Entry<String, String>> pairs = ((sorter == null) ? params.entries() Iterator<Map.Entry<String, String>> pairs = ((sorter == null) ? params.entries() : sortEntries(params.entries(),
: sortEntries(params.entries(), sorter)).iterator(); sorter)).iterator();
StringBuilder formBuilder = new StringBuilder(); StringBuilder formBuilder = new StringBuilder();
while (pairs.hasNext()) { while (pairs.hasNext()) {
Map.Entry<String, String> pair = pairs.next(); Map.Entry<String, String> pair = pairs.next();
@ -492,8 +483,7 @@ public class HttpUtils {
boolean chunked = any(headers.entries(), new Predicate<Entry<String, String>>() { boolean chunked = any(headers.entries(), new Predicate<Entry<String, String>>() {
@Override @Override
public boolean apply(Entry<String, String> input) { public boolean apply(Entry<String, String> input) {
return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) return "Transfer-Encoding".equalsIgnoreCase(input.getKey()) && "chunked".equalsIgnoreCase(input.getValue());
&& "chunked".equalsIgnoreCase(input.getValue());
} }
}); });
@ -514,23 +504,18 @@ public class HttpUtils {
if (message instanceof HttpRequest) { if (message instanceof HttpRequest) {
checkArgument( checkArgument(
message.getPayload() == null message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_TYPE) == null,
|| message.getFirstHeaderOrNull(CONTENT_TYPE) == null,
"configuration error please use request.getPayload().setContentType(value) as opposed to adding a content type header: " "configuration error please use request.getPayload().setContentType(value) as opposed to adding a content type header: "
+ message); + message);
checkArgument( checkArgument(
message.getPayload() == null message.getPayload() == null || message.getFirstHeaderOrNull(CONTENT_LENGTH) == null,
|| message.getFirstHeaderOrNull(CONTENT_LENGTH) == null,
"configuration error please use request.getPayload().setContentLength(value) as opposed to adding a content length header: " "configuration error please use request.getPayload().setContentLength(value) as opposed to adding a content length header: "
+ message); + message);
checkArgument(message.getPayload() == null checkArgument(message.getPayload() == null || message.getPayload().getContentLength() != null
|| message.getPayload().getContentLength() != null
|| "chunked".equalsIgnoreCase(message.getFirstHeaderOrNull("Transfer-Encoding")), || "chunked".equalsIgnoreCase(message.getFirstHeaderOrNull("Transfer-Encoding")),
"either chunked encoding must be set on the http request or contentlength set on the payload: " "either chunked encoding must be set on the http request or contentlength set on the payload: "
+ message); + message);
checkArgument( checkArgument(message.getPayload() == null || message.getFirstHeaderOrNull("Content-MD5") == null,
message.getPayload() == null
|| message.getFirstHeaderOrNull("Content-MD5") == null,
"configuration error please use request.getPayload().setContentMD5(value) as opposed to adding a content md5 header: " "configuration error please use request.getPayload().setContentMD5(value) as opposed to adding a content md5 header: "
+ message); + message);
} }
@ -555,7 +540,7 @@ public class HttpUtils {
public static Long attemptToParseSizeAndRangeFromHeaders(HttpResponse from) throws HttpException { public static Long attemptToParseSizeAndRangeFromHeaders(HttpResponse from) throws HttpException {
String contentRange = from.getFirstHeaderOrNull("Content-Range"); String contentRange = from.getFirstHeaderOrNull("Content-Range");
if (contentRange == null) { if (contentRange == null && from.getPayload() != null) {
return from.getPayload().getContentLength(); return from.getPayload().getContentLength();
} else if (contentRange != null) { } else if (contentRange != null) {
return Long.parseLong(contentRange.substring(contentRange.lastIndexOf('/') + 1)); return Long.parseLong(contentRange.substring(contentRange.lastIndexOf('/') + 1));

View File

@ -21,6 +21,8 @@ package org.jclouds.http.functions;
import static org.jclouds.http.HttpUtils.releasePayload; import static org.jclouds.http.HttpUtils.releasePayload;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.annotation.Resource; import javax.annotation.Resource;
import javax.inject.Inject; import javax.inject.Inject;
@ -32,23 +34,26 @@ import org.jclouds.logging.Logger;
import com.google.common.base.Function; import com.google.common.base.Function;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.inject.TypeLiteral;
/** /**
* This object will parse the body of an HttpResponse and return the result of type <T> back to the * This object will parse the body of an HttpResponse and return the result of
* caller. * type <T> back to the caller.
* *
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public abstract class ParseJson<T> implements Function<HttpResponse, T> { public class ParseJson<T> implements Function<HttpResponse, T> {
@Resource @Resource
protected Logger logger = Logger.NULL; protected Logger logger = Logger.NULL;
protected final Gson gson; protected final Gson gson;
protected final TypeLiteral<T> type;
@Inject @Inject
public ParseJson(Gson gson){ public ParseJson(Gson gson, TypeLiteral<T> type) {
this.gson = gson; this.gson = gson;
this.type = type;
} }
/** /**
@ -62,12 +67,21 @@ public abstract class ParseJson<T> implements Function<HttpResponse, T> {
StringBuilder message = new StringBuilder(); StringBuilder message = new StringBuilder();
message.append("Error parsing input"); message.append("Error parsing input");
logger.error(e, message.toString()); logger.error(e, message.toString());
throw new HttpResponseException(message.toString() + "\n" + from, null, from, e); throw new HttpResponseException(message.toString() + "\n" + from,
null, from, e);
} finally { } finally {
releasePayload(from); releasePayload(from);
} }
} }
protected abstract T apply(InputStream stream); @SuppressWarnings("unchecked")
public T apply(InputStream stream) {
try {
return (T) gson.fromJson(new InputStreamReader(stream, "UTF-8"), type
.getType());
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
} }

View File

@ -16,42 +16,34 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
package org.jclouds.rackspace.cloudservers.functions; package org.jclouds.http.functions;
import java.io.InputStream; import java.util.Map;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.rackspace.cloudservers.domain.Image;
import com.google.gson.Gson;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import com.google.common.base.Function;
import com.google.inject.internal.Iterables;
/** /**
* This parses {@link Image} from a gson string.
*
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseImageFromJsonResponse extends ParseJson<Image> { public class UnwrapOnlyJsonValue<T> implements Function<HttpResponse, T> {
private final ParseJson<Map<String, T>> json;
@Inject @Inject
public ParseImageFromJsonResponse(Gson gson) { UnwrapOnlyJsonValue(ParseJson<Map<String, T>> json) {
super(gson); this.json = json;
} }
private static class ImageListResponse { @Override
Image image; public T apply(HttpResponse arg0) {
} Map<String, T> map = json.apply(arg0);
return Iterables.getOnlyElement(map.values());
public Image apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), ImageListResponse.class).image;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -20,6 +20,7 @@ package org.jclouds.http.functions.config;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.Date; import java.util.Date;
import java.util.List;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -29,11 +30,13 @@ import javax.xml.parsers.SAXParserFactory;
import org.jclouds.Constants; import org.jclouds.Constants;
import org.jclouds.date.DateService; import org.jclouds.date.DateService;
import org.jclouds.encryption.EncryptionService;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ParseSax.HandlerWithResult; import org.jclouds.http.functions.ParseSax.HandlerWithResult;
import org.xml.sax.XMLReader; import org.xml.sax.XMLReader;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.common.primitives.Bytes;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializationContext;
@ -43,6 +46,7 @@ import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive; import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer; import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
import com.google.inject.ImplementedBy; import com.google.inject.ImplementedBy;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -88,9 +92,13 @@ public class ParserModule extends AbstractModule {
@Provides @Provides
@Singleton @Singleton
Gson provideGson(DateAdapter adapter, GsonAdapterBindings bindings) { Gson provideGson(DateAdapter adapter, ByteListAdapter byteListAdapter,
ByteArrayAdapter byteArrayAdapter, GsonAdapterBindings bindings) {
GsonBuilder gson = new GsonBuilder(); GsonBuilder gson = new GsonBuilder();
gson.registerTypeAdapter(Date.class, adapter); gson.registerTypeAdapter(Date.class, adapter);
gson.registerTypeAdapter(new TypeToken<List<Byte>>() {
}.getType(), byteListAdapter);
gson.registerTypeAdapter(byte[].class, byteArrayAdapter);
for (Map.Entry<Type, Object> binding : bindings.getBindings().entrySet()) { for (Map.Entry<Type, Object> binding : bindings.getBindings().entrySet()) {
gson.registerTypeAdapter(binding.getKey(), binding.getValue()); gson.registerTypeAdapter(binding.getKey(), binding.getValue());
} }
@ -98,10 +106,68 @@ public class ParserModule extends AbstractModule {
} }
@ImplementedBy(CDateAdapter.class) @ImplementedBy(CDateAdapter.class)
public static interface DateAdapter extends JsonSerializer<Date>, JsonDeserializer<Date> { public static interface DateAdapter extends JsonSerializer<Date>,
JsonDeserializer<Date> {
} }
@ImplementedBy(HexByteListAdapter.class)
public static interface ByteListAdapter extends JsonSerializer<List<Byte>>,
JsonDeserializer<List<Byte>> {
}
@ImplementedBy(HexByteArrayAdapter.class)
public static interface ByteArrayAdapter extends JsonSerializer<byte[]>,
JsonDeserializer<byte[]> {
}
@Singleton
public static class HexByteListAdapter implements ByteListAdapter {
private final EncryptionService encryptionService;
@Inject
HexByteListAdapter(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
@Override
public List<Byte> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return Bytes.asList(encryptionService.fromHex(json.getAsString()));
}
@Override
public JsonElement serialize(List<Byte> src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(encryptionService.hex(Bytes.toArray(src)));
}
}
@Singleton
public static class HexByteArrayAdapter implements ByteArrayAdapter {
private final EncryptionService encryptionService;
@Inject
HexByteArrayAdapter(EncryptionService encryptionService) {
this.encryptionService = encryptionService;
}
@Override
public byte[] deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
return encryptionService.fromHex(json.getAsString());
}
@Override
public JsonElement serialize(byte[] src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(encryptionService.hex(src));
}
}
@Singleton @Singleton
public static class Iso8601DateAdapter implements DateAdapter { public static class Iso8601DateAdapter implements DateAdapter {
private final DateService dateService; private final DateService dateService;
@ -111,12 +177,13 @@ public class ParserModule extends AbstractModule {
this.dateService = dateService; this.dateService = dateService;
} }
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(dateService.iso8601DateFormat(src)); return new JsonPrimitive(dateService.iso8601DateFormat(src));
} }
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public Date deserialize(JsonElement json, Type typeOfT,
throws JsonParseException { JsonDeserializationContext context) throws JsonParseException {
String toParse = json.getAsJsonPrimitive().getAsString(); String toParse = json.getAsJsonPrimitive().getAsString();
try { try {
return dateService.iso8601DateParse(toParse); return dateService.iso8601DateParse(toParse);
@ -136,12 +203,13 @@ public class ParserModule extends AbstractModule {
this.dateService = dateService; this.dateService = dateService;
} }
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(dateService.cDateFormat(src)); return new JsonPrimitive(dateService.cDateFormat(src));
} }
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public Date deserialize(JsonElement json, Type typeOfT,
throws JsonParseException { JsonDeserializationContext context) throws JsonParseException {
String toParse = json.getAsJsonPrimitive().getAsString(); String toParse = json.getAsJsonPrimitive().getAsString();
Date toReturn = dateService.cDateParse(toParse); Date toReturn = dateService.cDateParse(toParse);
return toReturn; return toReturn;
@ -152,12 +220,13 @@ public class ParserModule extends AbstractModule {
@Singleton @Singleton
public static class LongDateAdapter implements DateAdapter { public static class LongDateAdapter implements DateAdapter {
public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { public JsonElement serialize(Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.getTime()); return new JsonPrimitive(src.getTime());
} }
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) public Date deserialize(JsonElement json, Type typeOfT,
throws JsonParseException { JsonDeserializationContext context) throws JsonParseException {
long toParse = json.getAsJsonPrimitive().getAsLong(); long toParse = json.getAsJsonPrimitive().getAsLong();
Date toReturn = new Date(toParse); Date toReturn = new Date(toParse);
return toReturn; return toReturn;
@ -170,7 +239,8 @@ public class ParserModule extends AbstractModule {
private final Map<Type, Object> bindings = Maps.newHashMap(); private final Map<Type, Object> bindings = Maps.newHashMap();
@com.google.inject.Inject(optional = true) @com.google.inject.Inject(optional = true)
public void setBindings(@Named(Constants.PROPERTY_GSON_ADAPTERS) Map<Type, Object> bindings) { public void setBindings(
@Named(Constants.PROPERTY_GSON_ADAPTERS) Map<Type, Object> bindings) {
this.bindings.putAll(bindings); this.bindings.putAll(bindings);
} }

View File

@ -0,0 +1,37 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.rest.annotations;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
/**
* Unwraps the only value in the json reponse
*
* ex. { "foo" :"bar" } becomes "bar"
*
* @author Adrian Cole
*/
@Target(METHOD)
@Retention(RUNTIME)
public @interface Unwrap {
}

View File

@ -51,7 +51,8 @@ public class JschSshClientModule extends AbstractModule {
protected void configure() { protected void configure() {
bind(SshClient.Factory.class).to(Factory.class).in(Scopes.SINGLETON); bind(SshClient.Factory.class).to(Factory.class).in(Scopes.SINGLETON);
bind(SocketOpen.class).to(InetSocketAddressConnect.class).in(Scopes.SINGLETON); bind(SocketOpen.class).to(InetSocketAddressConnect.class).in(
Scopes.SINGLETON);
} }
private static class Factory implements SshClient.Factory { private static class Factory implements SshClient.Factory {
@ -64,27 +65,30 @@ public class JschSshClientModule extends AbstractModule {
@SuppressWarnings("unused") @SuppressWarnings("unused")
@Inject @Inject
public Factory(BackoffLimitedRetryHandler backoffLimitedRetryHandler, Injector injector) { public Factory(BackoffLimitedRetryHandler backoffLimitedRetryHandler,
Injector injector) {
this.backoffLimitedRetryHandler = backoffLimitedRetryHandler; this.backoffLimitedRetryHandler = backoffLimitedRetryHandler;
this.injector = injector; this.injector = injector;
} }
public SshClient create(IPSocket socket, String username, String password) { public SshClient create(IPSocket socket, String username, String password) {
SshClient client = new JschSshClient(backoffLimitedRetryHandler, socket, timeout, SshClient client = new JschSshClient(backoffLimitedRetryHandler,
username, password, null); socket, timeout, username, password, null);
injector.injectMembers(client);// add logger injector.injectMembers(client);// add logger
return client; return client;
} }
public SshClient create(IPSocket socket, String username, byte[] privateKey) { public SshClient create(IPSocket socket, String username,
SshClient client = new JschSshClient(backoffLimitedRetryHandler, socket, timeout, byte[] privateKey) {
username, null, privateKey); SshClient client = new JschSshClient(backoffLimitedRetryHandler,
socket, timeout, username, null, privateKey);
injector.injectMembers(client);// add logger injector.injectMembers(client);// add logger
return client; return client;
} }
@Override @Override
public Map<String, String> generateRSAKeyPair(String comment, String passphrase) { public Map<String, String> generateRSAKeyPair(String comment,
String passphrase) {
KeyPair pair = null; KeyPair pair = null;
try { try {
pair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA); pair = KeyPair.genKeyPair(new JSch(), KeyPair.RSA);
@ -97,9 +101,9 @@ public class JschSshClientModule extends AbstractModule {
pair.writePrivateKey(privateKey); pair.writePrivateKey(privateKey);
ByteArrayOutputStream publicKey = new ByteArrayOutputStream(); ByteArrayOutputStream publicKey = new ByteArrayOutputStream();
pair.writePublicKey(publicKey, comment); pair.writePublicKey(publicKey, comment);
return ImmutableMap.of("comment", comment, "passphrase", passphrase, "private", return ImmutableMap.of("comment", comment, "passphrase", passphrase,
new String(privateKey.toByteArray()), "public", new String(publicKey "private", new String(privateKey.toByteArray()), "public",
.toByteArray())); new String(publicKey.toByteArray()));
} }
} }
} }

View File

@ -23,19 +23,15 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.internal.ErrorResponse; import org.jclouds.gogrid.domain.internal.ErrorResponse;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
@ -47,24 +43,20 @@ import com.google.inject.Singleton;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseErrorFromJsonResponse extends public class ParseErrorFromJsonResponse implements
ParseJson<SortedSet<ErrorResponse>> { Function<HttpResponse, SortedSet<ErrorResponse>> {
private final ParseJson<GenericResponseContainer<ErrorResponse>> json;
@Inject @Inject
ParseErrorFromJsonResponse(Gson gson) { ParseErrorFromJsonResponse(
super(gson); ParseJson<GenericResponseContainer<ErrorResponse>> json) {
this.json = json;
} }
public SortedSet<ErrorResponse> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<ErrorResponse>>() { public SortedSet<ErrorResponse> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<ErrorResponse> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,32 +18,31 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.ServerImage; import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.HttpResponse;
import com.google.common.base.Function;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseImageFromJsonResponse extends ParseJson<ServerImage> { public class ParseImageFromJsonResponse implements
Function<HttpResponse, ServerImage> {
private final ParseImageListFromJsonResponse parser;
@Inject @Inject
ParseImageFromJsonResponse(Gson gson) { ParseImageFromJsonResponse(ParseImageListFromJsonResponse parser) {
super(gson); this.parser = parser;
} }
public ServerImage apply(InputStream stream) { @Override
SortedSet<ServerImage> allImages = new ParseImageListFromJsonResponse( public ServerImage apply(HttpResponse arg0) {
gson).apply(stream); return Iterables.getOnlyElement(parser.apply(arg0));
return Iterables.getOnlyElement(allImages);
} }
} }

View File

@ -18,43 +18,35 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.ServerImage; import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseImageListFromJsonResponse extends public class ParseImageListFromJsonResponse implements
ParseJson<SortedSet<ServerImage>> { Function<HttpResponse, SortedSet<ServerImage>> {
private final ParseJson<GenericResponseContainer<ServerImage>> json;
@Inject @Inject
ParseImageListFromJsonResponse(Gson gson) { ParseImageListFromJsonResponse(
super(gson); ParseJson<GenericResponseContainer<ServerImage>> json) {
this.json = json;
} }
public SortedSet<ServerImage> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<ServerImage>>() { public SortedSet<ServerImage> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<ServerImage> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,19 +18,15 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.Ip; import org.jclouds.gogrid.domain.Ip;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
@ -39,23 +35,19 @@ import com.google.inject.Singleton;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseIpListFromJsonResponse extends ParseJson<SortedSet<Ip>> { public class ParseIpListFromJsonResponse implements
Function<HttpResponse, SortedSet<Ip>> {
private final ParseJson<GenericResponseContainer<Ip>> json;
@Inject @Inject
ParseIpListFromJsonResponse(Gson gson) { ParseIpListFromJsonResponse(ParseJson<GenericResponseContainer<Ip>> json) {
super(gson); this.json = json;
} }
public SortedSet<Ip> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<Ip>>() { public SortedSet<Ip> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<Ip> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,19 +18,15 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.Job; import org.jclouds.gogrid.domain.Job;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
@ -39,23 +35,19 @@ import com.google.inject.Singleton;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseJobListFromJsonResponse extends ParseJson<SortedSet<Job>> { public class ParseJobListFromJsonResponse implements
Function<HttpResponse, SortedSet<Job>> {
private final ParseJson<GenericResponseContainer<Job>> json;
@Inject @Inject
ParseJobListFromJsonResponse(Gson gson) { ParseJobListFromJsonResponse(ParseJson<GenericResponseContainer<Job>> json) {
super(gson); this.json = json;
} }
public SortedSet<Job> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<Job>>() { public SortedSet<Job> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<Job> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,16 +18,14 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import com.google.common.collect.Iterables; import javax.inject.Inject;
import com.google.gson.Gson;
import com.google.inject.Singleton;
import org.jclouds.gogrid.domain.LoadBalancer; import org.jclouds.gogrid.domain.LoadBalancer;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.HttpResponse;
import javax.inject.Inject; import com.google.common.base.Function;
import java.io.InputStream; import com.google.common.collect.Iterables;
import java.util.SortedSet; import com.google.inject.Singleton;
/** /**
* Parses the single load balancer out of the response. * Parses the single load balancer out of the response.
@ -38,17 +36,19 @@ import java.util.SortedSet;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseLoadBalancerFromJsonResponse extends ParseJson<LoadBalancer> { public class ParseLoadBalancerFromJsonResponse implements
Function<HttpResponse, LoadBalancer> {
private final ParseLoadBalancerListFromJsonResponse parser;
@Inject @Inject
ParseLoadBalancerFromJsonResponse(Gson gson) { ParseLoadBalancerFromJsonResponse(
super(gson); ParseLoadBalancerListFromJsonResponse parser) {
this.parser = parser;
} }
public LoadBalancer apply(InputStream stream) { @Override
SortedSet<LoadBalancer> allLoadBalancers = new ParseLoadBalancerListFromJsonResponse( public LoadBalancer apply(HttpResponse arg0) {
gson).apply(stream); return Iterables.getOnlyElement(parser.apply(arg0));
return Iterables.getOnlyElement(allLoadBalancers);
} }
} }

View File

@ -18,19 +18,15 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.LoadBalancer; import org.jclouds.gogrid.domain.LoadBalancer;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
@ -40,24 +36,20 @@ import com.google.inject.Singleton;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseLoadBalancerListFromJsonResponse extends public class ParseLoadBalancerListFromJsonResponse implements
ParseJson<SortedSet<LoadBalancer>> { Function<HttpResponse, SortedSet<LoadBalancer>> {
private final ParseJson<GenericResponseContainer<LoadBalancer>> json;
@Inject @Inject
ParseLoadBalancerListFromJsonResponse(Gson gson) { ParseLoadBalancerListFromJsonResponse(
super(gson); ParseJson<GenericResponseContainer<LoadBalancer>> json) {
this.json = json;
} }
public SortedSet<LoadBalancer> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<LoadBalancer>>() { public SortedSet<LoadBalancer> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<LoadBalancer> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,46 +18,38 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import org.jclouds.gogrid.domain.Option; import org.jclouds.gogrid.domain.Option;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Singleton; import com.google.inject.Singleton;
/** /**
* Parses the list of generic options. * Parses the list of generic options.
* *
* GoGrid uses options as containers for id/name/description objects. * GoGrid uses options as containers for id/name/descrOptiontion objects.
* *
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseOptionsFromJsonResponse extends ParseJson<SortedSet<Option>> { public class ParseOptionsFromJsonResponse implements
Function<HttpResponse, SortedSet<Option>> {
private final ParseJson<GenericResponseContainer<Option>> json;
@Inject @Inject
ParseOptionsFromJsonResponse(Gson gson) { ParseOptionsFromJsonResponse(ParseJson<GenericResponseContainer<Option>> json) {
super(gson); this.json = json;
} }
public SortedSet<Option> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<Option>>() { public SortedSet<Option> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<Option> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -23,17 +23,14 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.Server;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.HttpResponse;
import com.google.common.base.Function;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.gson.Gson;
import com.google.inject.Singleton;
/** /**
* Parses a single {@link Server} from a json string. * Parses a single {@link Server} from a json string.
@ -43,16 +40,18 @@ import com.google.inject.Singleton;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseServerFromJsonResponse extends ParseJson<Server> { public class ParseServerFromJsonResponse implements
Function<HttpResponse, Server> {
private final ParseServerListFromJsonResponse parser;
@Inject @Inject
ParseServerFromJsonResponse(Gson gson) { ParseServerFromJsonResponse(ParseServerListFromJsonResponse parser) {
super(gson); this.parser = parser;
} }
public Server apply(InputStream stream) { @Override
SortedSet<Server> allServers = new ParseServerListFromJsonResponse(gson) public Server apply(HttpResponse arg0) {
.apply(stream); return Iterables.getOnlyElement(parser.apply(arg0));
return Iterables.getOnlyElement(allServers);
} }
} }

View File

@ -6,7 +6,7 @@
* Licensed to the Apache Software Foundation (ASF) under one * Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file * or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information * distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file * regarding copyright ownershServer. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the * to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance * "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at * with the License. You may obtain a copy of the License at
@ -23,20 +23,16 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.SortedSet; import java.util.SortedSet;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.Server;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
import com.google.gson.reflect.TypeToken;
/** /**
* Parses {@link Server servers} from a json string. * Parses {@link Server servers} from a json string.
@ -44,24 +40,19 @@ import com.google.gson.reflect.TypeToken;
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseServerListFromJsonResponse extends public class ParseServerListFromJsonResponse implements
ParseJson<SortedSet<Server>> { Function<HttpResponse, SortedSet<Server>> {
private final ParseJson<GenericResponseContainer<Server>> json;
@Inject @Inject
ParseServerListFromJsonResponse(Gson gson) { ParseServerListFromJsonResponse(ParseJson<GenericResponseContainer<Server>> json) {
super(gson); this.json = json;
} }
public SortedSet<Server> apply(InputStream stream) { @Override
Type setType = new TypeToken<GenericResponseContainer<Server>>() { public SortedSet<Server> apply(HttpResponse arg0) {
}.getType(); return json.apply(arg0).getList();
GenericResponseContainer<Server> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
return response.getList();
} }
} }

View File

@ -18,10 +18,6 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.util.Map; import java.util.Map;
import javax.inject.Inject; import javax.inject.Inject;
@ -29,41 +25,25 @@ import javax.inject.Singleton;
import org.jclouds.domain.Credentials; import org.jclouds.domain.Credentials;
import org.jclouds.gogrid.domain.Server; import org.jclouds.gogrid.domain.Server;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.common.base.Function;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.SerializedName;
import com.google.gson.reflect.TypeToken;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Singleton @Singleton
public class ParseServerNameToCredentialsMapFromJsonResponse extends public class ParseServerNameToCredentialsMapFromJsonResponse implements
ParseJson<Map<String, Credentials>> { Function<HttpResponse, Map<String, Credentials>> {
private final ParseJson<GenericResponseContainer<Password>> json;
@Inject @Inject
ParseServerNameToCredentialsMapFromJsonResponse(Gson gson) { ParseServerNameToCredentialsMapFromJsonResponse(
super(gson); ParseJson<GenericResponseContainer<Password>> json) {
} this.json = json;
public Map<String, Credentials> apply(InputStream stream) {
Type setType = new TypeToken<GenericResponseContainer<Password>>() {
}.getType();
GenericResponseContainer<Password> response;
try {
response = gson.fromJson(new InputStreamReader(stream, "UTF-8"),
setType);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
Map<String, Credentials> serverNameToCredentials = Maps.newHashMap();
for (Password password : response.getList()) {
serverNameToCredentials.put(password.getServer().getName(),
new Credentials(password.getUserName(), password.getPassword()));
}
return serverNameToCredentials;
} }
// incidental wrapper class to assist in getting the correct data // incidental wrapper class to assist in getting the correct data
@ -122,4 +102,14 @@ public class ParseServerNameToCredentialsMapFromJsonResponse extends
} }
} }
@Override
public Map<String, Credentials> apply(HttpResponse arg0) {
Map<String, Credentials> serverNameToCredentials = Maps.newHashMap();
for (Password password : json.apply(arg0).getList()) {
serverNameToCredentials.put(password.getServer().getName(),
new Credentials(password.getUserName(), password.getPassword()));
}
return serverNameToCredentials;
}
} }

View File

@ -34,7 +34,6 @@ import org.jclouds.http.HttpCommand;
import org.jclouds.http.HttpErrorHandler; import org.jclouds.http.HttpErrorHandler;
import org.jclouds.http.HttpResponse; import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.http.Payload;
import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.AuthorizationException;
import org.jclouds.rest.ResourceNotFoundException; import org.jclouds.rest.ResourceNotFoundException;
@ -57,22 +56,24 @@ public class GoGridErrorHandler implements HttpErrorHandler {
public void handleError(HttpCommand command, HttpResponse response) { public void handleError(HttpCommand command, HttpResponse response) {
try { try {
Exception exception = new HttpResponseException(command, response); Exception exception = new HttpResponseException(command, response);
Set<ErrorResponse> errors = parseErrorsFromContentOrNull(response.getPayload()); Set<ErrorResponse> errors = parseErrorsFromContentOrNull(response);
switch (response.getStatusCode()) { switch (response.getStatusCode()) {
case 400: case 400:
if (Iterables.get(errors, 0).getMessage().indexOf("No object found") != -1) { if (Iterables.get(errors, 0).getMessage()
exception = new ResourceNotFoundException(Iterables.get(errors, 0).getMessage(), .indexOf("No object found") != -1) {
exception); exception = new ResourceNotFoundException(Iterables.get(errors,
0).getMessage(), exception);
break; break;
} }
case 403: case 403:
exception = new AuthorizationException(command.getRequest(), errors != null ? errors exception = new AuthorizationException(command.getRequest(),
.toString() : response.getStatusLine()); errors != null ? errors.toString() : response.getStatusLine());
break; break;
default: default:
exception = errors != null ? new GoGridResponseException(command, response, errors) exception = errors != null ? new GoGridResponseException(command,
: new HttpResponseException(command, response); response, errors) : new HttpResponseException(command,
response);
} }
command.setException(exception); command.setException(exception);
} finally { } finally {
@ -80,10 +81,10 @@ public class GoGridErrorHandler implements HttpErrorHandler {
} }
} }
Set<ErrorResponse> parseErrorsFromContentOrNull(Payload payload) { Set<ErrorResponse> parseErrorsFromContentOrNull(HttpResponse response) {
if (payload != null) { if (response.getPayload() != null) {
try { try {
return errorParser.apply(payload.getInput()); return errorParser.apply(response);
} catch (/* Parsing */Exception e) { } catch (/* Parsing */Exception e) {
return null; return null;
} }

View File

@ -23,36 +23,25 @@
*/ */
package org.jclouds.gogrid.functions; package org.jclouds.gogrid.functions;
import com.google.common.collect.Iterables; import java.io.InputStream;
import com.google.gson.Gson; import java.net.UnknownHostException;
import com.google.inject.Guice;
import com.google.inject.Injector;
import org.jclouds.gogrid.config.DateSecondsAdapter; import org.jclouds.gogrid.config.DateSecondsAdapter;
import org.jclouds.gogrid.domain.internal.ErrorResponse; import org.jclouds.gogrid.domain.internal.ErrorResponse;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.io.InputStream; import com.google.common.collect.Iterables;
import java.net.UnknownHostException; import com.google.inject.Guice;
import com.google.inject.Injector;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
public class ParseErrorFromJsonResponseTest { public class ParseErrorFromJsonResponseTest {
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_error_handler.json");
ParseErrorFromJsonResponse parser = new ParseErrorFromJsonResponse(i
.getInstance(Gson.class));
ErrorResponse response = Iterables.getOnlyElement(parser.apply(is));
assert "No object found that matches your input criteria.".equals(response.getMessage());
assert "IllegalArgumentException".equals(response.getErrorCode());
}
Injector i = Guice.createInjector(new ParserModule() { Injector i = Guice.createInjector(new ParserModule() {
@Override @Override
protected void configure() { protected void configure() {
@ -61,4 +50,18 @@ public class ParseErrorFromJsonResponseTest {
} }
}); });
@Test
public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream(
"/test_error_handler.json");
ParseErrorFromJsonResponse parser = i
.getInstance(ParseErrorFromJsonResponse.class);
ErrorResponse response = Iterables.getOnlyElement(parser
.apply(new HttpResponse(200, "ok", Payloads
.newInputStreamPayload(is))));
assert "No object found that matches your input criteria."
.equals(response.getMessage());
assert "IllegalArgumentException".equals(response.getErrorCode());
}
} }

View File

@ -37,13 +37,14 @@ import org.jclouds.gogrid.domain.JobState;
import org.jclouds.gogrid.domain.ObjectType; import org.jclouds.gogrid.domain.ObjectType;
import org.jclouds.gogrid.domain.Option; import org.jclouds.gogrid.domain.Option;
import org.jclouds.gogrid.functions.internal.CustomDeserializers; import org.jclouds.gogrid.functions.internal.CustomDeserializers;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -56,11 +57,13 @@ public class ParseJobsFromJsonResponseTest {
@Test @Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_get_job_list.json"); InputStream is = getClass()
.getResourceAsStream("/test_get_job_list.json");
ParseJobListFromJsonResponse parser = new ParseJobListFromJsonResponse(i ParseJobListFromJsonResponse parser = i
.getInstance(Gson.class)); .getInstance(ParseJobListFromJsonResponse.class);
SortedSet<Job> response = parser.apply(is); SortedSet<Job> response = parser.apply(new HttpResponse(200, "ok",
Payloads.newInputStreamPayload(is)));
Map<String, String> details = Maps.newTreeMap(); Map<String, String> details = Maps.newTreeMap();
details.put("description", null); details.put("description", null);
@ -69,12 +72,14 @@ public class ParseJobsFromJsonResponseTest {
details.put("name", "ServerCreated40562"); details.put("name", "ServerCreated40562");
details.put("type", "virtual_server"); details.put("type", "virtual_server");
Job job = new Job(250628L, new Option(7L, "DeleteVirtualServer", "Delete Virtual Server"), Job job = new Job(250628L, new Option(7L, "DeleteVirtualServer",
ObjectType.VIRTUAL_SERVER, new Date(1267404528895L), new Date(1267404538592L), "Delete Virtual Server"), ObjectType.VIRTUAL_SERVER, new Date(
JobState.SUCCEEDED, 1, "3116784158f0af2d-24076@api.gogrid.com", ImmutableSortedSet 1267404528895L), new Date(1267404538592L), JobState.SUCCEEDED, 1,
.of(new JobProperties(940263L, new Date(1267404528897L), JobState.CREATED, "3116784158f0af2d-24076@api.gogrid.com", ImmutableSortedSet.of(
null), new JobProperties(940264L, new Date(1267404528967L), new JobProperties(940263L, new Date(1267404528897L),
JobState.QUEUED, null)), details); JobState.CREATED, null), new JobProperties(940264L,
new Date(1267404528967L), JobState.QUEUED, null)),
details);
assertEquals(job, Iterables.getOnlyElement(response)); assertEquals(job, Iterables.getOnlyElement(response));
} }
@ -91,8 +96,10 @@ public class ParseJobsFromJsonResponseTest {
@com.google.inject.name.Named(Constants.PROPERTY_GSON_ADAPTERS) @com.google.inject.name.Named(Constants.PROPERTY_GSON_ADAPTERS)
public Map<Type, Object> provideCustomAdapterBindings() { public Map<Type, Object> provideCustomAdapterBindings() {
Map<Type, Object> bindings = Maps.newHashMap(); Map<Type, Object> bindings = Maps.newHashMap();
bindings.put(ObjectType.class, new CustomDeserializers.ObjectTypeAdapter()); bindings.put(ObjectType.class,
bindings.put(JobState.class, new CustomDeserializers.JobStateAdapter()); new CustomDeserializers.ObjectTypeAdapter());
bindings
.put(JobState.class, new CustomDeserializers.JobStateAdapter());
return bindings; return bindings;
} }
}); });

View File

@ -40,13 +40,14 @@ import org.jclouds.gogrid.domain.LoadBalancerState;
import org.jclouds.gogrid.domain.LoadBalancerType; import org.jclouds.gogrid.domain.LoadBalancerType;
import org.jclouds.gogrid.domain.Option; import org.jclouds.gogrid.domain.Option;
import org.jclouds.gogrid.functions.internal.CustomDeserializers; import org.jclouds.gogrid.functions.internal.CustomDeserializers;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -59,20 +60,28 @@ public class ParseLoadBalancersFromJsonResponseTest {
@Test @Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_get_load_balancer_list.json"); InputStream is = getClass().getResourceAsStream(
"/test_get_load_balancer_list.json");
ParseLoadBalancerListFromJsonResponse parser = i
.getInstance(ParseLoadBalancerListFromJsonResponse.class);
SortedSet<LoadBalancer> response = parser.apply(new HttpResponse(200,
"ok", Payloads.newInputStreamPayload(is)));
ParseLoadBalancerListFromJsonResponse parser = new ParseLoadBalancerListFromJsonResponse(i
.getInstance(Gson.class));
SortedSet<LoadBalancer> response = parser.apply(is);
Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter"); Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter");
LoadBalancer loadBalancer = new LoadBalancer(6372L, "Balancer", null, new IpPortPair(new Ip( LoadBalancer loadBalancer = new LoadBalancer(6372L, "Balancer", null,
1313082L, "204.51.240.181", "204.51.240.176/255.255.255.240", true, new IpPortPair(
new Ip(1313082L, "204.51.240.181",
"204.51.240.176/255.255.255.240", true,
IpState.ASSIGNED, dc), 80), ImmutableSortedSet.of( IpState.ASSIGNED, dc), 80), ImmutableSortedSet.of(
new IpPortPair(new Ip(1313086L, "204.51.240.185", "204.51.240.176/255.255.255.240", new IpPortPair(new Ip(1313086L, "204.51.240.185",
true, IpState.ASSIGNED, dc), 80), new IpPortPair(new Ip(1313089L, "204.51.240.176/255.255.255.240", true,
"204.51.240.188", "204.51.240.176/255.255.255.240", true, IpState.ASSIGNED, IpState.ASSIGNED, dc), 80), new IpPortPair(new Ip(
dc), 80)), LoadBalancerType.ROUND_ROBIN, LoadBalancerPersistenceType.NONE, 1313089L, "204.51.240.188",
"204.51.240.176/255.255.255.240", true,
IpState.ASSIGNED, dc), 80)),
LoadBalancerType.ROUND_ROBIN, LoadBalancerPersistenceType.NONE,
LoadBalancerOs.F5, LoadBalancerState.ON, dc); LoadBalancerOs.F5, LoadBalancerState.ON, dc);
assertEquals(Iterables.getOnlyElement(response), loadBalancer); assertEquals(Iterables.getOnlyElement(response), loadBalancer);
} }
@ -90,11 +99,14 @@ public class ParseLoadBalancersFromJsonResponseTest {
@com.google.inject.name.Named(Constants.PROPERTY_GSON_ADAPTERS) @com.google.inject.name.Named(Constants.PROPERTY_GSON_ADAPTERS)
public Map<Type, Object> provideCustomAdapterBindings() { public Map<Type, Object> provideCustomAdapterBindings() {
Map<Type, Object> bindings = Maps.newHashMap(); Map<Type, Object> bindings = Maps.newHashMap();
bindings.put(LoadBalancerOs.class, new CustomDeserializers.LoadBalancerOsAdapter()); bindings.put(LoadBalancerOs.class,
bindings.put(LoadBalancerState.class, new CustomDeserializers.LoadBalancerStateAdapter()); new CustomDeserializers.LoadBalancerOsAdapter());
bindings.put(LoadBalancerState.class,
new CustomDeserializers.LoadBalancerStateAdapter());
bindings.put(LoadBalancerPersistenceType.class, bindings.put(LoadBalancerPersistenceType.class,
new CustomDeserializers.LoadBalancerPersistenceTypeAdapter()); new CustomDeserializers.LoadBalancerPersistenceTypeAdapter());
bindings.put(LoadBalancerType.class, new CustomDeserializers.LoadBalancerTypeAdapter()); bindings.put(LoadBalancerType.class,
new CustomDeserializers.LoadBalancerTypeAdapter());
bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter()); bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());
return bindings; return bindings;
} }

View File

@ -34,11 +34,12 @@ import org.jclouds.gogrid.domain.IpState;
import org.jclouds.gogrid.domain.ServerImageState; import org.jclouds.gogrid.domain.ServerImageState;
import org.jclouds.gogrid.domain.ServerImageType; import org.jclouds.gogrid.domain.ServerImageType;
import org.jclouds.gogrid.functions.internal.CustomDeserializers; import org.jclouds.gogrid.functions.internal.CustomDeserializers;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -51,11 +52,14 @@ public class ParseServerNameToCredentialsMapFromJsonResponseTest {
@Test @Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_credentials_list.json"); InputStream is = getClass().getResourceAsStream(
"/test_credentials_list.json");
ParseServerNameToCredentialsMapFromJsonResponse parser = i
.getInstance(ParseServerNameToCredentialsMapFromJsonResponse.class);
Map<String, Credentials> response = parser.apply(new HttpResponse(200,
"ok", Payloads.newInputStreamPayload(is)));
ParseServerNameToCredentialsMapFromJsonResponse parser = new ParseServerNameToCredentialsMapFromJsonResponse(
i.getInstance(Gson.class));
Map<String, Credentials> response = parser.apply(is);
assertEquals(response.size(), 6); assertEquals(response.size(), 6);
} }
@ -73,9 +77,12 @@ public class ParseServerNameToCredentialsMapFromJsonResponseTest {
public Map<Type, Object> provideCustomAdapterBindings() { public Map<Type, Object> provideCustomAdapterBindings() {
Map<Type, Object> bindings = Maps.newHashMap(); Map<Type, Object> bindings = Maps.newHashMap();
bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter()); bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());
bindings.put(ServerImageType.class, new CustomDeserializers.ServerImageTypeAdapter()); bindings.put(ServerImageType.class,
bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter()); new CustomDeserializers.ServerImageTypeAdapter());
bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter()); bindings.put(ServerImageState.class,
new CustomDeserializers.ServerImageStateAdapter());
bindings.put(ServerImageState.class,
new CustomDeserializers.ServerImageStateAdapter());
return bindings; return bindings;
} }
}); });

View File

@ -45,13 +45,14 @@ import org.jclouds.gogrid.domain.ServerImage;
import org.jclouds.gogrid.domain.ServerImageState; import org.jclouds.gogrid.domain.ServerImageState;
import org.jclouds.gogrid.domain.ServerImageType; import org.jclouds.gogrid.domain.ServerImageType;
import org.jclouds.gogrid.functions.internal.CustomDeserializers; import org.jclouds.gogrid.functions.internal.CustomDeserializers;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Maps; import com.google.common.collect.Maps;
import com.google.gson.Gson;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
import com.google.inject.Provides; import com.google.inject.Provides;
@ -66,26 +67,35 @@ public class ParseServersFromJsonResponseTest {
@Test @Test
public void testApplyInputStreamDetails() throws UnknownHostException { public void testApplyInputStreamDetails() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/test_get_server_list.json"); InputStream is = getClass().getResourceAsStream(
"/test_get_server_list.json");
ParseServerListFromJsonResponse parser = i
.getInstance(ParseServerListFromJsonResponse.class);
SortedSet<Server> response = parser.apply(new HttpResponse(200, "ok",
Payloads.newInputStreamPayload(is)));
ParseServerListFromJsonResponse parser = new ParseServerListFromJsonResponse(i
.getInstance(Gson.class));
SortedSet<Server> response = parser.apply(is);
Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter"); Option dc = new Option(1l, "US-West-1", "US West 1 Datacenter");
Option centOs = new Option(13L, "CentOS 5.2 (32-bit)", "CentOS 5.2 (32-bit)"); Option centOs = new Option(13L, "CentOS 5.2 (32-bit)",
Option webServer = new Option(1L, "Web Server", "Web or Application Server"); "CentOS 5.2 (32-bit)");
Option webServer = new Option(1L, "Web Server",
"Web or Application Server");
Server server = new Server(75245L, dc, false, "PowerServer", Server server = new Server(75245L, dc, false, "PowerServer",
"server to test the api. created by Alex", new Option(1L, "On", "server to test the api. created by Alex", new Option(1L, "On",
"Server is in active state."), webServer, new Option(1L, "512MB", "Server is in active state."), webServer, new Option(1L,
"Server with 512MB RAM"), centOs, new Ip(1313079L, "204.51.240.178", "512MB", "Server with 512MB RAM"), centOs, new Ip(1313079L,
"204.51.240.176/255.255.255.240", true, IpState.ASSIGNED, dc), new ServerImage( "204.51.240.178", "204.51.240.176/255.255.255.240", true,
1946L, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c", IpState.ASSIGNED, dc), new ServerImage(1946L,
"BitNami Gallery 2.3.1-0", "http://bitnami.org/stack/gallery", centOs, "GSI-f8979644-e646-4711-ad58-d98a5fa3612c",
null, ServerImageType.WEB_APPLICATION_SERVER, ServerImageState.AVAILABLE, "BitNami Gallery 2.3.1-0",
0.0, "24732/GSI-f8979644-e646-4711-ad58-d98a5fa3612c.img", true, true, "http://bitnami.org/stack/gallery", centOs, null,
new Date(1261504577971L), new Date(1262649582180L), ImmutableSortedSet.of( ServerImageType.WEB_APPLICATION_SERVER,
new BillingToken(38L, "CentOS 5.2 32bit", 0.0), new BillingToken( ServerImageState.AVAILABLE, 0.0,
56L, "BitNami: Gallery", 0.0)), new Customer(24732L, "24732/GSI-f8979644-e646-4711-ad58-d98a5fa3612c.img", true,
true, new Date(1261504577971L), new Date(1262649582180L),
ImmutableSortedSet.of(new BillingToken(38L,
"CentOS 5.2 32bit", 0.0), new BillingToken(56L,
"BitNami: Gallery", 0.0)), new Customer(24732L,
"BitRock"))); "BitRock")));
assertEquals(Iterables.getOnlyElement(response), server); assertEquals(Iterables.getOnlyElement(response), server);
} }
@ -104,8 +114,10 @@ public class ParseServersFromJsonResponseTest {
public Map<Class, Object> provideCustomAdapterBindings() { public Map<Class, Object> provideCustomAdapterBindings() {
Map<Class, Object> bindings = Maps.newHashMap(); Map<Class, Object> bindings = Maps.newHashMap();
bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter()); bindings.put(IpState.class, new CustomDeserializers.IpStateAdapter());
bindings.put(ServerImageType.class, new CustomDeserializers.ServerImageTypeAdapter()); bindings.put(ServerImageType.class,
bindings.put(ServerImageState.class, new CustomDeserializers.ServerImageStateAdapter()); new CustomDeserializers.ServerImageTypeAdapter());
bindings.put(ServerImageState.class,
new CustomDeserializers.ServerImageStateAdapter());
return bindings; return bindings;
} }
}); });

View File

@ -40,8 +40,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest<GridImag
@Test @Test
public void testGetImageListWithOptions() throws NoSuchMethodException, IOException { public void testGetImageListWithOptions() throws NoSuchMethodException, IOException {
Method method = GridImageAsyncClient.class.getMethod("getImageList", Method method = GridImageAsyncClient.class.getMethod("getImageList", GetImageListOptions[].class);
GetImageListOptions[].class);
GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method,
new GetImageListOptions().onlyPublic().setState(ServerImageState.AVAILABLE).setType( new GetImageListOptions().onlyPublic().setState(ServerImageState.AVAILABLE).setType(
ServerImageType.WEB_APPLICATION_SERVER)); ServerImageType.WEB_APPLICATION_SERVER));
@ -68,8 +67,7 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest<GridImag
@Test @Test
public void testGetImagesByName() throws NoSuchMethodException, IOException { public void testGetImagesByName() throws NoSuchMethodException, IOException {
Method method = GridImageAsyncClient.class.getMethod("getImagesByName", String[].class); Method method = GridImageAsyncClient.class.getMethod("getImagesByName", String[].class);
GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, "name1", "name2");
"name1", "name2");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/get?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/get?v=1.5&"
+ "name=name1&name=name2 HTTP/1.1"); + "name=name1&name=name2 HTTP/1.1");
@ -84,18 +82,15 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest<GridImag
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/get?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/get?v=1.5&"
+ "name=name1&name=name2&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "name=name1&name=name2&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testEditImageDescription() throws NoSuchMethodException, IOException { public void testEditImageDescription() throws NoSuchMethodException, IOException {
Method method = GridImageAsyncClient.class.getMethod("editImageDescription", String.class, Method method = GridImageAsyncClient.class.getMethod("editImageDescription", String.class, String.class);
String.class); GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, "imageName", "newDesc");
GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method,
"imageName", "newDesc");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&"
+ "image=imageName&description=newDesc HTTP/1.1"); + "image=imageName&description=newDesc HTTP/1.1");
@ -110,18 +105,16 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest<GridImag
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&"
+ "image=imageName&description=newDesc&" + "image=imageName&description=newDesc&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testEditImageFriendlyName() throws NoSuchMethodException, IOException { public void testEditImageFriendlyName() throws NoSuchMethodException, IOException {
Method method = GridImageAsyncClient.class.getMethod("editImageFriendlyName", String.class, Method method = GridImageAsyncClient.class.getMethod("editImageFriendlyName", String.class, String.class);
String.class); GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, "imageName",
GeneratedHttpRequest<GridImageAsyncClient> httpRequest = processor.createRequest(method, "newFriendlyName");
"imageName", "newFriendlyName");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&"
+ "image=imageName&friendlyName=newFriendlyName HTTP/1.1"); + "image=imageName&friendlyName=newFriendlyName HTTP/1.1");
@ -136,8 +129,8 @@ public class GridImageAsyncClientTest extends BaseGoGridAsyncClientTest<GridImag
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/image/edit?v=1.5&"
+ "image=imageName&friendlyName=newFriendlyName&" + "image=imageName&friendlyName=newFriendlyName&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1"); + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }

View File

@ -39,11 +39,10 @@ public class GridIpAsyncClientTest extends BaseGoGridAsyncClientTest<GridIpAsync
@Test @Test
public void testGetIpListWithOptions() throws NoSuchMethodException, IOException { public void testGetIpListWithOptions() throws NoSuchMethodException, IOException {
Method method = GridIpAsyncClient.class.getMethod("getIpList", GetIpListOptions[].class); Method method = GridIpAsyncClient.class.getMethod("getIpList", GetIpListOptions[].class);
GeneratedHttpRequest<GridIpAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<GridIpAsyncClient> httpRequest = processor.createRequest(method, new GetIpListOptions()
new GetIpListOptions().onlyUnassigned().onlyWithType(IpType.PUBLIC)); .onlyUnassigned().onlyWithType(IpType.PUBLIC));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&"
"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&"
+ "ip.type=Public HTTP/1.1"); + "ip.type=Public HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -55,10 +54,8 @@ public class GridIpAsyncClientTest extends BaseGoGridAsyncClientTest<GridIpAsync
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&"
"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Unassigned&" + "ip.type=Public&sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "ip.type=Public&sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@ -80,8 +77,7 @@ public class GridIpAsyncClientTest extends BaseGoGridAsyncClientTest<GridIpAsync
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Assigned&"
"GET https://api.gogrid.com/api/grid/ip/list?v=1.5&ip.state=Assigned&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1"); + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);

View File

@ -42,14 +42,13 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest<GridJobAsy
public void testGetJobListWithOptions() throws NoSuchMethodException, IOException { public void testGetJobListWithOptions() throws NoSuchMethodException, IOException {
Method method = GridJobAsyncClient.class.getMethod("getJobList", GetJobListOptions[].class); Method method = GridJobAsyncClient.class.getMethod("getJobList", GetJobListOptions[].class);
GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method,
new GetJobListOptions.Builder().create().withStartDate(new Date(1267385381770L)) new GetJobListOptions.Builder().create().withStartDate(new Date(1267385381770L)).withEndDate(
.withEndDate(new Date(1267385382770L)).onlyForObjectType( new Date(1267385382770L)).onlyForObjectType(ObjectType.VIRTUAL_SERVER).onlyForState(
ObjectType.VIRTUAL_SERVER).onlyForState(JobState.PROCESSING)); JobState.PROCESSING));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&" "GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&"
+ "enddate=1267385382770&job.objecttype=VirtualServer&" + "enddate=1267385382770&job.objecttype=VirtualServer&" + "job.state=Processing HTTP/1.1");
+ "job.state=Processing HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -62,8 +61,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest<GridJobAsy
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&" "GET https://api.gogrid.com/api/grid/job/list?v=1.5&startdate=1267385381770&"
+ "enddate=1267385382770&job.objecttype=VirtualServer&" + "enddate=1267385382770&job.objecttype=VirtualServer&" + "job.state=Processing&"
+ "job.state=Processing&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo HTTP/1.1"); + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -74,8 +72,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest<GridJobAsy
Method method = GridJobAsyncClient.class.getMethod("getJobList", GetJobListOptions[].class); Method method = GridJobAsyncClient.class.getMethod("getJobList", GetJobListOptions[].class);
GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/list?v=1.5 HTTP/1.1");
"GET https://api.gogrid.com/api/grid/job/list?v=1.5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@ -83,8 +80,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest<GridJobAsy
@Test @Test
public void testGetJobsForServerName() throws NoSuchMethodException, IOException { public void testGetJobsForServerName() throws NoSuchMethodException, IOException {
Method method = GridJobAsyncClient.class.getMethod("getJobsForObjectName", String.class); Method method = GridJobAsyncClient.class.getMethod("getJobsForObjectName", String.class);
GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method, GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method, "MyServer");
"MyServer");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/list?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/list?v=1.5&"
+ "object=MyServer HTTP/1.1"); + "object=MyServer HTTP/1.1");
@ -107,8 +103,7 @@ public class GridJobAsyncClientTest extends BaseGoGridAsyncClientTest<GridJobAsy
@Test @Test
public void testGetJobsById() throws NoSuchMethodException, IOException { public void testGetJobsById() throws NoSuchMethodException, IOException {
Method method = GridJobAsyncClient.class.getMethod("getJobsById", long[].class); Method method = GridJobAsyncClient.class.getMethod("getJobsById", long[].class);
GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method, 123L, GeneratedHttpRequest<GridJobAsyncClient> httpRequest = processor.createRequest(method, 123L, 456L);
456L);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/get?v=1.5&" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/job/get?v=1.5&"
+ "id=123&id=456 HTTP/1.1"); + "id=123&id=456 HTTP/1.1");

View File

@ -40,30 +40,25 @@ import com.google.inject.TypeLiteral;
/** /**
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
public class GridLoadBalancerAsyncClientTest extends public class GridLoadBalancerAsyncClientTest extends BaseGoGridAsyncClientTest<GridLoadBalancerAsyncClient> {
BaseGoGridAsyncClientTest<GridLoadBalancerAsyncClient> {
@Test @Test
public void testGetLoadBalancerList() throws NoSuchMethodException, IOException { public void testGetLoadBalancerList() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("getLoadBalancerList"); Method method = GridLoadBalancerAsyncClient.class.getMethod("getLoadBalancerList");
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5 HTTP/1.1");
"GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerListFromJsonResponse.class);
ParseLoadBalancerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5&"
"GET https://api.gogrid.com/api/grid/loadbalancer/list?v=1.5&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1"); + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -71,12 +66,11 @@ public class GridLoadBalancerAsyncClientTest extends
@Test @Test
public void testAddLoadBalancer() throws NoSuchMethodException, IOException { public void testAddLoadBalancer() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("addLoadBalancer", String.class, Method method = GridLoadBalancerAsyncClient.class.getMethod("addLoadBalancer", String.class, IpPortPair.class,
IpPortPair.class, List.class, AddLoadBalancerOptions[].class); List.class, AddLoadBalancerOptions[].class);
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method, "BalanceIt",
method, "BalanceIt", new IpPortPair(new Ip("127.0.0.1"), 80), Arrays.asList( new IpPortPair(new Ip("127.0.0.1"), 80), Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080),
new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip( new IpPortPair(new Ip("127.0.0.1"), 9090)), new AddLoadBalancerOptions.Builder().create(
"127.0.0.1"), 9090)), new AddLoadBalancerOptions.Builder().create(
LoadBalancerType.LEAST_CONNECTED, LoadBalancerPersistenceType.SSL_STICKY)); LoadBalancerType.LEAST_CONNECTED, LoadBalancerPersistenceType.SSL_STICKY));
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/"
@ -98,19 +92,17 @@ public class GridLoadBalancerAsyncClientTest extends
+ "add?v=1.5&name=BalanceIt&loadbalancer.type=Least%20Connect&" + "add?v=1.5&name=BalanceIt&loadbalancer.type=Least%20Connect&"
+ "loadbalancer.persistence=SSL%20Sticky&realiplist.0.ip=127.0.0.1&" + "loadbalancer.persistence=SSL%20Sticky&realiplist.0.ip=127.0.0.1&"
+ "realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090&" + "realiplist.0.port=8080&realiplist.1.ip=127.0.0.1&realiplist.1.port=9090&"
+ "virtualip.ip=127.0.0.1&virtualip.port=80&" + "virtualip.ip=127.0.0.1&virtualip.port=80&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1"); + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testEditLoadBalancer() throws NoSuchMethodException, IOException { public void testEditLoadBalancer() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("editLoadBalancer", long.class, Method method = GridLoadBalancerAsyncClient.class.getMethod("editLoadBalancer", long.class, List.class);
List.class); GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method, 1l, Arrays
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest( .asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip("127.0.0.1"), 9090)));
method, 1l, Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(
new Ip("127.0.0.1"), 9090)));
assertRequestLineEquals( assertRequestLineEquals(
httpRequest, httpRequest,
@ -134,11 +126,9 @@ public class GridLoadBalancerAsyncClientTest extends
@Test @Test
public void testEditLoadBalancerNamed() throws NoSuchMethodException, IOException { public void testEditLoadBalancerNamed() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("editLoadBalancerNamed", Method method = GridLoadBalancerAsyncClient.class.getMethod("editLoadBalancerNamed", String.class, List.class);
String.class, List.class); GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method, "BalanceIt",
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest( Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080), new IpPortPair(new Ip("127.0.0.1"), 9090)));
method, "BalanceIt", Arrays.asList(new IpPortPair(new Ip("127.0.0.1"), 8080),
new IpPortPair(new Ip("127.0.0.1"), 9090)));
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/"
+ "edit?v=1.5&name=BalanceIt&realiplist.0.ip=127.0.0.1&" + "edit?v=1.5&name=BalanceIt&realiplist.0.ip=127.0.0.1&"
@ -162,18 +152,16 @@ public class GridLoadBalancerAsyncClientTest extends
@Test @Test
public void testGetLoadBalancersByName() throws NoSuchMethodException, IOException { public void testGetLoadBalancersByName() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("getLoadBalancersByName", Method method = GridLoadBalancerAsyncClient.class.getMethod("getLoadBalancersByName", String[].class);
String[].class); GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method,
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest( "My Load Balancer", "My Load Balancer 2");
method, "My Load Balancer", "My Load Balancer 2");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/"
+ "get?v=1.5&name=My%20Load%20Balancer&name=My%20Load%20Balancer%202 HTTP/1.1"); + "get?v=1.5&name=My%20Load%20Balancer&name=My%20Load%20Balancer%202 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseLoadBalancerListFromJsonResponse.class);
ParseLoadBalancerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -190,8 +178,7 @@ public class GridLoadBalancerAsyncClientTest extends
@Test @Test
public void testDeleteLoadBalancerById() throws NoSuchMethodException, IOException { public void testDeleteLoadBalancerById() throws NoSuchMethodException, IOException {
Method method = GridLoadBalancerAsyncClient.class.getMethod("deleteById", Long.class); Method method = GridLoadBalancerAsyncClient.class.getMethod("deleteById", Long.class);
GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<GridLoadBalancerAsyncClient> httpRequest = processor.createRequest(method, 55L);
method, 55L);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/"
+ "delete?v=1.5&id=55 HTTP/1.1"); + "delete?v=1.5&id=55 HTTP/1.1");
@ -205,9 +192,8 @@ public class GridLoadBalancerAsyncClientTest extends
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/loadbalancer/" + "delete?v=1.5&id=55&"
+ "delete?v=1.5&id=55&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }

View File

@ -67,170 +67,130 @@ import com.google.inject.TypeLiteral;
* @author Oleksiy Yarmula * @author Oleksiy Yarmula
*/ */
@Test(groups = "unit", testName = "gogrid.GoGridAsyncClientTest") @Test(groups = "unit", testName = "gogrid.GoGridAsyncClientTest")
public class GridServerAsyncClientTest extends public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridServerAsyncClient> {
BaseGoGridAsyncClientTest<GridServerAsyncClient> {
@Test @Test
public void testGetServerListNoOptions() throws NoSuchMethodException, public void testGetServerListNoOptions() throws NoSuchMethodException, IOException {
IOException { Method method = GridServerAsyncClient.class.getMethod("getServerList", GetServerListOptions[].class);
Method method = GridServerAsyncClient.class.getMethod("getServerList", GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method);
GetServerListOptions[].class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/list?v=1.5 HTTP/1.1");
"GET https://api.gogrid.com/api/grid/server/list?v=1.5 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/list?"
"GET https://api.gogrid.com/api/grid/server/list?" + "v=1.5&sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "v=1.5&sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testGetServerListWithOptions() throws NoSuchMethodException, public void testGetServerListWithOptions() throws NoSuchMethodException, IOException {
IOException { Method method = GridServerAsyncClient.class.getMethod("getServerList", GetServerListOptions[].class);
Method method = GridServerAsyncClient.class.getMethod("getServerList", GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method,
GetServerListOptions[].class); new GetServerListOptions.Builder().onlySandboxServers());
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, new GetServerListOptions.Builder()
.onlySandboxServers());
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://api.gogrid.com/api/grid/server/list?v=1.5&isSandbox=true HTTP/1.1"); "GET https://api.gogrid.com/api/grid/server/list?v=1.5&isSandbox=true HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals( assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/list?"
httpRequest, + "v=1.5&isSandbox=true&sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
"GET https://api.gogrid.com/api/grid/server/list?"
+ "v=1.5&isSandbox=true&sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testGetServersByName() throws NoSuchMethodException, IOException { public void testGetServersByName() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("getServersByName", Method method = GridServerAsyncClient.class.getMethod("getServersByName", String[].class);
String[].class); GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "server1");
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, "server1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?v=1.5&name=server1 HTTP/1.1");
"GET https://api.gogrid.com/api/grid/server/get?v=1.5&name=server1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?" + "v=1.5&name=server1&"
"GET https://api.gogrid.com/api/grid/server/get?" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "v=1.5&name=server1&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testGetServersById() throws NoSuchMethodException, IOException { public void testGetServersById() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("getServersById", Method method = GridServerAsyncClient.class.getMethod("getServersById", long[].class);
long[].class); GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, 123L);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, 123L);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?v=1.5&id=123 HTTP/1.1");
"GET https://api.gogrid.com/api/grid/server/get?v=1.5&id=123 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class); assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?" + "v=1.5&id=123&"
"GET https://api.gogrid.com/api/grid/server/get?" + "v=1.5&id=123&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testAddServerNoOptions() throws NoSuchMethodException, public void testAddServerNoOptions() throws NoSuchMethodException, IOException {
IOException { Method method = GridServerAsyncClient.class.getMethod("addServer", String.class, String.class, String.class,
Method method = GridServerAsyncClient.class.getMethod("addServer", String.class, AddServerOptions[].class);
String.class, String.class, String.class, String.class, GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "serverName", "img55",
AddServerOptions[].class); "memory", "127.0.0.1");
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, "serverName", "img55", "memory", "127.0.0.1");
assertRequestLineEquals( assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/add?v=1.5&"
httpRequest, + "name=serverName&server.ram=memory&image=img55&ip=127.0.0.1 " + "HTTP/1.1");
"GET https://api.gogrid.com/api/grid/server/add?v=1.5&"
+ "name=serverName&server.ram=memory&image=img55&ip=127.0.0.1 "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerFromJsonResponse.class);
ParseServerFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/add?"
"GET https://api.gogrid.com/api/grid/server/add?" + "v=1.5&name=serverName&server.ram=memory&" + "image=img55&ip=127.0.0.1&"
+ "v=1.5&name=serverName&server.ram=memory&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "image=img55&ip=127.0.0.1&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testAddServerOptions() throws NoSuchMethodException, IOException { public void testAddServerOptions() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("addServer", Method method = GridServerAsyncClient.class.getMethod("addServer", String.class, String.class, String.class,
String.class, String.class, String.class, String.class, String.class, AddServerOptions[].class);
AddServerOptions[].class); GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "serverName", "img55",
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor "memory", "127.0.0.1", new AddServerOptions().asSandboxType().withDescription("fooy"));
.createRequest(method, "serverName", "img55", "memory",
"127.0.0.1", new AddServerOptions().asSandboxType()
.withDescription("fooy"));
assertRequestLineEquals( assertRequestLineEquals(
httpRequest, httpRequest,
@ -238,8 +198,7 @@ public class GridServerAsyncClientTest extends
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerFromJsonResponse.class);
ParseServerFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -255,60 +214,47 @@ public class GridServerAsyncClientTest extends
@Test @Test
public void testPowerServer() throws NoSuchMethodException, IOException { public void testPowerServer() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("power", Method method = GridServerAsyncClient.class.getMethod("power", String.class, PowerCommand.class);
String.class, PowerCommand.class); GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "PowerServer",
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor PowerCommand.RESTART);
.createRequest(method, "PowerServer", PowerCommand.RESTART);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/power?v=1.5&"
"GET https://api.gogrid.com/api/grid/server/power?v=1.5&"
+ "server=PowerServer&power=restart " + "HTTP/1.1"); + "server=PowerServer&power=restart " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerFromJsonResponse.class);
ParseServerFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/power?v=1.5&"
"GET https://api.gogrid.com/api/grid/server/power?v=1.5&" + "server=PowerServer&power=restart&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "server=PowerServer&power=restart&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testDeleteByName() throws NoSuchMethodException, IOException { public void testDeleteByName() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("deleteByName", Method method = GridServerAsyncClient.class.getMethod("deleteByName", String.class);
String.class); GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "PowerServer");
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, "PowerServer");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/delete?v=1.5&"
"GET https://api.gogrid.com/api/grid/server/delete?v=1.5&"
+ "name=PowerServer " + "HTTP/1.1"); + "name=PowerServer " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseServerFromJsonResponse.class);
ParseServerFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/delete?v=1.5&"
"GET https://api.gogrid.com/api/grid/server/delete?v=1.5&" + "name=PowerServer&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "name=PowerServer&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@ -316,46 +262,37 @@ public class GridServerAsyncClientTest extends
@Test @Test
public void testGetRamSizes() throws NoSuchMethodException, IOException { public void testGetRamSizes() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("getRamSizes"); Method method = GridServerAsyncClient.class.getMethod("getRamSizes");
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram "
"GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram "
+ "HTTP/1.1"); + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseOptionsFromJsonResponse.class);
ParseOptionsFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
checkFilters(httpRequest); checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram&"
"GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram&" + "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo "
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
} }
@Test @Test
public void testServerCredentials() throws NoSuchMethodException, public void testServerCredentials() throws NoSuchMethodException, IOException {
IOException { Method method = GridServerAsyncClient.class.getMethod("getServerCredentials", long.class);
Method method = GridServerAsyncClient.class.getMethod( GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, 1);
"getServerCredentials", long.class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor
.createRequest(method, 1);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://api.gogrid.com/api/support/grid/password/get?v=1.5&id=1 HTTP/1.1"); "GET https://api.gogrid.com/api/support/grid/password/get?v=1.5&id=1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, assertResponseParserClassEquals(method, httpRequest, ParseCredentialsFromJsonResponse.class);
ParseCredentialsFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
} }

View File

@ -52,7 +52,6 @@ import org.jclouds.ibmdev.functions.ParseImageFromJson;
import org.jclouds.ibmdev.functions.ParseImagesFromJson; import org.jclouds.ibmdev.functions.ParseImagesFromJson;
import org.jclouds.ibmdev.functions.ParseInstanceFromJson; import org.jclouds.ibmdev.functions.ParseInstanceFromJson;
import org.jclouds.ibmdev.functions.ParseInstancesFromJson; import org.jclouds.ibmdev.functions.ParseInstancesFromJson;
import org.jclouds.ibmdev.functions.ParseKeyFromJson;
import org.jclouds.ibmdev.functions.ParseKeysFromJson; import org.jclouds.ibmdev.functions.ParseKeysFromJson;
import org.jclouds.ibmdev.functions.ParseLongFromDate; import org.jclouds.ibmdev.functions.ParseLongFromDate;
import org.jclouds.ibmdev.functions.ParseVolumeFromJson; import org.jclouds.ibmdev.functions.ParseVolumeFromJson;
@ -83,7 +82,6 @@ import com.google.common.util.concurrent.ListenableFuture;
* @author Adrian Cole * @author Adrian Cole
*/ */
@RequestFilters(BasicAuthentication.class) @RequestFilters(BasicAuthentication.class)
@Consumes(MediaType.APPLICATION_JSON)
@SkipEncoding( { '{', '}' }) @SkipEncoding( { '{', '}' })
public interface IBMDeveloperCloudAsyncClient { public interface IBMDeveloperCloudAsyncClient {
public static final String VERSION = "20090403"; public static final String VERSION = "20090403";
@ -93,6 +91,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/images")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImagesFromJson.class) @ResponseParser(ParseImagesFromJson.class)
ListenableFuture<Set<? extends Image>> listImages(); ListenableFuture<Set<? extends Image>> listImages();
@ -102,6 +101,7 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class) @ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> getImage(@PathParam("imageId") String id); ListenableFuture<Image> getImage(@PathParam("imageId") String id);
@ -119,6 +119,7 @@ public interface IBMDeveloperCloudAsyncClient {
@PUT @PUT
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class) @ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id, ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id,
@FormParam("visibility") Image.Visibility visibility); @FormParam("visibility") Image.Visibility visibility);
@ -129,15 +130,16 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/requests/{requestId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/requests/{requestId}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class) @ResponseParser(ParseInstancesFromJson.class)
ListenableFuture<Set<? extends Instance>> listInstancesFromRequest( ListenableFuture<Set<? extends Instance>> listInstancesFromRequest(@PathParam("requestId") String requestId);
@PathParam("requestId") String requestId);
/** /**
* @see IBMDeveloperCloudClient#listInstances() * @see IBMDeveloperCloudClient#listInstances()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class) @ResponseParser(ParseInstancesFromJson.class)
ListenableFuture<Set<? extends Instance>> listInstances(); ListenableFuture<Set<? extends Instance>> listInstances();
@ -147,6 +149,7 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstanceFromJson.class) @ResponseParser(ParseInstanceFromJson.class)
ListenableFuture<Instance> getInstance(@PathParam("instanceId") String id); ListenableFuture<Instance> getInstance(@PathParam("instanceId") String id);
@ -156,6 +159,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseExpirationTimeFromJson.class) @ResponseParser(ParseExpirationTimeFromJson.class)
ListenableFuture<Date> extendReservationForInstance(@PathParam("instanceId") String id, ListenableFuture<Date> extendReservationForInstance(@PathParam("instanceId") String id,
@FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime); @FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime);
@ -166,25 +170,25 @@ public interface IBMDeveloperCloudAsyncClient {
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}")
@FormParams(keys = "state", values = "restart") @FormParams(keys = "state", values = "restart")
ListenableFuture<Void> restartInstance(@PathParam("instanceId") String id, ListenableFuture<Void> restartInstance(@PathParam("instanceId") String id, RestartInstanceOptions... options);
RestartInstanceOptions... options);
/** /**
* @see IBMDeveloperCloudClient#saveInstanceToImage * @see IBMDeveloperCloudClient#saveInstanceToImage
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances/{instanceId}")
@Consumes(MediaType.APPLICATION_JSON)
@FormParams(keys = "state", values = "save") @FormParams(keys = "state", values = "save")
@ResponseParser(ParseImageFromJson.class) @ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> saveInstanceToImage(@PathParam("instanceId") String id, ListenableFuture<Image> saveInstanceToImage(@PathParam("instanceId") String id,
@FormParam("name") String toImageName, @FormParam("name") String toImageName, @FormParam("description") String toImageDescription);
@FormParam("description") String toImageDescription);
/** /**
* @see IBMDeveloperCloudClient#createInstanceInLocation * @see IBMDeveloperCloudClient#createInstanceInLocation
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(GetFirstInstanceInList.class) @ResponseParser(GetFirstInstanceInList.class)
ListenableFuture<Instance> createInstanceInLocation(@FormParam("location") String location, ListenableFuture<Instance> createInstanceInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("imageID") String imageID, @FormParam("name") String name, @FormParam("imageID") String imageID,
@ -203,6 +207,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseKeysFromJson.class) @ResponseParser(ParseKeysFromJson.class)
ListenableFuture<Set<? extends Key>> listKeys(); ListenableFuture<Set<? extends Key>> listKeys();
@ -211,7 +216,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys")
@ResponseParser(ParseKeyFromJson.class) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Key> generateKeyPair(@FormParam("name") String name); ListenableFuture<Key> generateKeyPair(@FormParam("name") String name);
/** /**
@ -219,16 +224,14 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys")
ListenableFuture<Void> addPublicKey(@FormParam("name") String name, ListenableFuture<Void> addPublicKey(@FormParam("name") String name, @FormParam("publicKey") String publicKey);
@FormParam("publicKey") String publicKey);
/** /**
* @see IBMDeveloperCloudClient#updatePublicKey(String, String) * @see IBMDeveloperCloudClient#updatePublicKey(String, String)
*/ */
@PUT @PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}")
ListenableFuture<Void> updatePublicKey(@PathParam("keyName") String name, ListenableFuture<Void> updatePublicKey(@PathParam("keyName") String name, @FormParam("publicKey") String publicKey);
@FormParam("publicKey") String publicKey);
/** /**
* @see IBMDeveloperCloudClient#setDefaultStatusOfKey(String, boolean) * @see IBMDeveloperCloudClient#setDefaultStatusOfKey(String, boolean)
@ -244,7 +247,7 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}")
@ResponseParser(ParseKeyFromJson.class) @Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Key> getKey(@PathParam("keyName") String name); ListenableFuture<Key> getKey(@PathParam("keyName") String name);
/** /**
@ -261,6 +264,7 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage")
@ResponseParser(ParseVolumesFromJson.class) @ResponseParser(ParseVolumesFromJson.class)
@Consumes(MediaType.APPLICATION_JSON)
ListenableFuture<Set<? extends Volume>> listVolumes(); ListenableFuture<Set<? extends Volume>> listVolumes();
/** /**
@ -268,10 +272,10 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class) @ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location, ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("format") String format, @FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size);
@FormParam("size") String size);
/** /**
* @see IBMDeveloperCloudClient#getVolume(long) * @see IBMDeveloperCloudClient#getVolume(long)
@ -279,6 +283,7 @@ public interface IBMDeveloperCloudAsyncClient {
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage/{volumeId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage/{volumeId}")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class) @ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> getVolume(@PathParam("volumeId") String id); ListenableFuture<Volume> getVolume(@PathParam("volumeId") String id);
@ -314,6 +319,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressesFromJson.class) @ResponseParser(ParseAddressesFromJson.class)
ListenableFuture<Set<? extends Address>> listAddresses(); ListenableFuture<Set<? extends Address>> listAddresses();
@ -322,6 +328,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@POST @POST
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressFromJson.class) @ResponseParser(ParseAddressFromJson.class)
ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId); ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId);

View File

@ -41,36 +41,32 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibmdev.domain.Address;
import com.google.gson.Gson; import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseAddressFromJson extends ParseJson<Address> { public class ParseAddressFromJson implements Function<HttpResponse, Address> {
private final ParseJson<Address> json;
@Inject @Inject
public ParseAddressFromJson(Gson gson) { ParseAddressFromJson(ParseJson<Address> json) {
super(gson); this.json = json;
} }
@Override @Override
protected Address apply(InputStream stream) { public Address apply(HttpResponse arg0) {
try { Address input = json.apply(arg0);
Address returnVal = gson.fromJson(new InputStreamReader(stream, "UTF-8"), Address.class); ParseUtils.CLEAN_ADDRESS.apply(input);
ParseUtils.CLEAN_ADDRESS.apply(returnVal); return input;
return returnVal;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -41,28 +41,30 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibmdev.domain.Address;
import com.google.common.base.Function;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.gson.Gson;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseAddressesFromJson extends ParseJson<Set<? extends Address>> { public class ParseAddressesFromJson implements
Function<HttpResponse, Set<? extends Address>> {
private final ParseJson<AddressListResponse> json;
@Inject @Inject
public ParseAddressesFromJson(Gson gson) { ParseAddressesFromJson(ParseJson<AddressListResponse> json) {
super(gson); this.json = json;
} }
private static class AddressListResponse { private static class AddressListResponse {
@ -70,12 +72,8 @@ public class ParseAddressesFromJson extends ParseJson<Set<? extends Address>> {
} }
@Override @Override
protected Set<? extends Address> apply(InputStream stream) { public Set<? extends Address> apply(HttpResponse arg0) {
try { return ParseUtils.clean(json.apply(arg0).addresses,
return ParseUtils.clean(gson.fromJson(new InputStreamReader(stream, "UTF-8"), ParseUtils.CLEAN_ADDRESS);
AddressListResponse.class).addresses, ParseUtils.CLEAN_ADDRESS);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -18,26 +18,28 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Date; import java.util.Date;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import com.google.gson.Gson; import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseExpirationTimeFromJson extends ParseJson<Date> { public class ParseExpirationTimeFromJson implements
Function<HttpResponse, Date> {
private final ParseJson<ExpirationTimeResponse> json;
@Inject @Inject
public ParseExpirationTimeFromJson(Gson gson) { ParseExpirationTimeFromJson(ParseJson<ExpirationTimeResponse> json) {
super(gson); this.json = json;
} }
private static class ExpirationTimeResponse { private static class ExpirationTimeResponse {
@ -45,11 +47,7 @@ public class ParseExpirationTimeFromJson extends ParseJson<Date> {
} }
@Override @Override
protected Date apply(InputStream stream) { public Date apply(HttpResponse arg0) {
try { return json.apply(arg0).expirationTime;
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), ExpirationTimeResponse.class).expirationTime;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -41,36 +41,32 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import com.google.gson.Gson; import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseImageFromJson extends ParseJson<Image> { public class ParseImageFromJson implements Function<HttpResponse, Image> {
private final ParseJson<Image> json;
@Inject @Inject
public ParseImageFromJson(Gson gson) { ParseImageFromJson(ParseJson<Image> json) {
super(gson); this.json = json;
} }
@Override @Override
protected Image apply(InputStream stream) { public Image apply(HttpResponse arg0) {
try { Image input = json.apply(arg0);
Image returnVal = gson.fromJson(new InputStreamReader(stream, "UTF-8"), Image.class); ParseUtils.CLEAN_IMAGE.apply(input);
ParseUtils.CLEAN_IMAGE.apply(returnVal); return input;
return returnVal;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -41,28 +41,30 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import com.google.common.base.Function;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.gson.Gson;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseImagesFromJson extends ParseJson<Set<? extends Image>> { public class ParseImagesFromJson implements
Function<HttpResponse, Set<? extends Image>> {
private final ParseJson<ImageListResponse> json;
@Inject @Inject
public ParseImagesFromJson(Gson gson) { ParseImagesFromJson(ParseJson<ImageListResponse> json) {
super(gson); this.json = json;
} }
private static class ImageListResponse { private static class ImageListResponse {
@ -70,12 +72,7 @@ public class ParseImagesFromJson extends ParseJson<Set<? extends Image>> {
} }
@Override @Override
protected Set<? extends Image> apply(InputStream stream) { public Set<? extends Image> apply(HttpResponse arg0) {
try { return ParseUtils.clean(json.apply(arg0).images, ParseUtils.CLEAN_IMAGE);
return ParseUtils.clean(gson.fromJson(new InputStreamReader(stream, "UTF-8"),
ImageListResponse.class).images, ParseUtils.CLEAN_IMAGE);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -41,36 +41,32 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import com.google.gson.Gson; import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseInstanceFromJson extends ParseJson<Instance> { public class ParseInstanceFromJson implements Function<HttpResponse, Instance> {
private final ParseJson<Instance> json;
@Inject @Inject
public ParseInstanceFromJson(Gson gson) { ParseInstanceFromJson(ParseJson<Instance> json) {
super(gson); this.json = json;
} }
@Override @Override
protected Instance apply(InputStream stream) { public Instance apply(HttpResponse arg0) {
try { Instance input = json.apply(arg0);
Instance returnVal = gson.fromJson(new InputStreamReader(stream, "UTF-8"), Instance.class); ParseUtils.CLEAN_INSTANCE.apply(input);
ParseUtils.CLEAN_INSTANCE.apply(returnVal); return input;
return returnVal;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -41,28 +41,30 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import com.google.common.base.Function;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.gson.Gson;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseInstancesFromJson extends ParseJson<Set<? extends Instance>> { public class ParseInstancesFromJson implements
Function<HttpResponse, Set<? extends Instance>> {
private final ParseJson<InstanceListResponse> json;
@Inject @Inject
public ParseInstancesFromJson(Gson gson) { ParseInstancesFromJson(ParseJson<InstanceListResponse> json) {
super(gson); this.json = json;
} }
private static class InstanceListResponse { private static class InstanceListResponse {
@ -70,12 +72,8 @@ public class ParseInstancesFromJson extends ParseJson<Set<? extends Instance>> {
} }
@Override @Override
protected Set<? extends Instance> apply(InputStream stream) { public Set<? extends Instance> apply(HttpResponse arg0) {
try { return ParseUtils.clean(json.apply(arg0).instances,
return ParseUtils.clean(gson.fromJson(new InputStreamReader(stream, "UTF-8"), ParseUtils.CLEAN_INSTANCE);
InstanceListResponse.class).instances, ParseUtils.CLEAN_INSTANCE);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -1,74 +0,0 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Key;
import com.google.gson.Gson;
/**
* @author Adrian Cole
*/
@Singleton
public class ParseKeyFromJson extends ParseJson<Key> {
@Inject
public ParseKeyFromJson(Gson gson) {
super(gson);
}
@Override
protected Key apply(InputStream stream) {
try {
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), Key.class);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
}
}

View File

@ -41,28 +41,30 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibmdev.domain.Key;
import com.google.common.base.Function;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.gson.Gson;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseKeysFromJson extends ParseJson<Set<? extends Key>> { public class ParseKeysFromJson implements
Function<HttpResponse, Set<? extends Key>> {
private final ParseJson<KeyListResponse> json;
@Inject @Inject
public ParseKeysFromJson(Gson gson) { ParseKeysFromJson(ParseJson<KeyListResponse> json) {
super(gson); this.json = json;
} }
private static class KeyListResponse { private static class KeyListResponse {
@ -70,11 +72,7 @@ public class ParseKeysFromJson extends ParseJson<Set<? extends Key>> {
} }
@Override @Override
protected Set<? extends Key> apply(InputStream stream) { public Set<? extends Key> apply(HttpResponse arg0) {
try { return json.apply(arg0).keys;
return gson.fromJson(new InputStreamReader(stream, "UTF-8"), KeyListResponse.class).keys;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -18,36 +18,32 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibmdev.domain.Volume;
import com.google.gson.Gson; import com.google.common.base.Function;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseVolumeFromJson extends ParseJson<Volume> { public class ParseVolumeFromJson implements Function<HttpResponse, Volume> {
private final ParseJson<Volume> json;
@Inject @Inject
public ParseVolumeFromJson(Gson gson) { ParseVolumeFromJson(ParseJson<Volume> json) {
super(gson); this.json = json;
} }
@Override @Override
protected Volume apply(InputStream stream) { public Volume apply(HttpResponse arg0) {
try { Volume input = json.apply(arg0);
Volume returnVal = gson.fromJson(new InputStreamReader(stream, "UTF-8"), Volume.class); ParseUtils.CLEAN_VOLUME.apply(input);
ParseUtils.CLEAN_VOLUME.apply(returnVal); return input;
return returnVal;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -18,28 +18,30 @@
*/ */
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Set; import java.util.Set;
import javax.inject.Inject; import javax.inject.Inject;
import javax.inject.Singleton; import javax.inject.Singleton;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibmdev.domain.Volume;
import com.google.common.base.Function;
import com.google.common.collect.Sets; import com.google.common.collect.Sets;
import com.google.gson.Gson;
/** /**
* @author Adrian Cole * @author Adrian Cole
*/ */
@Singleton @Singleton
public class ParseVolumesFromJson extends ParseJson<Set<? extends Volume>> { public class ParseVolumesFromJson implements
Function<HttpResponse, Set<? extends Volume>> {
private final ParseJson<VolumeListResponse> json;
@Inject @Inject
public ParseVolumesFromJson(Gson gson) { ParseVolumesFromJson(ParseJson<VolumeListResponse> json) {
super(gson); this.json = json;
} }
private static class VolumeListResponse { private static class VolumeListResponse {
@ -47,12 +49,8 @@ public class ParseVolumesFromJson extends ParseJson<Set<? extends Volume>> {
} }
@Override @Override
protected Set<? extends Volume> apply(InputStream stream) { public Set<? extends Volume> apply(HttpResponse arg0) {
try { return ParseUtils
return ParseUtils.clean(gson.fromJson(new InputStreamReader(stream, "UTF-8"), .clean(json.apply(arg0).volumes, ParseUtils.CLEAN_VOLUME);
VolumeListResponse.class).volumes, ParseUtils.CLEAN_VOLUME);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("jclouds requires UTF-8 encoding", e);
}
} }
} }

View File

@ -32,6 +32,7 @@ import java.util.Properties;
import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpRequest;
import org.jclouds.http.filters.BasicAuthentication; import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
@ -43,7 +44,6 @@ import org.jclouds.ibmdev.functions.ParseImageFromJson;
import org.jclouds.ibmdev.functions.ParseImagesFromJson; import org.jclouds.ibmdev.functions.ParseImagesFromJson;
import org.jclouds.ibmdev.functions.ParseInstanceFromJson; import org.jclouds.ibmdev.functions.ParseInstanceFromJson;
import org.jclouds.ibmdev.functions.ParseInstancesFromJson; import org.jclouds.ibmdev.functions.ParseInstancesFromJson;
import org.jclouds.ibmdev.functions.ParseKeyFromJson;
import org.jclouds.ibmdev.functions.ParseKeysFromJson; import org.jclouds.ibmdev.functions.ParseKeysFromJson;
import org.jclouds.ibmdev.functions.ParseVolumeFromJson; import org.jclouds.ibmdev.functions.ParseVolumeFromJson;
import org.jclouds.ibmdev.functions.ParseVolumesFromJson; import org.jclouds.ibmdev.functions.ParseVolumesFromJson;
@ -74,8 +74,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListImages() throws SecurityException, NoSuchMethodException, IOException { public void testListImages() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listImages"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listImages");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1");
@ -88,7 +87,8 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1");
// for example, using basic authentication, we should get "only one" header // for example, using basic authentication, we should get "only one"
// header
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest,
"Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n"); "Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -103,8 +103,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGetImage() throws SecurityException, NoSuchMethodException, IOException { public void testGetImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getImage", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getImage", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1");
@ -121,12 +120,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testDeleteImage() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteImage", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteImage", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -137,18 +135,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testSetImageVisibility() throws SecurityException, NoSuchMethodException, public void testSetImageVisibility() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("setImageVisibility", String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("setImageVisibility", Image.Visibility.class);
String.class, Image.Visibility.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( Image.Visibility.PUBLIC);
method, "1", Image.Visibility.PUBLIC);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false);
false);
assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -160,8 +156,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListInstances() throws SecurityException, NoSuchMethodException, IOException { public void testListInstances() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstances"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstances");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1");
@ -176,12 +171,9 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListInstancesFromRequest() throws SecurityException, NoSuchMethodException, public void testListInstancesFromRequest() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstancesFromRequest", String.class);
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listInstancesFromRequest", GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/requests/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/requests/1 HTTP/1.1");
@ -198,8 +190,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGetInstance() throws SecurityException, NoSuchMethodException, IOException { public void testGetInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getInstance", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getInstance", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
@ -214,17 +205,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testExtendReservationForInstance() throws SecurityException, NoSuchMethodException, public void testExtendReservationForInstance() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("extendReservationForInstance", String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("extendReservationForInstance", Date.class);
String.class, Date.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1", new Date(
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( 123215235l));
method, "1", new Date(123215235l));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseExpirationTimeFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseExpirationTimeFromJson.class);
@ -237,13 +226,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testRestartInstance() throws SecurityException, NoSuchMethodException, IOException { public void testRestartInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class, Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class); RestartInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -253,17 +240,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testRestartInstanceNewKey() throws SecurityException, NoSuchMethodException, public void testRestartInstanceNewKey() throws SecurityException, NoSuchMethodException, IOException {
IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class, Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class); RestartInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
method, "1", new RestartInstanceOptions().authorizePublicKey("keyName")); new RestartInstanceOptions().authorizePublicKey("keyName"));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -273,18 +258,17 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
checkFilters(httpRequest); checkFilters(httpRequest);
} }
public void testSaveInstanceToImage() throws SecurityException, NoSuchMethodException, public void testSaveInstanceToImage() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("saveInstanceToImage", String.class, String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("saveInstanceToImage", String.class);
String.class, String.class, String.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( "imageName", "imageDescription");
method, "1", "imageName", "imageDescription");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
"Accept: application/json\n"); assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName",
assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName", "application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseImageFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -295,12 +279,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testDeleteInstance() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteInstance", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteInstance", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -313,8 +296,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListKeys() throws SecurityException, NoSuchMethodException, IOException { public void testListKeys() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listKeys"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listKeys");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1");
@ -331,15 +313,14 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGetKey() throws SecurityException, NoSuchMethodException, IOException { public void testGetKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getKey", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getKey", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeyFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
@ -349,16 +330,14 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGenerateKeyPair() throws SecurityException, NoSuchMethodException, IOException { public void testGenerateKeyPair() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("generateKeyPair", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("generateKeyPair", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key");
method, "key");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseKeyFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null); assertExceptionParserClassEquals(method, null);
@ -367,15 +346,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testAddPublicKey() throws SecurityException, NoSuchMethodException, IOException { public void testAddPublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("addPublicKey", String.class, Method method = IBMDeveloperCloudAsyncClient.class.getMethod("addPublicKey", String.class, String.class);
String.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key",
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( "publicbits");
method, "key", "publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -387,15 +364,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testUpdatePublicKey() throws SecurityException, NoSuchMethodException, IOException { public void testUpdatePublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("updatePublicKey", String.class, Method method = IBMDeveloperCloudAsyncClient.class.getMethod("updatePublicKey", String.class, String.class);
String.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key",
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( "publicbits");
method, "key", "publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -406,17 +381,14 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testSetDefaultStatusOfKey() throws SecurityException, NoSuchMethodException, public void testSetDefaultStatusOfKey() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("setDefaultStatusOfKey", .getMethod("setDefaultStatusOfKey", String.class, boolean.class);
String.class, boolean.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key", true);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(
method, "key", true);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1"); "PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest, "");
"Accept: application/json\n");
assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -429,12 +401,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testDeleteKey() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteKey", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteKey", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1"); "DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -447,8 +418,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException { public void testListVolumes() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listVolumes"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listVolumes");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1");
@ -465,8 +435,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException { public void testGetVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getVolume", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getVolume", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1");
@ -481,12 +450,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class, String.class, String.class);
String.class, String.class, String.class, String.class); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location",
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( "name", "format", "size");
method, "location", "name", "format", "size");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1"); "POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1");
@ -502,13 +470,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateInstanceInLocation() throws SecurityException, NoSuchMethodException, public void testCreateInstanceInLocation() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, String.class, String.class, CreateInstanceOptions[].class);
String.class, String.class, String.class, String.class, GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1", "name",
CreateInstanceOptions[].class); "22", "instanceType");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(
method, "1", "name", "22", "instanceType");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1"); "POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1");
@ -523,17 +489,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testCreateInstanceInLocationWithOptions() throws SecurityException, public void testCreateInstanceInLocationWithOptions() throws SecurityException, NoSuchMethodException, IOException {
NoSuchMethodException, IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class,
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class, String.class, String.class, CreateInstanceOptions[].class);
String.class, String.class, String.class, String.class, GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location",
CreateInstanceOptions[].class); "name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO")
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( .mountVolume("2", "/mnt").configurationData(
method, "location", "name", "22", "instanceType", new CreateInstanceOptions() ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", "myPassword2",
.attachIp("1").authorizePublicKey("MOO").mountVolume("2", "/mnt")
.configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1",
"db2_admin_password", "myPassword2",
"report_user_password", "myPassword3"))); "report_user_password", "myPassword3")));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
@ -554,12 +516,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException { public void testDeleteVolume() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteVolume", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("deleteVolume", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1"); "DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -572,8 +533,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListLocations() throws SecurityException, NoSuchMethodException, IOException { public void testListLocations() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listLocations"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listLocations");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations HTTP/1.1");
@ -590,8 +550,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testGetLocation() throws SecurityException, NoSuchMethodException, IOException { public void testGetLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getLocation", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("getLocation", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations/1 HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations/1 HTTP/1.1");
@ -608,8 +567,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testListAddresses() throws SecurityException, NoSuchMethodException, IOException { public void testListAddresses() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listAddresses"); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listAddresses");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1"); "GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1");
@ -624,12 +582,9 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, IOException {
IOException { Method method = IBMDeveloperCloudAsyncClient.class.getMethod("allocateAddressInLocation", String.class);
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("allocateAddressInLocation", GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1"); "POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1");
@ -646,12 +601,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException { public void testReleaseAddress() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("releaseAddress", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("releaseAddress", String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest( GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses/1 HTTP/1.1"); "DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class); assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
@ -676,7 +630,6 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
@Override @Override
public ContextSpec<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> createContextSpec() { public ContextSpec<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> createContextSpec() {
return new RestContextFactory().createContextSpec("ibmdev", "identity", "credential", return new RestContextFactory().createContextSpec("ibmdev", "identity", "credential", new Properties());
new Properties());
} }
} }

View File

@ -23,6 +23,8 @@ import static org.testng.Assert.assertEquals;
import java.io.IOException; import java.io.IOException;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibmdev.domain.Address;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
@ -55,8 +57,9 @@ public class ParseAddressFromJsonTest {
public void test() { public void test() {
Address address = new Address(2, "1", "129.33.196.243", "1217", "1"); Address address = new Address(2, "1", "129.33.196.243", "1217", "1");
Address compare = handler.apply(ParseAddressFromJsonTest.class Address compare = handler.apply(new HttpResponse(200, "ok", Payloads
.getResourceAsStream("/address.json")); .newInputStreamPayload(ParseAddressFromJsonTest.class
.getResourceAsStream("/address.json"))));
assertEquals(compare, address); assertEquals(compare, address);
} }
} }

View File

@ -24,8 +24,9 @@ import static org.testng.Assert.assertEquals;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.util.Utils;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -55,7 +56,8 @@ public class ParseExpirationTimeFromJsonTest {
} }
public void test() { public void test() {
Date compare = handler.apply(Utils.toInputStream("{ \"expirationTime\":1249876800000 }")); Date compare = handler.apply(new HttpResponse(200, "ok", Payloads
.newStringPayload("{ \"expirationTime\":1249876800000 }")));
assertEquals(compare, new Date(1249876800000l)); assertEquals(compare, new Date(1249876800000l));
} }
} }

View File

@ -24,7 +24,9 @@ import static org.testng.Assert.assertEquals;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule; import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
@ -76,8 +78,9 @@ public class ParseImageFromJsonTest {
image image
.setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle."); .setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle.");
Image compare = handler.apply(ParseImageFromJsonTest.class Image compare = handler.apply(new HttpResponse(200, "ok", Payloads
.getResourceAsStream("/image.json")); .newInputStreamPayload(ParseImageFromJsonTest.class
.getResourceAsStream("/image.json"))));
assertEquals(compare, image); assertEquals(compare, image);
} }
} }

View File

@ -23,7 +23,9 @@ import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.HttpUtils; import org.jclouds.http.HttpUtils;
import org.jclouds.http.Payloads;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule; import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
@ -65,8 +67,10 @@ public class ParseImagesFromJsonTest {
image1.setPlatform("SUSE Linux Enterprise/10 SP2"); image1.setPlatform("SUSE Linux Enterprise/10 SP2");
image1.setCreatedTime(new Date(1240632000000l)); image1.setCreatedTime(new Date(1240632000000l));
image1.setLocation("1"); image1.setLocation("1");
image1.setSupportedInstanceTypes(ImmutableSet.of("SMALL", "MEDIUM", "LARGE")); image1.setSupportedInstanceTypes(ImmutableSet.of("SMALL", "MEDIUM",
image1.setProductCodes(ImmutableSet.of("fd2d0478b132490897526b9b4433a334")); "LARGE"));
image1.setProductCodes(ImmutableSet
.of("fd2d0478b132490897526b9b4433a334"));
image1 image1
.setDocumentation(HttpUtils .setDocumentation(HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/GettingStarted.html")); .createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/GettingStarted.html"));
@ -95,8 +99,9 @@ public class ParseImagesFromJsonTest {
image2 image2
.setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle."); .setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle.");
Set<? extends Image> compare = handler.apply(ParseImagesFromJsonTest.class Set<? extends Image> compare = handler.apply(new HttpResponse(200, "ok",
.getResourceAsStream("/images.json")); Payloads.newInputStreamPayload(ParseImagesFromJsonTest.class
.getResourceAsStream("/images.json"))));
assert (compare.contains(image1)); assert (compare.contains(image1));
assert (compare.contains(image2)); assert (compare.contains(image2));
} }

Some files were not shown because too many files have changed in this diff Show More