normalized all list operations to Set<Thing> and on 404 they return an empty list

This commit is contained in:
Adrian Cole 2010-07-17 19:46:43 -07:00
parent 7d27e70d59
commit cd5fddf1f4
59 changed files with 996 additions and 1121 deletions

View File

@ -56,8 +56,7 @@ public class AWSFormSigningRestClientModule<S, A> extends AWSRestClientModule<S,
@TimeStamp
protected String provideTimeStamp(final DateService dateService,
@Named(Constants.PROPERTY_SESSION_INTERVAL) final int expiration) {
return dateService.iso8601DateFormat(new Date(System.currentTimeMillis()
+ (expiration * 1000)));
return dateService.iso8601DateFormat(new Date(System.currentTimeMillis() + (expiration * 1000)));
}
@Provides

View File

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

View File

@ -20,7 +20,7 @@ package org.jclouds.aws.s3;
import static org.jclouds.blobstore.attr.BlobScopes.CONTAINER;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.annotation.Nullable;
@ -242,7 +242,7 @@ public interface S3AsyncClient {
@XMLResponseParser(ListAllMyBucketsHandler.class)
@Path("/")
@VirtualHost
ListenableFuture<? extends SortedSet<BucketMetadata>> listOwnedBuckets();
ListenableFuture<? extends Set<BucketMetadata>> listOwnedBuckets();
/**
* @see S3Client#copyObject

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.aws.s3;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@ -250,7 +250,7 @@ public interface S3Client {
* />
*
*/
SortedSet<BucketMetadata> listOwnedBuckets();
Set<BucketMetadata> listOwnedBuckets();
/**
* Copies one object to another bucket, retaining UserMetadata from the source. The destination

View File

@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.util.concurrent.Futures.compose;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ExecutorService;
import javax.inject.Inject;
@ -113,9 +112,9 @@ public class S3AsyncBlobStore extends BaseAsyncBlobStore {
public ListenableFuture<? extends PageSet<? extends StorageMetadata>> list() {
return compose(
async.listOwnedBuckets(),
new Function<SortedSet<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
new Function<Set<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(
SortedSet<BucketMetadata> from) {
Set<BucketMetadata> from) {
return new PageSetImpl<StorageMetadata>(Iterables.transform(from,
bucket2ResourceMd), null);
}

View File

@ -21,7 +21,6 @@ package org.jclouds.aws.s3.blobstore;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Set;
import java.util.SortedSet;
import javax.inject.Inject;
import javax.inject.Provider;
@ -101,9 +100,9 @@ public class S3BlobStore extends BaseBlobStore {
*/
@Override
public PageSet<? extends StorageMetadata> list() {
return new Function<SortedSet<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
return new Function<Set<BucketMetadata>, org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata>>() {
public org.jclouds.blobstore.domain.PageSet<? extends StorageMetadata> apply(
SortedSet<BucketMetadata> from) {
Set<BucketMetadata> from) {
return new PageSetImpl<StorageMetadata>(Iterables.transform(from, bucket2ResourceMd),
null);
}

View File

@ -61,18 +61,18 @@ public class S3RestClientModule extends AWSRestClientModule<S3Client, S3AsyncCli
super.configure();
}
@Provides
@TimeStamp
protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {
return cache.get();
}
@Provides
@Singleton
protected RequestSigner provideRequestSigner(RequestAuthorizeSignature in) {
return in;
}
@Provides
@TimeStamp
protected String provideTimeStamp(@TimeStamp Supplier<String> cache) {
return cache.get();
}
/**
* borrowing concurrency code to ensure that caching takes place properly
*/

View File

@ -23,7 +23,6 @@ import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import com.google.common.annotations.VisibleForTesting;
@ -67,7 +66,7 @@ public class AccessControlList {
* @return an unmodifiable set of grantees who have been assigned permissions in this ACL.
*/
public Set<Grantee> getGrantees() {
SortedSet<Grantee> grantees = new TreeSet<Grantee>();
Set<Grantee> grantees = new TreeSet<Grantee>();
for (Grant grant : getGrants()) {
grantees.add(grant.getGrantee());
}

View File

@ -19,7 +19,7 @@
package org.jclouds.aws.s3.xml;
import java.util.Date;
import java.util.SortedSet;
import java.util.Set;
import javax.inject.Inject;
@ -33,16 +33,16 @@ import com.google.common.collect.Sets;
/**
* Parses the following XML document:
* <p/>
* SortedSetAllMyBucketsResult xmlns="http://doc.s3.amazonaws.com/2006-03-01"
* SetAllMyBucketsResult xmlns="http://doc.s3.amazonaws.com/2006-03-01"
*
* @see <a
* href="http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTServiceGET.html"
* />
* @author Adrian Cole
*/
public class ListAllMyBucketsHandler extends ParseSax.HandlerWithResult<SortedSet<BucketMetadata>> {
public class ListAllMyBucketsHandler extends ParseSax.HandlerWithResult<Set<BucketMetadata>> {
private SortedSet<BucketMetadata> buckets = Sets.newTreeSet();
private Set<BucketMetadata> buckets = Sets.newLinkedHashSet();
private CanonicalUser currentOwner;
private StringBuilder currentText = new StringBuilder();
@ -55,7 +55,7 @@ public class ListAllMyBucketsHandler extends ParseSax.HandlerWithResult<SortedSe
this.dateParser = dateParser;
}
public SortedSet<BucketMetadata> getResult() {
public Set<BucketMetadata> getResult() {
return buckets;
}

View File

@ -19,7 +19,7 @@
package org.jclouds.aws.s3.xml;
import java.util.Date;
import java.util.SortedSet;
import java.util.Set;
import javax.inject.Inject;
@ -48,8 +48,8 @@ import com.google.common.collect.Sets;
* />
*/
public class ListBucketHandler extends ParseSax.HandlerWithResult<ListBucketResponse> {
private SortedSet<ObjectMetadata> contents;
private SortedSet<String> commonPrefixes;
private Set<ObjectMetadata> contents;
private Set<String> commonPrefixes;
private CanonicalUser currentOwner;
private StringBuilder currentText = new StringBuilder();
@ -67,8 +67,8 @@ public class ListBucketHandler extends ParseSax.HandlerWithResult<ListBucketResp
public ListBucketHandler(DateService dateParser, EncryptionService encryptionService) {
this.dateParser = dateParser;
this.encryptionService = encryptionService;
this.contents = Sets.newTreeSet();
this.commonPrefixes = Sets.newTreeSet();
this.contents = Sets.newLinkedHashSet();
this.commonPrefixes = Sets.newLinkedHashSet();
}
public ListBucketResponse getResult() {

View File

@ -38,6 +38,12 @@ public class ParseAWSErrorFromXmlContentTest {
"<Error><Code>Monster.NotFound</Code></Error>", ResourceNotFoundException.class);
}
@Test
public void test400WithUnknownSetsResourceNotFoundException() {
assertCodeMakes("GET", URI.create("https://amazonaws.com/foo"), 400, "",
"<Error><Code>InvalidPlacementGroup.Unknown</Code></Error>", ResourceNotFoundException.class);
}
@Test
public void test400WithIncorrectStateSetsIllegalStateException() {
assertCodeMakes("GET", URI.create("https://amazonaws.com/foo"), 400, "",
@ -50,24 +56,23 @@ public class ParseAWSErrorFromXmlContentTest {
"<Error><Code>AuthFailure</Code></Error>", AuthorizationException.class);
}
private void assertCodeMakes(String method, URI uri, int statusCode, String message,
String content, Class<? extends Exception> expected) {
private void assertCodeMakes(String method, URI uri, int statusCode, String message, String content,
Class<? extends Exception> expected) {
ParseAWSErrorFromXmlContent function = Guice.createInjector(new ParserModule(),
new AbstractModule() {
ParseAWSErrorFromXmlContent function = Guice.createInjector(new ParserModule(), new AbstractModule() {
@Override
protected void configure() {
bind(RequestSigner.class).toInstance(createMock(RequestSigner.class));
bindConstant().annotatedWith(Names.named(PROPERTY_HEADER_TAG)).to("amz");
}
@Override
protected void configure() {
bind(RequestSigner.class).toInstance(createMock(RequestSigner.class));
bindConstant().annotatedWith(Names.named(PROPERTY_HEADER_TAG)).to("amz");
}
}).getInstance(ParseAWSErrorFromXmlContent.class);
}).getInstance(ParseAWSErrorFromXmlContent.class);
HttpCommand command = createMock(HttpCommand.class);
HttpRequest request = new HttpRequest(method, uri);
HttpResponse response = new HttpResponse(statusCode, message, Payloads
.newInputStreamPayload(Utils.toInputStream(content)));
HttpResponse response = new HttpResponse(statusCode, message, Payloads.newInputStreamPayload(Utils
.toInputStream(content)));
expect(command.getRequest()).andReturn(request).atLeastOnce();
command.setException(classEq(expected));

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.aws.s3.blobstore.functions;
import java.util.SortedSet;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
@ -67,7 +67,7 @@ public class ResourceToBucketList implements
});
SortedSet<String> commonPrefixes = Sets.newTreeSet(Iterables.transform(Iterables.filter(list,
Set<String> commonPrefixes = Sets.newLinkedHashSet(Iterables.transform(Iterables.filter(list,
new Predicate<StorageMetadata>() {
public boolean apply(StorageMetadata input) {

View File

@ -25,7 +25,7 @@ import static com.google.common.util.concurrent.Futures.immediateFuture;
import java.util.Date;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
@ -302,8 +302,8 @@ public class StubS3AsyncClient implements S3AsyncClient {
});
}
public ListenableFuture<? extends SortedSet<BucketMetadata>> listOwnedBuckets() {
return immediateFuture(Sets.newTreeSet(Iterables.transform(containerToBlobs.keySet(),
public ListenableFuture<? extends Set<BucketMetadata>> listOwnedBuckets() {
return immediateFuture(Sets.newLinkedHashSet(Iterables.transform(containerToBlobs.keySet(),
new Function<String, BucketMetadata>() {
public BucketMetadata apply(String name) {
return new BucketMetadata(name, null, null);

View File

@ -31,7 +31,7 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Date;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -56,6 +56,7 @@ import org.testng.annotations.Test;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/**
*
@ -87,8 +88,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
}
public void testPrivateAclIsDefaultForBucket() throws InterruptedException, ExecutionException,
TimeoutException, IOException {
public void testPrivateAclIsDefaultForBucket() throws InterruptedException, ExecutionException, TimeoutException,
IOException {
String bucketName = getContainerName();
try {
AccessControlList acl = getApi().getBucketACL(bucketName);
@ -102,8 +103,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
public void testUpdateBucketACL() throws InterruptedException, ExecutionException,
TimeoutException, IOException, Exception {
public void testUpdateBucketACL() throws InterruptedException, ExecutionException, TimeoutException, IOException,
Exception {
String bucketName = getContainerName();
try {
// Confirm the bucket is private
@ -134,24 +135,20 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());
assertTrue(acl.hasPermission(ownerId, Permission.WRITE_ACP), acl.toString());
// EmailAddressGrantee is replaced by a CanonicalUserGrantee, so we cannot test by email addr
assertTrue(acl.hasPermission(StubS3AsyncClient.TEST_ACL_ID, Permission.READ_ACP), acl
.toString());
assertTrue(acl.hasPermission(StubS3AsyncClient.TEST_ACL_ID, Permission.READ_ACP), acl.toString());
}
private void addGrantsToACL(AccessControlList acl) {
String ownerId = acl.getOwner().getId();
acl.addPermission(GroupGranteeURI.ALL_USERS, Permission.READ);
acl.addPermission(new EmailAddressGrantee(StubS3AsyncClient.TEST_ACL_EMAIL),
Permission.READ_ACP);
acl.addPermission(new EmailAddressGrantee(StubS3AsyncClient.TEST_ACL_EMAIL), Permission.READ_ACP);
acl.addPermission(new CanonicalUserGrantee(ownerId), Permission.WRITE_ACP);
}
public void testPublicReadAccessPolicy() throws Exception {
String bucketName = getScratchContainerName();
try {
getApi()
.putBucketInRegion(null, bucketName,
withBucketAcl(CannedAccessPolicy.PUBLIC_READ));
getApi().putBucketInRegion(null, bucketName, withBucketAcl(CannedAccessPolicy.PUBLIC_READ));
AccessControlList acl = getApi().getBucketACL(bucketName);
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());
// TODO: I believe that the following should work based on the above acl assertion passing.
@ -180,8 +177,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
String bucketName = getContainerName();
try {
String location = getApi().getBucketLocation(bucketName);
assert location.equals(Region.US_STANDARD) : "bucket: " + bucketName + " location: "
+ location;
assert location.equals(Region.US_STANDARD) : "bucket: " + bucketName + " location: " + location;
} finally {
returnContainer(bucketName);
}
@ -242,8 +238,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
// EmailAddressGrantee is replaced by a CanonicalUserGrantee, so we cannot test by
// email addr
assertTrue(acl.hasPermission(StubS3AsyncClient.TEST_ACL_ID,
Permission.FULL_CONTROL), acl.toString());
assertTrue(acl.hasPermission(StubS3AsyncClient.TEST_ACL_ID, Permission.FULL_CONTROL), acl.toString());
assertEquals(logging.getTargetBucket(), newLogging.getTargetBucket());
assertEquals(logging.getTargetPrefix(), newLogging.getTargetPrefix());
} catch (Exception e) {
@ -281,14 +276,12 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
public void testEu() throws Exception {
final String bucketName = getScratchContainerName();
try {
getApi().putBucketInRegion(Region.EU_WEST_1, bucketName + "eu",
withBucketAcl(CannedAccessPolicy.PUBLIC_READ));
getApi().putBucketInRegion(Region.EU_WEST_1, bucketName + "eu", withBucketAcl(CannedAccessPolicy.PUBLIC_READ));
assertConsistencyAware(new Runnable() {
public void run() {
try {
AccessControlList acl = getApi().getBucketACL(bucketName + "eu");
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl
.toString());
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());
} catch (Exception e) {
Throwables.propagateIfPossible(e);
}
@ -316,8 +309,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
public void run() {
try {
AccessControlList acl = getApi().getBucketACL(bucketName + "cali");
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl
.toString());
assertTrue(acl.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ), acl.toString());
} catch (Exception e) {
Throwables.propagateIfPossible(e);
}
@ -336,8 +328,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
void bucketExists() throws Exception {
String bucketName = getContainerName();
try {
SortedSet<BucketMetadata> list = getApi().listOwnedBuckets();
BucketMetadata firstBucket = list.first();
Set<BucketMetadata> list = getApi().listOwnedBuckets();
BucketMetadata firstBucket = Iterables.get(list, 0);
BucketMetadata toMatch = new BucketMetadata(bucketName, new Date(), firstBucket.getOwner());
assert list.contains(toMatch);
} finally {
@ -354,8 +346,7 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
}
public void testListBucketMarker() throws InterruptedException, ExecutionException,
TimeoutException {
public void testListBucketMarker() throws InterruptedException, ExecutionException, TimeoutException {
String bucketName = getContainerName();
try {
addAlphabetUnderRoot(bucketName);
@ -368,8 +359,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
}
public void testListBucketDelimiter() throws InterruptedException, ExecutionException,
TimeoutException, UnsupportedEncodingException {
public void testListBucketDelimiter() throws InterruptedException, ExecutionException, TimeoutException,
UnsupportedEncodingException {
String bucketName = getContainerName();
try {
String prefix = "apps";
@ -386,8 +377,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
public void testListBucketPrefix() throws InterruptedException, ExecutionException,
TimeoutException, UnsupportedEncodingException {
public void testListBucketPrefix() throws InterruptedException, ExecutionException, TimeoutException,
UnsupportedEncodingException {
String bucketName = getContainerName();
try {
String prefix = "apps";
@ -404,8 +395,8 @@ public class BucketsLiveTest extends BaseBlobStoreIntegrationTest {
}
public void testListBucketMaxResults() throws InterruptedException, ExecutionException,
TimeoutException, UnsupportedEncodingException {
public void testListBucketMaxResults() throws InterruptedException, ExecutionException, TimeoutException,
UnsupportedEncodingException {
String bucketName = getContainerName();
try {
addAlphabetUnderRoot(bucketName);

View File

@ -23,7 +23,7 @@ import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
@ -45,6 +45,7 @@ import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.xml.sax.SAXException;
import com.google.common.collect.Iterables;
import com.google.inject.Guice;
import com.google.inject.Injector;
@ -79,20 +80,17 @@ public class S3ParserTest extends PerformanceTest {
runParseListAllMyBuckets();
}
private SortedSet<BucketMetadata> runParseListAllMyBuckets() throws HttpException {
return (SortedSet<BucketMetadata>) factory.create(
injector.getInstance(ListAllMyBucketsHandler.class)).parse(
private Set<BucketMetadata> runParseListAllMyBuckets() throws HttpException {
return factory.create(injector.getInstance(ListAllMyBucketsHandler.class)).parse(
Utils.toInputStream(listAllMyBucketsResultOn200));
}
@Test
void testParseListAllMyBucketsParallelResponseTime() throws InterruptedException,
ExecutionException {
CompletionService<SortedSet<BucketMetadata>> completer = new ExecutorCompletionService<SortedSet<BucketMetadata>>(
exec);
void testParseListAllMyBucketsParallelResponseTime() throws InterruptedException, ExecutionException {
CompletionService<Set<BucketMetadata>> completer = new ExecutorCompletionService<Set<BucketMetadata>>(exec);
for (int i = 0; i < LOOP_COUNT; i++)
completer.submit(new Callable<SortedSet<BucketMetadata>>() {
public SortedSet<BucketMetadata> call() throws IOException, SAXException, HttpException {
completer.submit(new Callable<Set<BucketMetadata>>() {
public Set<BucketMetadata> call() throws IOException, SAXException, HttpException {
return runParseListAllMyBuckets();
}
});
@ -102,8 +100,8 @@ public class S3ParserTest extends PerformanceTest {
@Test
public void testCanParseListAllMyBuckets() throws HttpException {
SortedSet<BucketMetadata> s3Buckets = runParseListAllMyBuckets();
BucketMetadata container1 = s3Buckets.first();
Set<BucketMetadata> s3Buckets = runParseListAllMyBuckets();
BucketMetadata container1 = Iterables.get(s3Buckets, 0);
assert container1.getName().equals("adrianjbosstest");
Date expectedDate1 = new SimpleDateFormatDateService().iso8601DateParse("2009-03-12T02:00:07.000Z");
Date date1 = container1.getCreationDate();
@ -114,8 +112,7 @@ public class S3ParserTest extends PerformanceTest {
Date date2 = container2.getCreationDate();
assert date2.equals(expectedDate2);
assert s3Buckets.size() == 2;
CanonicalUser owner = new CanonicalUser(
"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0");
CanonicalUser owner = new CanonicalUser("e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0");
assert container1.getOwner().equals(owner);
assert container2.getOwner().equals(owner);
}
@ -130,20 +127,19 @@ public class S3ParserTest extends PerformanceTest {
ObjectMetadata object = container.iterator().next();
assert object.getKey().equals("3366");
Date expected = new SimpleDateFormatDateService().iso8601DateParse("2009-03-12T02:00:13.000Z");
assert object.getLastModified().equals(expected) : String.format(
"expected %1$s, but got %1$s", expected, object.getLastModified());
assert object.getLastModified().equals(expected) : String.format("expected %1$s, but got %1$s", expected, object
.getLastModified());
assertEquals(object.getETag(), "\"9d7bb64e8e18ee34eec06dd2cf37b766\"");
assert object.getSize() == 136;
CanonicalUser owner = new CanonicalUser(
"e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0");
CanonicalUser owner = new CanonicalUser("e1a5f66a480ca99a4fdfe8e318c3020446c9989d7004e7778029fbcc5d990fa0");
owner.setDisplayName("ferncam");
assert object.getOwner().equals(owner);
assert object.getStorageClass().equals(StorageClass.STANDARD);
}
private ListBucketResponse runParseListContainerResult() throws HttpException {
return (ListBucketResponse) factory.create(injector.getInstance(ListBucketHandler.class))
.parse(Utils.toInputStream(listContainerResult));
return (ListBucketResponse) factory.create(injector.getInstance(ListBucketHandler.class)).parse(
Utils.toInputStream(listContainerResult));
}
public static final String successfulCopyObject200 = "<CopyObjectResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01/\"><LastModified>2009-03-19T13:23:27.000Z</LastModified><ETag>\"92836a3ea45a6984d1b4d23a747d46bb\"</ETag></CopyObjectResult>";
@ -155,8 +151,7 @@ public class S3ParserTest extends PerformanceTest {
public void testCanParseCopyObjectResult() throws HttpException, UnsupportedEncodingException {
ObjectMetadata metadata = runParseCopyObjectResult();
Date expected = new SimpleDateFormatDateService()
.iso8601DateParse("2009-03-19T13:23:27.000Z");
Date expected = new SimpleDateFormatDateService().iso8601DateParse("2009-03-19T13:23:27.000Z");
assertEquals(metadata.getLastModified(), expected);
assertEquals(metadata.getETag(), "\"92836a3ea45a6984d1b4d23a747d46bb\"");
}
@ -168,10 +163,8 @@ public class S3ParserTest extends PerformanceTest {
}
@Test
void testParseListContainerResultParallelResponseTime() throws InterruptedException,
ExecutionException {
CompletionService<ListBucketResponse> completer = new ExecutorCompletionService<ListBucketResponse>(
exec);
void testParseListContainerResultParallelResponseTime() throws InterruptedException, ExecutionException {
CompletionService<ListBucketResponse> completer = new ExecutorCompletionService<ListBucketResponse>(exec);
for (int i = 0; i < LOOP_COUNT; i++)
completer.submit(new Callable<ListBucketResponse>() {
public ListBucketResponse call() throws IOException, SAXException, HttpException {

View File

@ -62,10 +62,8 @@ public class SQSClientLiveTest {
@BeforeGroups(groups = { "live" })
public void setupClient() throws IOException {
String identity = checkNotNull(System.getProperty("jclouds.test.identity"),
"jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"),
"jclouds.test.credential");
String identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
context = new RestContextFactory().createContext("sqs", identity, credential, ImmutableSet
.<Module> of(new Log4JLoggingModule()));
@ -74,8 +72,8 @@ public class SQSClientLiveTest {
@Test
void testListQueuesInRegion() throws InterruptedException {
for (String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1,
Region.US_WEST_1, Region.AP_SOUTHEAST_1)) {
for (String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1, Region.US_WEST_1,
Region.AP_SOUTHEAST_1)) {
SortedSet<Queue> allResults = Sets.newTreeSet(client.listQueuesInRegion(region));
assertNotNull(allResults);
if (allResults.size() >= 1) {
@ -91,11 +89,10 @@ public class SQSClientLiveTest {
void testCreateQueue() throws InterruptedException {
String queueName = PREFIX + "1";
for (final String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1,
Region.US_WEST_1, Region.AP_SOUTHEAST_1)) {
for (final String region : Lists.newArrayList(null, Region.EU_WEST_1, Region.US_EAST_1, Region.US_WEST_1,
Region.AP_SOUTHEAST_1)) {
try {
SortedSet<Queue> result = Sets.newTreeSet(client.listQueuesInRegion(region,
queuePrefix(queueName)));
SortedSet<Queue> result = Sets.newTreeSet(client.listQueuesInRegion(region, queuePrefix(queueName)));
if (result.size() >= 1) {
client.deleteQueue(result.last());
queueName += 1;// cannot recreate a queue within 60 seconds
@ -139,8 +136,7 @@ public class SQSClientLiveTest {
final Queue finalQ = queue;
assertEventually(new Runnable() {
public void run() {
SortedSet<Queue> result = Sets.newTreeSet(client.listQueuesInRegion(region,
queuePrefix(finalQ.getName())));
SortedSet<Queue> result = Sets.newTreeSet(client.listQueuesInRegion(region, queuePrefix(finalQ.getName())));
assertNotNull(result);
assert result.size() >= 1 : result;
assertEquals(result.first(), finalQ);
@ -161,9 +157,8 @@ public class SQSClientLiveTest {
try {
assertion.run();
if (i > 0)
System.err.printf("%d attempts and %dms asserting %s%n", i + 1, System
.currentTimeMillis()
- start, assertion.getClass().getSimpleName());
System.err.printf("%d attempts and %dms asserting %s%n", i + 1, System.currentTimeMillis() - start,
assertion.getClass().getSimpleName());
return;
} catch (AssertionError e) {
error = e;

View File

@ -24,7 +24,7 @@ import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import org.jclouds.aws.s3.S3Client;
import org.jclouds.aws.s3.blobstore.S3AsyncBlobStore;
@ -72,11 +72,10 @@ public class JCloudsS3Service extends S3Service {
* URLFetchServiceClientModule
* @throws S3ServiceException
*/
protected JCloudsS3Service(AWSCredentials awsCredentials, Module... modules)
throws S3ServiceException {
protected JCloudsS3Service(AWSCredentials awsCredentials, Module... modules) throws S3ServiceException {
super(awsCredentials);
context = new BlobStoreContextFactory().createContext("s3", awsCredentials.getAccessKey(),
awsCredentials.getSecretKey(), ImmutableList.<Module> copyOf(modules));
context = new BlobStoreContextFactory().createContext("s3", awsCredentials.getAccessKey(), awsCredentials
.getSecretKey(), ImmutableList.<Module> copyOf(modules));
connection = (S3Client) context.getProviderSpecificContext().getApi();
}
@ -91,13 +90,12 @@ public class JCloudsS3Service extends S3Service {
*/
@SuppressWarnings("unchecked")
@Override
protected Map copyObjectImpl(String sourceBucketName, String sourceObjectKey,
String destinationBucketName, String destinationObjectKey, AccessControlList acl,
Map destinationMetadata, Calendar ifModifiedSince, Calendar ifUnmodifiedSince,
String[] ifMatchTags, String[] ifNoneMatchTags) throws S3ServiceException {
protected Map copyObjectImpl(String sourceBucketName, String sourceObjectKey, String destinationBucketName,
String destinationObjectKey, AccessControlList acl, Map destinationMetadata, Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags) throws S3ServiceException {
try {
CopyObjectOptions options = Util.convertCopyObjectOptions(acl, destinationMetadata,
ifModifiedSince, ifUnmodifiedSince, ifMatchTags, ifNoneMatchTags);
CopyObjectOptions options = Util.convertCopyObjectOptions(acl, destinationMetadata, ifModifiedSince,
ifUnmodifiedSince, ifMatchTags, ifNoneMatchTags);
ObjectMetadata jcObjectMetadata = connection.copyObject(sourceBucketName, sourceObjectKey,
destinationBucketName, destinationObjectKey, options);
@ -157,8 +155,7 @@ public class JCloudsS3Service extends S3Service {
connection.deleteObject(bucketName, objectKey);
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException(String.format("error deleting object: %1$s:%2$s", bucketName,
objectKey), e);
throw new S3ServiceException(String.format("error deleting object: %1$s:%2$s", bucketName, objectKey), e);
}
}
@ -180,18 +177,15 @@ public class JCloudsS3Service extends S3Service {
}
@Override
protected S3BucketLoggingStatus getBucketLoggingStatusImpl(String bucketName)
throws S3ServiceException {
protected S3BucketLoggingStatus getBucketLoggingStatusImpl(String bucketName) throws S3ServiceException {
// TODO Unimplemented
throw new UnsupportedOperationException();
}
@Override
protected AccessControlList getObjectAclImpl(String bucketName, String objectKey)
throws S3ServiceException {
protected AccessControlList getObjectAclImpl(String bucketName, String objectKey) throws S3ServiceException {
try {
org.jclouds.aws.s3.domain.AccessControlList jcACL = connection.getObjectACL(bucketName,
objectKey);
org.jclouds.aws.s3.domain.AccessControlList jcACL = connection.getObjectACL(bucketName, objectKey);
return Util.convertAccessControlList(jcACL);
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
@ -200,9 +194,8 @@ public class JCloudsS3Service extends S3Service {
}
@Override
protected S3Object getObjectDetailsImpl(String bucketName, String objectKey,
Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags,
String[] ifNoneMatchTags) throws S3ServiceException {
protected S3Object getObjectDetailsImpl(String bucketName, String objectKey, Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags) throws S3ServiceException {
try {
if (ifModifiedSince != null)
throw new IllegalArgumentException("ifModifiedSince");
@ -216,23 +209,22 @@ public class JCloudsS3Service extends S3Service {
return Util.convertObjectHead(connection.headObject(bucketName, objectKey));
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException(String.format("error retrieving object head: %1$s:%2$s",
bucketName, objectKey), e);
throw new S3ServiceException(String.format("error retrieving object head: %1$s:%2$s", bucketName, objectKey),
e);
}
}
@Override
protected S3Object getObjectImpl(String bucketName, String objectKey, Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags,
Long byteRangeStart, Long byteRangeEnd) throws S3ServiceException {
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags, Long byteRangeStart,
Long byteRangeEnd) throws S3ServiceException {
try {
GetOptions options = Util.convertGetObjectOptions(ifModifiedSince, ifUnmodifiedSince,
ifMatchTags, ifNoneMatchTags);
GetOptions options = Util.convertGetObjectOptions(ifModifiedSince, ifUnmodifiedSince, ifMatchTags,
ifNoneMatchTags);
return Util.convertObject(connection.getObject(bucketName, objectKey, options));
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException(String.format("error retrieving object: %1$s:%2$s",
bucketName, objectKey), e);
throw new S3ServiceException(String.format("error retrieving object: %1$s:%2$s", bucketName, objectKey), e);
}
}
@ -251,8 +243,7 @@ public class JCloudsS3Service extends S3Service {
@Override
protected S3Bucket[] listAllBucketsImpl() throws S3ServiceException {
try {
SortedSet<org.jclouds.aws.s3.domain.BucketMetadata> jcBucketList = connection
.listOwnedBuckets();
Set<org.jclouds.aws.s3.domain.BucketMetadata> jcBucketList = connection.listOwnedBuckets();
return Util.convertBuckets(jcBucketList);
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
@ -261,16 +252,15 @@ public class JCloudsS3Service extends S3Service {
}
@Override
protected S3ObjectsChunk listObjectsChunkedImpl(String bucketName, String prefix,
String delimiter, long maxListingLength, String priorLastKey, boolean completeListing)
throws S3ServiceException {
protected S3ObjectsChunk listObjectsChunkedImpl(String bucketName, String prefix, String delimiter,
long maxListingLength, String priorLastKey, boolean completeListing) throws S3ServiceException {
try {
List<S3Object> jsObjects = new ArrayList<S3Object>();
List<String> commonPrefixes = new ArrayList<String>();
ListBucketResponse jcBucket = null;
do {
ListBucketOptions options = Util.convertListObjectOptions(prefix, priorLastKey,
delimiter, (int) maxListingLength);
ListBucketOptions options = Util.convertListObjectOptions(prefix, priorLastKey, delimiter,
(int) maxListingLength);
jcBucket = connection.listBucket(bucketName, options);
@ -283,11 +273,11 @@ public class JCloudsS3Service extends S3Service {
}
} while (completeListing && jcBucket.isTruncated()); // Build entire listing if requested
return new S3ObjectsChunk(prefix, // Return the supplied prefix, not the one in the S3
return new S3ObjectsChunk(
prefix, // Return the supplied prefix, not the one in the S3
// response.
jcBucket.getDelimiter(), (S3Object[]) jsObjects.toArray(new S3Object[jsObjects
.size()]), (String[]) commonPrefixes.toArray(new String[commonPrefixes
.size()]), priorLastKey);
jcBucket.getDelimiter(), (S3Object[]) jsObjects.toArray(new S3Object[jsObjects.size()]),
(String[]) commonPrefixes.toArray(new String[commonPrefixes.size()]), priorLastKey);
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException("error listing objects in bucket " + bucketName, e);
@ -295,20 +285,18 @@ public class JCloudsS3Service extends S3Service {
}
@Override
protected S3Object[] listObjectsImpl(String bucketName, String prefix, String delimiter,
long maxListingLength) throws S3ServiceException {
try {
return listObjectsChunked(bucketName, prefix, delimiter, maxListingLength, null, true)
.getObjects();
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException("error listing objects in bucket " + bucketName, e);
}
}
@Override
protected void putBucketAclImpl(String bucketName, AccessControlList jsACL)
protected S3Object[] listObjectsImpl(String bucketName, String prefix, String delimiter, long maxListingLength)
throws S3ServiceException {
try {
return listObjectsChunked(bucketName, prefix, delimiter, maxListingLength, null, true).getObjects();
} catch (Exception e) {
Throwables.propagateIfPossible(e, S3ServiceException.class);
throw new S3ServiceException("error listing objects in bucket " + bucketName, e);
}
}
@Override
protected void putBucketAclImpl(String bucketName, AccessControlList jsACL) throws S3ServiceException {
try {
org.jclouds.aws.s3.domain.AccessControlList jcACL = Util.convertAccessControlList(jsACL);
connection.putBucketACL(bucketName, jcACL);
@ -334,8 +322,7 @@ public class JCloudsS3Service extends S3Service {
protected S3Object putObjectImpl(String bucketName, S3Object jsObject) throws S3ServiceException {
try {
PutObjectOptions options = Util.convertPutObjectOptions(jsObject.getAcl());
org.jclouds.aws.s3.domain.S3Object jcObject = Util.convertObject(jsObject, connection
.newS3Object());
org.jclouds.aws.s3.domain.S3Object jcObject = Util.convertObject(jsObject, connection.newS3Object());
String eTag = connection.putObject(bucketName, jcObject, options);
jsObject.setETag(eTag);
return jsObject;
@ -346,23 +333,20 @@ public class JCloudsS3Service extends S3Service {
}
@Override
protected void setBucketLoggingStatusImpl(String bucketName, S3BucketLoggingStatus status)
throws S3ServiceException {
protected void setBucketLoggingStatusImpl(String bucketName, S3BucketLoggingStatus status) throws S3ServiceException {
// TODO Unimplemented
throw new UnsupportedOperationException();
}
@Override
protected void setRequesterPaysBucketImpl(String bucketName, boolean requesterPays)
throws S3ServiceException {
protected void setRequesterPaysBucketImpl(String bucketName, boolean requesterPays) throws S3ServiceException {
// TODO Unimplemented
throw new UnsupportedOperationException();
}
protected org.jets3t.service.model.S3Owner getAccountOwnerImpl()
throws org.jets3t.service.S3ServiceException {
protected org.jets3t.service.model.S3Owner getAccountOwnerImpl() throws org.jets3t.service.S3ServiceException {
// TODO Unimplemented
throw new UnsupportedOperationException();

View File

@ -25,7 +25,7 @@ import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import java.util.Map.Entry;
import javax.ws.rs.core.MediaType;
@ -66,14 +66,12 @@ public class Util {
public static S3Bucket convertBucket(org.jclouds.aws.s3.domain.BucketMetadata jcBucketMD) {
S3Bucket jsBucket = new S3Bucket(jcBucketMD.getName());
if (jcBucketMD.getOwner() != null) {
jsBucket.setOwner(new S3Owner(jcBucketMD.getOwner().getId(), jcBucketMD.getOwner()
.getDisplayName()));
jsBucket.setOwner(new S3Owner(jcBucketMD.getOwner().getId(), jcBucketMD.getOwner().getDisplayName()));
}
return jsBucket;
}
public static S3Bucket[] convertBuckets(
SortedSet<org.jclouds.aws.s3.domain.BucketMetadata> jcBucketMDs) {
public static S3Bucket[] convertBuckets(Set<org.jclouds.aws.s3.domain.BucketMetadata> jcBucketMDs) {
List<S3Bucket> jsBuckets = new ArrayList<S3Bucket>(jcBucketMDs.size());
for (org.jclouds.aws.s3.domain.BucketMetadata jcBucketMD : jcBucketMDs) {
jsBuckets.add(convertBucket(jcBucketMD));
@ -92,8 +90,7 @@ public class Util {
public static S3Object convertObjectHead(ObjectMetadata jcObjectMD) {
S3Object jsObject = new S3Object(jcObjectMD.getKey());
if (jcObjectMD.getOwner() != null) {
jsObject.setOwner(new S3Owner(jcObjectMD.getOwner().getId(), jcObjectMD.getOwner()
.getDisplayName()));
jsObject.setOwner(new S3Owner(jcObjectMD.getOwner().getId(), jcObjectMD.getOwner().getDisplayName()));
}
jsObject.setContentLength(jcObjectMD.getSize());
jsObject.setContentDisposition(jcObjectMD.getContentDisposition());
@ -172,9 +169,8 @@ public class Util {
return jcObject;
}
public static GetOptions convertGetObjectOptions(Calendar ifModifiedSince,
Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags)
throws UnsupportedEncodingException {
public static GetOptions convertGetObjectOptions(Calendar ifModifiedSince, Calendar ifUnmodifiedSince,
String[] ifMatchTags, String[] ifNoneMatchTags) throws UnsupportedEncodingException {
GetOptions options = new GetOptions();
if (ifModifiedSince != null) {
options.ifModifiedSince(ifModifiedSince.getTime());
@ -193,8 +189,8 @@ public class Util {
return options;
}
public static ListBucketOptions convertListObjectOptions(String prefix, String marker,
String delimiter, Integer maxKeys) throws UnsupportedEncodingException {
public static ListBucketOptions convertListObjectOptions(String prefix, String marker, String delimiter,
Integer maxKeys) throws UnsupportedEncodingException {
ListBucketOptions options = new ListBucketOptions();
if (prefix != null) {
options.withPrefix(prefix);
@ -223,12 +219,10 @@ public class Util {
} else if (acl == AccessControlList.REST_CANNED_PUBLIC_READ_WRITE) {
return CannedAccessPolicy.PUBLIC_READ_WRITE;
}
throw new IllegalArgumentException("Only 'canned' AccessControlList options are supported: "
+ acl);
throw new IllegalArgumentException("Only 'canned' AccessControlList options are supported: " + acl);
}
public static AccessControlList convertAccessControlList(
org.jclouds.aws.s3.domain.AccessControlList jcACL) {
public static AccessControlList convertAccessControlList(org.jclouds.aws.s3.domain.AccessControlList jcACL) {
AccessControlList jsACL = new AccessControlList();
if (jcACL.getOwner() != null) {
jsACL.setOwner(new S3Owner(jcACL.getOwner().getId(), jcACL.getOwner().getDisplayName()));
@ -264,16 +258,14 @@ public class Util {
}
@SuppressWarnings("unchecked")
public static org.jclouds.aws.s3.domain.AccessControlList convertAccessControlList(
AccessControlList jsACL) {
public static org.jclouds.aws.s3.domain.AccessControlList convertAccessControlList(AccessControlList jsACL) {
org.jclouds.aws.s3.domain.AccessControlList jcACL = new org.jclouds.aws.s3.domain.AccessControlList();
if (jsACL.getOwner() != null) {
jcACL.setOwner(new org.jclouds.aws.s3.domain.CanonicalUser(jsACL.getOwner().getId()));
}
Iterator jsGrantAndPermissionIter = jsACL.getGrants().iterator();
while (jsGrantAndPermissionIter.hasNext()) {
GrantAndPermission jsGrantAndPermission = (GrantAndPermission) jsGrantAndPermissionIter
.next();
GrantAndPermission jsGrantAndPermission = (GrantAndPermission) jsGrantAndPermissionIter.next();
org.jclouds.aws.s3.domain.AccessControlList.Permission jcPermission = null;
Permission jsPerm = jsGrantAndPermission.getPermission();
@ -292,15 +284,12 @@ public class Util {
org.jclouds.aws.s3.domain.AccessControlList.Grantee jcGrantee = null;
GranteeInterface jsGrantee = jsGrantAndPermission.getGrantee();
if (jsGrantee instanceof EmailAddressGrantee) {
jcGrantee = new org.jclouds.aws.s3.domain.AccessControlList.EmailAddressGrantee(
jsGrantee.getIdentifier());
jcGrantee = new org.jclouds.aws.s3.domain.AccessControlList.EmailAddressGrantee(jsGrantee.getIdentifier());
} else if (jsGrantee instanceof CanonicalGrantee) {
jcGrantee = new org.jclouds.aws.s3.domain.AccessControlList.CanonicalUserGrantee(
jsGrantee.getIdentifier());
jcGrantee = new org.jclouds.aws.s3.domain.AccessControlList.CanonicalUserGrantee(jsGrantee.getIdentifier());
} else if (jsGrantee instanceof GroupGrantee) {
jcGrantee = new org.jclouds.aws.s3.domain.AccessControlList.GroupGrantee(
org.jclouds.aws.s3.domain.AccessControlList.GroupGranteeURI.fromURI(jsGrantee
.getIdentifier()));
org.jclouds.aws.s3.domain.AccessControlList.GroupGranteeURI.fromURI(jsGrantee.getIdentifier()));
}
jcACL.addPermission(jcGrantee, jcPermission);
@ -317,9 +306,9 @@ public class Util {
}
@SuppressWarnings("unchecked")
public static CopyObjectOptions convertCopyObjectOptions(AccessControlList acl,
Map destinationMetadata, Calendar ifModifiedSince, Calendar ifUnmodifiedSince,
String[] ifMatchTags, String[] ifNoneMatchTags) throws UnsupportedEncodingException {
public static CopyObjectOptions convertCopyObjectOptions(AccessControlList acl, Map destinationMetadata,
Calendar ifModifiedSince, Calendar ifUnmodifiedSince, String[] ifMatchTags, String[] ifNoneMatchTags)
throws UnsupportedEncodingException {
CopyObjectOptions options = new CopyObjectOptions();
if (acl != null) {
options.overrideAcl(convertACLToCannedAccessPolicy(acl));

View File

@ -31,7 +31,7 @@ import java.io.InputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -99,8 +99,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testCreateBucketImpl() throws S3ServiceException, InterruptedException,
ExecutionException, TimeoutException {
public void testCreateBucketImpl() throws S3ServiceException, InterruptedException, ExecutionException,
TimeoutException {
String bucketName = getContainerName();
try {
S3Bucket bucket = service.createBucket(new S3Bucket(bucketName));
@ -112,8 +112,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testDeleteBucketImpl() throws S3ServiceException, InterruptedException,
ExecutionException, TimeoutException {
public void testDeleteBucketImpl() throws S3ServiceException, InterruptedException, ExecutionException,
TimeoutException {
final String bucketName = getContainerName();
service.deleteBucket(bucketName);
assertConsistencyAware(new Runnable() {
@ -124,8 +124,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testDeleteObjectImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException, IOException {
public void testDeleteObjectImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException, IOException {
String bucketName = getContainerName();
try {
String objectKey = "key-testDeleteObjectImpl";
@ -141,8 +141,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testGetObjectDetailsImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException, IOException {
public void testGetObjectDetailsImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException, IOException {
String bucketName = getContainerName();
try {
String objectKey = "key-testGetObjectDetailsImpl".toLowerCase();
@ -167,8 +167,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testGetObjectImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException, IOException {
public void testGetObjectImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException, IOException {
String bucketName = getContainerName();
try {
String objectKey = "key-testGetObjectImpl".toLowerCase();
@ -196,15 +196,14 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testListAllBucketsImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException {
public void testListAllBucketsImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException {
String bucketName = getContainerName();
try {
// Ensure there is at least 1 bucket in S3 identity to list and compare.
S3Bucket[] jsBuckets = service.listAllBuckets();
SortedSet<org.jclouds.aws.s3.domain.BucketMetadata> jcBuckets = getApi()
.listOwnedBuckets();
Set<org.jclouds.aws.s3.domain.BucketMetadata> jcBuckets = getApi().listOwnedBuckets();
assert jsBuckets.length == jcBuckets.size();
@ -221,8 +220,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testListObjectsChunkedImpl() throws InterruptedException, ExecutionException,
TimeoutException, IOException, S3ServiceException {
public void testListObjectsChunkedImpl() throws InterruptedException, ExecutionException, TimeoutException,
IOException, S3ServiceException {
String bucketName = getContainerName();
try {
addBlobToContainer(bucketName, "item1/subobject2");
@ -301,8 +300,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testListObjectsImpl() throws InterruptedException, ExecutionException,
TimeoutException, IOException, S3ServiceException {
public void testListObjectsImpl() throws InterruptedException, ExecutionException, TimeoutException, IOException,
S3ServiceException {
String bucketName = null;
try {
bucketName = getContainerName();
@ -343,8 +342,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
@Test
public void testPutObjectImpl() throws S3ServiceException, InterruptedException,
ExecutionException, TimeoutException, NoSuchAlgorithmException, IOException {
public void testPutObjectImpl() throws S3ServiceException, InterruptedException, ExecutionException,
TimeoutException, NoSuchAlgorithmException, IOException {
String bucketName = getContainerName();
try {
String objectKey = "putObject";
@ -396,8 +395,7 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
requestObject = new S3Object(objectKey);
requestObject.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
jsResultObject = service.putObject(new S3Bucket(bucketName), requestObject);
org.jclouds.aws.s3.domain.AccessControlList jcACL = getApi().getObjectACL(bucketName,
objectKey);
org.jclouds.aws.s3.domain.AccessControlList jcACL = getApi().getObjectACL(bucketName, objectKey);
assertTrue(jcACL.hasPermission(GroupGranteeURI.ALL_USERS, Permission.READ));
assertTrue(jcACL.hasPermission(jcACL.getOwner().getId(), Permission.FULL_CONTROL));
assertEquals(jcACL.getGrants().size(), 2);
@ -414,8 +412,7 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
jsResultObject = service.putObject(new S3Bucket(bucketName), requestObject);
jcObject = getApi().getObject(bucketName, objectKey);
assertTrue(jsResultObject.verifyData(data.getBytes("UTF-8")));
assertEquals(jsResultObject.getETag(), jcObject.getMetadata().getETag().replaceAll("\"",
""));
assertEquals(jsResultObject.getETag(), jcObject.getMetadata().getETag().replaceAll("\"", ""));
} finally {
returnContainer(bucketName);
}
@ -423,8 +420,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
@Test
@SuppressWarnings("unchecked")
public void testCopyObjectImpl() throws InterruptedException, ExecutionException,
TimeoutException, IOException, S3ServiceException {
public void testCopyObjectImpl() throws InterruptedException, ExecutionException, TimeoutException, IOException,
S3ServiceException {
String bucketName = getContainerName();
try {
String data = "This is my data";
@ -445,13 +442,11 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
// Copy with metadata and ACL retained
destinationObject = new S3Object(destinationObjectKey);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName,
destinationObject, false);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName, destinationObject, false);
jcDestinationObject = getApi().getObject(bucketName, destinationObject.getKey());
// TODO null keys from s3object! assertEquals(jcDestinationObject.getKey(),
// destinationObjectKey);
assertEquals(jcDestinationObject.getMetadata().getUserMetadata().get(metadataName),
sourceMetadataValue);
assertEquals(jcDestinationObject.getMetadata().getUserMetadata().get(metadataName), sourceMetadataValue);
assertEquals(copyResult.get("ETag"), jcDestinationObject.getMetadata().getETag());
// Test destination ACL is unchanged (ie private)
org.jclouds.aws.s3.domain.AccessControlList jcACL = getApi().getObjectACL(bucketName,
@ -462,11 +457,9 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
// Copy with metadata replaced
destinationObject = new S3Object(destinationObjectKey);
destinationObject.addMetadata("x-amz-meta-" + metadataName, destinationMetadataValue);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName,
destinationObject, true);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName, destinationObject, true);
jcDestinationObject = getApi().getObject(bucketName, destinationObject.getKey());
assertEquals(jcDestinationObject.getMetadata().getUserMetadata().get(metadataName),
destinationMetadataValue);
assertEquals(jcDestinationObject.getMetadata().getUserMetadata().get(metadataName), destinationMetadataValue);
// Test destination ACL is unchanged (ie private)
jcACL = getApi().getObjectACL(bucketName, destinationObject.getKey());
assertEquals(jcACL.getGrants().size(), 1);
@ -475,8 +468,7 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
// Copy with ACL modified
destinationObject = new S3Object(destinationObjectKey);
destinationObject.setAcl(AccessControlList.REST_CANNED_PUBLIC_READ);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName,
destinationObject, false);
copyResult = service.copyObject(bucketName, sourceObjectKey, bucketName, destinationObject, false);
// Test destination ACL is changed (ie public-read)
jcACL = getApi().getObjectACL(bucketName, destinationObject.getKey());
assertEquals(jcACL.getGrants().size(), 2);
@ -490,8 +482,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
@Test
@SuppressWarnings("unchecked")
public void testPutAndGetBucketAclImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException {
public void testPutAndGetBucketAclImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException {
String bucketName = getContainerName();
try {
S3Bucket bucket = new S3Bucket(bucketName);
@ -508,40 +500,31 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
});
assertNotNull(gap);
assertEquals(gap.getPermission(),
org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
// Add read access for public, and read-acp access for authenticated users.
acl.grantPermission(GroupGrantee.ALL_USERS,
org.jets3t.service.acl.Permission.PERMISSION_READ);
acl.grantPermission(GroupGrantee.AUTHENTICATED_USERS,
org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
acl.grantPermission(GroupGrantee.ALL_USERS, org.jets3t.service.acl.Permission.PERMISSION_READ);
acl.grantPermission(GroupGrantee.AUTHENTICATED_USERS, org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
service.putBucketAcl(bucketName, acl);
acl = service.getBucketAcl(bucket);
assertEquals(acl.getGrants().size(), 3);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(ownerId);
}
});
assertEquals(gap.getPermission(),
org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(
GroupGrantee.ALL_USERS.getIdentifier());
}
});
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(ownerId);
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(GroupGrantee.ALL_USERS.getIdentifier());
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_READ);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(
GroupGrantee.AUTHENTICATED_USERS.getIdentifier());
}
});
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(GroupGrantee.AUTHENTICATED_USERS.getIdentifier());
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
} finally {
// need to delete this container as we've modified its acls
@ -551,8 +534,8 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
@Test
@SuppressWarnings("unchecked")
public void testGetAndPutObjectAclImpl() throws InterruptedException, ExecutionException,
TimeoutException, S3ServiceException, NoSuchAlgorithmException, IOException {
public void testGetAndPutObjectAclImpl() throws InterruptedException, ExecutionException, TimeoutException,
S3ServiceException, NoSuchAlgorithmException, IOException {
String bucketName = getContainerName();
try {
S3Bucket bucket = new S3Bucket(bucketName);
@ -573,40 +556,31 @@ public class JCloudsS3ServiceLiveTest extends BaseBlobStoreIntegrationTest {
}
});
assertNotNull(gap);
assertEquals(gap.getPermission(),
org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
// Add read access for public, and read-acp access for authenticated users.
acl.grantPermission(GroupGrantee.ALL_USERS,
org.jets3t.service.acl.Permission.PERMISSION_READ);
acl.grantPermission(GroupGrantee.AUTHENTICATED_USERS,
org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
acl.grantPermission(GroupGrantee.ALL_USERS, org.jets3t.service.acl.Permission.PERMISSION_READ);
acl.grantPermission(GroupGrantee.AUTHENTICATED_USERS, org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
service.putObjectAcl(bucketName, object.getKey(), acl);
acl = service.getObjectAcl(bucket, object.getKey());
assertEquals(acl.getGrants().size(), 3);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(ownerId);
}
});
assertEquals(gap.getPermission(),
org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(
GroupGrantee.ALL_USERS.getIdentifier());
}
});
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(ownerId);
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_FULL_CONTROL);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(GroupGrantee.ALL_USERS.getIdentifier());
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_READ);
gap = (GrantAndPermission) Iterables.find(acl.getGrants(),
new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(
GroupGrantee.AUTHENTICATED_USERS.getIdentifier());
}
});
gap = (GrantAndPermission) Iterables.find(acl.getGrants(), new Predicate<GrantAndPermission>() {
public boolean apply(GrantAndPermission gap) {
return gap.getGrantee().getIdentifier().equals(GroupGrantee.AUTHENTICATED_USERS.getIdentifier());
}
});
assertEquals(gap.getPermission(), org.jets3t.service.acl.Permission.PERMISSION_READ_ACP);
} finally {
returnContainer(bucketName);

View File

@ -57,6 +57,7 @@ import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.rest.binders.BindToJsonPayload;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
@ -83,7 +84,7 @@ public interface ChefAsyncClient {
@POST
@Path("sandboxes")
ListenableFuture<UploadSandbox> getUploadSandboxForChecksums(
@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
@PUT
ListenableFuture<Void> uploadContent(@BinderParam(BindChecksumsToJsonPayload.class) Set<List<Byte>> md5s);
@ -94,7 +95,7 @@ public interface ChefAsyncClient {
@PUT
@Path("sandboxes/{id}")
ListenableFuture<Sandbox> commitSandbox(@PathParam("id") String id,
@BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted);
@BinderParam(BindIsCompletedToJsonPayload.class) boolean isCompleted);
/**
* @see ChefCookbooks#listCookbooks
@ -102,6 +103,7 @@ public interface ChefAsyncClient {
@GET
@Path("cookbooks")
@ResponseParser(ParseKeySetFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<String>> listCookbooks();
/**
@ -110,7 +112,7 @@ public interface ChefAsyncClient {
@PUT
@Path("cookbooks/{cookbookname}/{version}")
ListenableFuture<Void> updateCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);
@PathParam("version") String version, @BinderParam(BindToJsonPayload.class) CookbookVersion cookbook);
/**
* @see ChefCookbook#deleteCookbook(String)
@ -119,7 +121,7 @@ public interface ChefAsyncClient {
@Path("cookbooks/{cookbookname}/{version}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version);
@PathParam("version") String version);
/**
* @see ChefCookbook#getVersionsOfCookbook
@ -127,7 +129,7 @@ public interface ChefAsyncClient {
@GET
@Path("cookbooks/{cookbookname}")
@Unwrap
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<String>> getVersionsOfCookbook(@PathParam("cookbookname") String cookbookName);
/**
@ -137,7 +139,7 @@ public interface ChefAsyncClient {
@Path("cookbooks/{cookbookname}/{version}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<CookbookVersion> getCookbook(@PathParam("cookbookname") String cookbookName,
@PathParam("version") String version);
@PathParam("version") String version);
/**
* @see ChefClient#createClient
@ -154,7 +156,7 @@ public interface ChefAsyncClient {
@Path("clients/{clientname}")
@ResponseParser(ParseKeyFromJson.class)
ListenableFuture<String> generateKeyForClient(
@PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname);
@PathParam("clientname") @BinderParam(BindGenerateKeyForClientToJsonPayload.class) String clientname);
/**
* @see ChefClient#clientExists
@ -188,6 +190,7 @@ public interface ChefAsyncClient {
@GET
@Path("clients")
@ResponseParser(ParseKeySetFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<String>> listClients();
/**
@ -203,7 +206,7 @@ public interface ChefAsyncClient {
@PUT
@Path("nodes/{nodename}")
ListenableFuture<Node> updateNode(
@PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node);
@PathParam("nodename") @ParamParser(NodeName.class) @BinderParam(BindToJsonPayload.class) Node node);
/**
* @see ChefNode#nodeExists
@ -236,5 +239,6 @@ public interface ChefAsyncClient {
@GET
@Path("nodes")
@ResponseParser(ParseKeySetFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<String>> listNodes();
}

View File

@ -48,6 +48,7 @@ import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
@ -73,9 +74,9 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
Method method = ChefAsyncClient.class.getMethod("commitSandbox", String.class, boolean.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method,
"0189e76ccc476701d6b374e5a1a27347", true);
"0189e76ccc476701d6b374e5a1a27347", true);
assertRequestLineEquals(httpRequest,
"PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1");
"PUT http://localhost:4000/sandboxes/0189e76ccc476701d6b374e5a1a27347 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(httpRequest, "{\"is_completed\":\"true\"}", "application/json", false);
@ -91,15 +92,15 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
EncryptionService encryptionService = injector.getInstance(EncryptionService.class);
Method method = ChefAsyncClient.class.getMethod("getUploadSandboxForChecksums", Set.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, ImmutableSet.of(Bytes
.asList(encryptionService.fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes.asList(encryptionService
.fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes.asList(encryptionService
.fromHex("1dda05ed139664f1f89b9dec482b77c0"))));
.asList(encryptionService.fromHex("0189e76ccc476701d6b374e5a1a27347")), Bytes.asList(encryptionService
.fromHex("0c5ecd7788cf4f6c7de2a57193897a6c")), Bytes.asList(encryptionService
.fromHex("1dda05ed139664f1f89b9dec482b77c0"))));
assertRequestLineEquals(httpRequest, "POST http://localhost:4000/sandboxes HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(
httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}",
"application/json", false);
httpRequest,
"{\"checksums\":{\"0189e76ccc476701d6b374e5a1a27347\":null,\"0c5ecd7788cf4f6c7de2a57193897a6c\":null,\"1dda05ed139664f1f89b9dec482b77c0\":null}}",
"application/json", false);
assertResponseParserClassEquals(method, httpRequest, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
@ -141,16 +142,16 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
public void testUpdateCookbook() throws SecurityException, NoSuchMethodException, IOException {
Method method = ChefAsyncClient.class.getMethod("updateCookbook", String.class, String.class,
CookbookVersion.class);
CookbookVersion.class);
GeneratedHttpRequest<ChefAsyncClient> httpRequest = processor.createRequest(method, "cookbook", "1.0.1",
new CookbookVersion("cookbook", "1.0.1"));
new CookbookVersion("cookbook", "1.0.1"));
assertRequestLineEquals(httpRequest, "PUT http://localhost:4000/cookbooks/cookbook/1.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\nX-Chef-Version: 0.9.6\n");
assertPayloadEquals(
httpRequest,
"{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}",
"application/json", false);
httpRequest,
"{\"name\":\"cookbook-1.0.1\",\"definitions\":[],\"attributes\":[],\"files\":[],\"metadata\":{\"suggestions\":{},\"dependencies\":{},\"conflicting\":{},\"providing\":{},\"platforms\":{},\"recipes\":{},\"replacing\":{},\"groupings\":{},\"attributes\":{},\"recommendations\":{}},\"providers\":[],\"cookbook_name\":\"cookbook\",\"resources\":[],\"templates\":[],\"libraries\":[],\"version\":\"1.0.1\",\"recipes\":[],\"root_files\":[],\"json_class\":\"Chef::CookbookVersion\",\"chef_type\":\"cookbook_version\"}",
"application/json", false);
assertResponseParserClassEquals(method, httpRequest, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
@ -169,7 +170,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -246,7 +247,7 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
assertResponseParserClassEquals(method, httpRequest, ParseKeySetFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -282,6 +283,6 @@ public class ChefAsyncClientTest extends RestClientTest<ChefAsyncClient> {
@Override
public ContextSpec<ChefClient, ChefAsyncClient> createContextSpec() {
return new RestContextFactory().createContextSpec("chef", "user", SignedHeaderAuthTest.PRIVATE_KEY,
new Properties());
new Properties());
}
}

View File

@ -47,38 +47,31 @@ public class ComputeServiceTimeoutsModule extends AbstractModule {
@Provides
@Singleton
@Named("NODE_RUNNING")
protected Predicate<NodeMetadata> nodeRunning(NodeRunning stateRunning,
Timeouts timeouts) {
return timeouts.nodeRunning == 0 ? stateRunning
: new RetryablePredicate<NodeMetadata>(stateRunning,
timeouts.nodeRunning);
protected Predicate<NodeMetadata> nodeRunning(NodeRunning stateRunning, Timeouts timeouts) {
return timeouts.nodeRunning == 0 ? stateRunning : new RetryablePredicate<NodeMetadata>(stateRunning,
timeouts.nodeRunning);
}
@Provides
@Singleton
@Named("NODE_TERMINATED")
protected Predicate<NodeMetadata> serverTerminated(
NodeTerminated stateTerminated, Timeouts timeouts) {
return timeouts.nodeTerminated == 0 ? stateTerminated
: new RetryablePredicate<NodeMetadata>(stateTerminated,
timeouts.nodeTerminated);
protected Predicate<NodeMetadata> serverTerminated(NodeTerminated stateTerminated, Timeouts timeouts) {
return timeouts.nodeTerminated == 0 ? stateTerminated : new RetryablePredicate<NodeMetadata>(stateTerminated,
timeouts.nodeTerminated);
}
@Provides
@Singleton
@Named("SCRIPT_COMPLETE")
protected Predicate<CommandUsingClient> runScriptRunning(
ScriptStatusReturnsZero stateRunning, Timeouts timeouts) {
return timeouts.scriptComplete == 0 ? not(stateRunning)
: new RetryablePredicate<CommandUsingClient>(not(stateRunning),
timeouts.scriptComplete);
protected Predicate<CommandUsingClient> runScriptRunning(ScriptStatusReturnsZero stateRunning, Timeouts timeouts) {
return timeouts.scriptComplete == 0 ? not(stateRunning) : new RetryablePredicate<CommandUsingClient>(
not(stateRunning), timeouts.scriptComplete);
}
@Provides
@Singleton
protected Predicate<IPSocket> socketTester(SocketOpen open, Timeouts timeouts) {
return timeouts.portOpen == 0 ? open : new RetryablePredicate<IPSocket>(
open, timeouts.portOpen);
return timeouts.portOpen == 0 ? open : new RetryablePredicate<IPSocket>(open, timeouts.portOpen);
}
@Override

View File

@ -40,7 +40,7 @@ public interface ComputeServiceConstants {
static class Timeouts {
@Inject(optional = true)
@Named(PROPERTY_TIMEOUT_NODE_TERMINATED)
public long nodeTerminated = 15 * 1000;
public long nodeTerminated = 30 * 1000;
@Inject(optional = true)
@Named(PROPERTY_TIMEOUT_NODE_RUNNING)

View File

@ -25,6 +25,6 @@ package org.jclouds.domain;
*/
public enum LocationScope {
PROVIDER, REGION, ZONE, RACK, HOST;
PROVIDER, REGION, NETWORK, ZONE, RACK, HOST;
}

View File

@ -0,0 +1,61 @@
/**
*
* 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.functions;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.util.Utils.propagateOrNull;
import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.jclouds.http.functions.ReturnTrueOn404;
import org.jclouds.rest.ResourceNotFoundException;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
/**
*
* @author Adrian Cole
*/
@Singleton
public class ReturnEmptySetOnNotFoundOr404 implements Function<Exception, Object> {
private final ReturnTrueOn404 rto404;
@Inject
private ReturnEmptySetOnNotFoundOr404(ReturnTrueOn404 rto404) {
this.rto404 = checkNotNull(rto404, "rto404");
}
public Object apply(Exception from) {
Iterable<ResourceNotFoundException> throwables = Iterables.filter(Throwables.getCausalChain(from),
ResourceNotFoundException.class);
if (Iterables.size(throwables) >= 1) {
return ImmutableSet.of();
} else if (rto404.apply(from)) {
return ImmutableSet.of();
}
return Set.class.cast(propagateOrNull(from));
}
}

View File

@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Map;
import java.util.SortedSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -65,8 +65,7 @@ public class StoreTweetsController extends HttpServlet {
Blob to = map.newBlob(from.getId() + "");
to.getMetadata().setContentType(MediaType.TEXT_PLAIN);
to.setPayload(from.getText());
to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME,
from.getUser().getScreenName());
to.getMetadata().getUserMetadata().put(TweetStoreConstants.SENDER_NAME, from.getUser().getScreenName());
return to;
}
}
@ -84,17 +83,16 @@ public class StoreTweetsController extends HttpServlet {
@Inject
@VisibleForTesting
public StoreTweetsController(Map<String, BlobStoreContext> contexts,
@Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container,
TwitterClient client) {
@Named(TweetStoreConstants.PROPERTY_TWEETSTORE_CONTAINER) String container, TwitterClient client) {
this.container = container;
this.contexts = contexts;
this.client = client;
}
@VisibleForTesting
public void addMyTweets(String contextName, SortedSet<Status> allAboutMe) {
BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for "
+ contextName + " in " + contexts.keySet());
public void addMyTweets(String contextName, Set<Status> allAboutMe) {
BlobStoreContext context = checkNotNull(contexts.get(contextName), "no context for " + contextName + " in "
+ contexts.keySet());
BlobMap map = context.createBlobMap(container);
for (Status status : allAboutMe) {
Blob blob = null;
@ -104,20 +102,17 @@ public class StoreTweetsController extends HttpServlet {
} catch (AuthorizationException e) {
throw e;
} catch (Exception e) {
logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob,
context, container);
logger.error(e, "Error storing tweet %s (blob[%s]) on map %s/%s", status.getId(), blob, context, container);
}
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getHeader("X-AppEngine-QueueName") != null
&& request.getHeader("X-AppEngine-QueueName").equals("twitter")) {
try {
String contextName = checkNotNull(request.getHeader("context"),
"missing header context");
String contextName = checkNotNull(request.getHeader("context"), "missing header context");
logger.info("retrieving tweets");
addMyTweets(contextName, client.getMyMentions());
logger.debug("done storing tweets");

View File

@ -29,7 +29,6 @@ import java.net.URL;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.Map.Entry;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -68,20 +67,17 @@ public class TweetStoreLiveTest {
private Map<String, BlobStoreContext> contexts;
private String container;
private static final Iterable<String> blobstores = ImmutableSet.of("cloudfiles",
"googlestorage", "s3", "azureblob");
private static final Iterable<String> blobstores = ImmutableSet.of("cloudfiles", "googlestorage", "s3", "azureblob");
private static final Properties props = new Properties();
@BeforeTest
void clearAndCreateContainers() throws InterruptedException, ExecutionException,
TimeoutException, IOException {
void clearAndCreateContainers() throws InterruptedException, ExecutionException, TimeoutException, IOException {
container = checkNotNull(System.getProperty(PROPERTY_TWEETSTORE_CONTAINER));
props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, checkNotNull(System
.getProperty(PROPERTY_TWEETSTORE_CONTAINER), PROPERTY_TWEETSTORE_CONTAINER));
props.setProperty(PROPERTY_TWEETSTORE_CONTAINER, checkNotNull(System.getProperty(PROPERTY_TWEETSTORE_CONTAINER),
PROPERTY_TWEETSTORE_CONTAINER));
props.setProperty(GuiceServletConfig.PROPERTY_BLOBSTORE_CONTEXTS, Joiner.on(',').join(
blobstores));
props.setProperty(GuiceServletConfig.PROPERTY_BLOBSTORE_CONTEXTS, Joiner.on(',').join(blobstores));
// put all identity/credential pairs into the client
addCredentialsForBlobStores(props);
@ -98,18 +94,17 @@ public class TweetStoreLiveTest {
contexts.put(provider, factory.createContext(provider, wiring, props));
}
RestContext<TwitterClient, TwitterAsyncClient> twitterContext = new RestContextFactory()
.createContext("twitter", wiring, props);
StoreTweetsController controller = new StoreTweetsController(contexts, container,
twitterContext.getApi());
RestContext<TwitterClient, TwitterAsyncClient> twitterContext = new RestContextFactory().createContext("twitter",
wiring, props);
StoreTweetsController controller = new StoreTweetsController(contexts, container, twitterContext.getApi());
SortedSet<Status> statuses = twitterContext.getApi().getMyMentions();
Set<Status> statuses = twitterContext.getApi().getMyMentions();
boolean deleted = false;
for (BlobStoreContext context : contexts.values()) {
if (context.getBlobStore().containerExists(container)) {
System.err.printf("deleting container %s at %s%n", container, context
.getProviderSpecificContext().getEndpoint());
System.err.printf("deleting container %s at %s%n", container, context.getProviderSpecificContext()
.getEndpoint());
context.getBlobStore().deleteContainer(container);
deleted = true;
}
@ -119,8 +114,8 @@ public class TweetStoreLiveTest {
Thread.sleep(60000);
}
for (BlobStoreContext context : contexts.values()) {
System.err.printf("creating container %s at %s%n", container, context
.getProviderSpecificContext().getEndpoint());
System.err.printf("creating container %s at %s%n", container, context.getProviderSpecificContext()
.getEndpoint());
context.getBlobStore().createContainerInLocation(null, container);
}
@ -137,8 +132,7 @@ public class TweetStoreLiveTest {
@BeforeTest(dependsOnMethods = "clearAndCreateContainers")
@Parameters( { "warfile", "devappserver.address", "devappserver.port" })
public void startDevAppServer(final String warfile, final String address, final String port)
throws Exception {
public void startDevAppServer(final String warfile, final String address, final String port) throws Exception {
url = new URL(String.format("http://%s:%s", address, port));
server = new GoogleDevServer();
@ -146,22 +140,19 @@ public class TweetStoreLiveTest {
}
private void addConfigurationForTwitter(Properties props) {
String twitterIdentity = checkNotNull(System.getProperty("twitter.identity"),
"twitter.identity");
String twitterCredential = checkNotNull(System.getProperty("twitter.credential"),
"twitter.credential");
String twitterIdentity = checkNotNull(System.getProperty("twitter.identity"), "twitter.identity");
String twitterCredential = checkNotNull(System.getProperty("twitter.credential"), "twitter.credential");
props.putAll(RestContextFactory.toProperties(contextSpec("twitter", "http://twitter.com",
"1", twitterIdentity, twitterCredential, TwitterClient.class,
TwitterAsyncClient.class)));
props.putAll(RestContextFactory.toProperties(contextSpec("twitter", "http://twitter.com", "1", twitterIdentity,
twitterCredential, TwitterClient.class, TwitterAsyncClient.class)));
}
private void addCredentialsForBlobStores(Properties props) {
for (String provider : blobstores) {
props.setProperty(provider + ".identity", checkNotNull(System.getProperty(provider
+ ".identity"), provider + ".identity"));
props.setProperty(provider + ".credential", checkNotNull(System.getProperty(provider
+ ".credential"), provider + ".credential"));
props.setProperty(provider + ".identity", checkNotNull(System.getProperty(provider + ".identity"), provider
+ ".identity"));
props.setProperty(provider + ".credential", checkNotNull(System.getProperty(provider + ".credential"),
provider + ".credential"));
}
}
@ -195,8 +186,7 @@ public class TweetStoreLiveTest {
System.err.println("sleeping 20 seconds to allow for eventual consistency delay");
Thread.sleep(20000);
for (BlobStoreContext context : contexts.values()) {
assert context.createInputStreamMap(container).size() > 0 : context
.getProviderSpecificContext().getEndpoint();
assert context.createInputStreamMap(container).size() > 0 : context.getProviderSpecificContext().getEndpoint();
}
}

View File

@ -53,7 +53,6 @@ import org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;
import org.jclouds.gogrid.functions.ParseServerFromJsonResponse;
import org.jclouds.gogrid.functions.ParseServerListFromJsonResponse;
import org.jclouds.gogrid.functions.ParseServerNameToCredentialsMapFromJsonResponse;
import org.jclouds.gogrid.functions.ReturnEmptySetOnNotFound;
import org.jclouds.gogrid.options.AddServerOptions;
import org.jclouds.gogrid.options.GetServerListOptions;
import org.jclouds.rest.annotations.BinderParam;
@ -61,6 +60,7 @@ import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import com.google.common.util.concurrent.ListenableFuture;
@ -91,7 +91,7 @@ public interface GridServerAsyncClient {
*/
@GET
@ResponseParser(ParseServerListFromJsonResponse.class)
@ExceptionParser(ReturnEmptySetOnNotFound.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Path("/grid/server/get")
ListenableFuture<Set<Server>> getServersByName(
@BinderParam(BindNamesToQueryParams.class) String... names);
@ -101,7 +101,7 @@ public interface GridServerAsyncClient {
*/
@GET
@ResponseParser(ParseServerListFromJsonResponse.class)
@ExceptionParser(ReturnEmptySetOnNotFound.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Path("/grid/server/get")
ListenableFuture<Set<Server>> getServersById(
@BinderParam(BindIdsToQueryParams.class) long... ids);

View File

@ -85,8 +85,7 @@ public class GoGridLiveTest {
private RetryablePredicate<Server> serverLatestJobCompleted;
private RetryablePredicate<LoadBalancer> loadBalancerLatestJobCompleted;
/**
* Keeps track of the servers, created during the tests, to remove them after
* all tests complete
* Keeps track of the servers, created during the tests, to remove them after all tests complete
*/
private List<String> serversToDeleteAfterTheTests = new ArrayList<String>();
private List<String> loadBalancersToDeleteAfterTest = new ArrayList<String>();
@ -95,34 +94,28 @@ public class GoGridLiveTest {
@BeforeGroups(groups = { "live" })
public void setupClient() {
String identity = checkNotNull(System
.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System
.getProperty("jclouds.test.credential"), "jclouds.test.credential");
String identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
context = new RestContextFactory().createContext("gogrid", identity,
credential, ImmutableSet.<Module> of(new Log4JLoggingModule()));
context = new RestContextFactory().createContext("gogrid", identity, credential, ImmutableSet
.<Module> of(new Log4JLoggingModule()));
client = context.getApi();
serverLatestJobCompleted = new RetryablePredicate<Server>(
new ServerLatestJobCompleted(client.getJobServices()), 800, 20,
TimeUnit.SECONDS);
loadBalancerLatestJobCompleted = new RetryablePredicate<LoadBalancer>(
new LoadBalancerLatestJobCompleted(client.getJobServices()), 800,
20, TimeUnit.SECONDS);
serverLatestJobCompleted = new RetryablePredicate<Server>(new ServerLatestJobCompleted(client.getJobServices()),
800, 20, TimeUnit.SECONDS);
loadBalancerLatestJobCompleted = new RetryablePredicate<LoadBalancer>(new LoadBalancerLatestJobCompleted(client
.getJobServices()), 800, 20, TimeUnit.SECONDS);
}
@Test(enabled = true)
public void testDescriptionIs500Characters() {
final String nameOfServer = "Description"
+ String.valueOf(new Date().getTime()).substring(6);
final String nameOfServer = "Description" + String.valueOf(new Date().getTime()).substring(6);
serversToDeleteAfterTheTests.add(nameOfServer);
Set<Ip> availableIps = client.getIpServices().getUnassignedPublicIpList();
Ip availableIp = Iterables.getLast(availableIps);
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0)
.getName();
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0).getName();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 1 * 500; i++)
@ -131,73 +124,60 @@ public class GoGridLiveTest {
String description = builder.toString();
Server createdServer = client.getServerServices().addServer(nameOfServer,
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram,
availableIp.getIp(),
new AddServerOptions().withDescription(description));
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, availableIp.getIp(),
new AddServerOptions().withDescription(description));
assertNotNull(createdServer);
assert serverLatestJobCompleted.apply(createdServer);
assertEquals(Iterables.getLast(
client.getServerServices().getServersByName(nameOfServer))
.getDescription(), description);
assertEquals(Iterables.getLast(client.getServerServices().getServersByName(nameOfServer)).getDescription(),
description);
}
/**
* Tests server start, reboot and deletion. Also verifies IP services and job
* services.
* Tests server start, reboot and deletion. Also verifies IP services and job services.
*/
@Test(enabled = true)
public void testServerLifecycle() {
int serverCountBeforeTest = client.getServerServices().getServerList()
.size();
int serverCountBeforeTest = client.getServerServices().getServerList().size();
final String nameOfServer = "Server"
+ String.valueOf(new Date().getTime()).substring(6);
final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
serversToDeleteAfterTheTests.add(nameOfServer);
Set<Ip> availableIps = client.getIpServices().getUnassignedPublicIpList();
Ip availableIp = Iterables.getLast(availableIps);
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0)
.getName();
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0).getName();
Server createdServer = client.getServerServices().addServer(nameOfServer,
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram,
availableIp.getIp());
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, availableIp.getIp());
assertNotNull(createdServer);
assert serverLatestJobCompleted.apply(createdServer);
// get server by name
Set<Server> response = client.getServerServices().getServersByName(
nameOfServer);
Set<Server> response = client.getServerServices().getServersByName(nameOfServer);
assert (response.size() == 1);
// restart the server
client.getServerServices().power(nameOfServer, PowerCommand.RESTART);
Set<Job> jobs = client.getJobServices()
.getJobsForObjectName(nameOfServer);
assert ("RestartVirtualServer".equals(Iterables.getLast(jobs)
.getCommand().getName()));
Set<Job> jobs = client.getJobServices().getJobsForObjectName(nameOfServer);
assert ("RestartVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));
assert serverLatestJobCompleted.apply(createdServer);
int serverCountAfterAddingOneServer = client.getServerServices()
.getServerList().size();
int serverCountAfterAddingOneServer = client.getServerServices().getServerList().size();
assert serverCountAfterAddingOneServer == serverCountBeforeTest + 1 : "There should be +1 increase in the number of servers since the test started";
// delete the server
client.getServerServices().deleteByName(nameOfServer);
jobs = client.getJobServices().getJobsForObjectName(nameOfServer);
assert ("DeleteVirtualServer".equals(Iterables.getLast(jobs).getCommand()
.getName()));
assert ("DeleteVirtualServer".equals(Iterables.getLast(jobs).getCommand().getName()));
assert serverLatestJobCompleted.apply(createdServer);
int serverCountAfterDeletingTheServer = client.getServerServices()
.getServerList().size();
int serverCountAfterDeletingTheServer = client.getServerServices().getServerList().size();
assert serverCountAfterDeletingTheServer == serverCountBeforeTest : "There should be the same # of servers as since the test started";
// make sure that IP is put back to "unassigned"
@ -205,37 +185,32 @@ public class GoGridLiveTest {
}
/**
* Starts a servers, verifies that jobs are created correctly and an be
* retrieved from the job services
* Starts a servers, verifies that jobs are created correctly and an be retrieved from the job
* services
*/
@Test(dependsOnMethods = "testServerLifecycle", enabled = true)
public void testJobs() {
final String nameOfServer = "Server"
+ String.valueOf(new Date().getTime()).substring(6);
final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
serversToDeleteAfterTheTests.add(nameOfServer);
Set<Ip> availableIps = client.getIpServices().getUnassignedPublicIpList();
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0)
.getName();
String ram = Iterables.get(client.getServerServices().getRamSizes(), 0).getName();
Server createdServer = client.getServerServices().addServer(nameOfServer,
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram,
Iterables.getLast(availableIps).getIp());
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", ram, Iterables.getLast(availableIps).getIp());
assert serverLatestJobCompleted.apply(createdServer);
// restart the server
client.getServerServices().power(nameOfServer, PowerCommand.RESTART);
Set<Job> jobs = client.getJobServices()
.getJobsForObjectName(nameOfServer);
Set<Job> jobs = client.getJobServices().getJobsForObjectName(nameOfServer);
Job latestJob = Iterables.getLast(jobs);
Long latestJobId = latestJob.getId();
Job latestJobFetched = Iterables.getOnlyElement(client.getJobServices()
.getJobsById(latestJobId));
Job latestJobFetched = Iterables.getOnlyElement(client.getJobServices().getJobsById(latestJobId));
assert latestJob.equals(latestJobFetched) : "Job and its reprentation found by ID don't match";
@ -247,86 +222,69 @@ public class GoGridLiveTest {
Set<Job> jobsFetched = client.getJobServices().getJobsById(idsOfAllJobs);
assert jobsFetched.size() == jobs.size() : format(
"Number of jobs fetched by ids doesn't match the number of jobs "
+ "requested. Requested/expected: %d. Found: %d.", jobs
.size(), jobsFetched.size());
"Number of jobs fetched by ids doesn't match the number of jobs "
+ "requested. Requested/expected: %d. Found: %d.", jobs.size(), jobsFetched.size());
// delete the server
client.getServerServices().deleteByName(nameOfServer);
}
/**
* Tests common load balancer operations. Also verifies IP services and job
* services.
* Tests common load balancer operations. Also verifies IP services and job services.
*/
@Test(enabled = true)
public void testLoadBalancerLifecycle() {
int lbCountBeforeTest = client.getLoadBalancerServices()
.getLoadBalancerList().size();
int lbCountBeforeTest = client.getLoadBalancerServices().getLoadBalancerList().size();
final String nameOfLoadBalancer = "LoadBalancer"
+ String.valueOf(new Date().getTime()).substring(6);
final String nameOfLoadBalancer = "LoadBalancer" + String.valueOf(new Date().getTime()).substring(6);
loadBalancersToDeleteAfterTest.add(nameOfLoadBalancer);
Set<Ip> availableIps = client.getIpServices().getUnassignedPublicIpList();
if (availableIps.size() < 4)
throw new SkipException(
"Not enough available IPs (4 needed) to run the test");
throw new SkipException("Not enough available IPs (4 needed) to run the test");
Iterator<Ip> ipIterator = availableIps.iterator();
Ip vip = ipIterator.next();
Ip realIp1 = ipIterator.next();
Ip realIp2 = ipIterator.next();
Ip realIp3 = ipIterator.next();
AddLoadBalancerOptions options = new AddLoadBalancerOptions.Builder()
.create(LoadBalancerType.LEAST_CONNECTED,
LoadBalancerPersistenceType.SOURCE_ADDRESS);
LoadBalancer createdLoadBalancer = client.getLoadBalancerServices()
.addLoadBalancer(
nameOfLoadBalancer,
new IpPortPair(vip, 80),
Arrays.asList(new IpPortPair(realIp1, 80), new IpPortPair(
realIp2, 80)), options);
AddLoadBalancerOptions options = new AddLoadBalancerOptions.Builder().create(LoadBalancerType.LEAST_CONNECTED,
LoadBalancerPersistenceType.SOURCE_ADDRESS);
LoadBalancer createdLoadBalancer = client.getLoadBalancerServices().addLoadBalancer(nameOfLoadBalancer,
new IpPortPair(vip, 80), Arrays.asList(new IpPortPair(realIp1, 80), new IpPortPair(realIp2, 80)),
options);
assertNotNull(createdLoadBalancer);
assert loadBalancerLatestJobCompleted.apply(createdLoadBalancer);
// get load balancer by name
Set<LoadBalancer> response = client.getLoadBalancerServices()
.getLoadBalancersByName(nameOfLoadBalancer);
Set<LoadBalancer> response = client.getLoadBalancerServices().getLoadBalancersByName(nameOfLoadBalancer);
assert (response.size() == 1);
createdLoadBalancer = Iterables.getOnlyElement(response);
assertNotNull(createdLoadBalancer.getRealIpList());
assertEquals(createdLoadBalancer.getRealIpList().size(), 2);
assertNotNull(createdLoadBalancer.getVirtualIp());
assertEquals(createdLoadBalancer.getVirtualIp().getIp().getIp(), vip
.getIp());
assertEquals(createdLoadBalancer.getVirtualIp().getIp().getIp(), vip.getIp());
LoadBalancer editedLoadBalancer = client.getLoadBalancerServices()
.editLoadBalancerNamed(nameOfLoadBalancer,
Arrays.asList(new IpPortPair(realIp3, 8181)));
LoadBalancer editedLoadBalancer = client.getLoadBalancerServices().editLoadBalancerNamed(nameOfLoadBalancer,
Arrays.asList(new IpPortPair(realIp3, 8181)));
assert loadBalancerLatestJobCompleted.apply(editedLoadBalancer);
assertNotNull(editedLoadBalancer.getRealIpList());
assertEquals(editedLoadBalancer.getRealIpList().size(), 1);
assertEquals(Iterables.getOnlyElement(editedLoadBalancer.getRealIpList())
.getIp().getIp(), realIp3.getIp());
assertEquals(Iterables.getOnlyElement(editedLoadBalancer.getRealIpList()).getIp().getIp(), realIp3.getIp());
int lbCountAfterAddingOneServer = client.getLoadBalancerServices()
.getLoadBalancerList().size();
int lbCountAfterAddingOneServer = client.getLoadBalancerServices().getLoadBalancerList().size();
assert lbCountAfterAddingOneServer == lbCountBeforeTest + 1 : "There should be +1 increase in the number of load balancers since the test started";
// delete the load balancer
client.getLoadBalancerServices().deleteByName(nameOfLoadBalancer);
Set<Job> jobs = client.getJobServices().getJobsForObjectName(
nameOfLoadBalancer);
assert ("DeleteLoadBalancer".equals(Iterables.getLast(jobs).getCommand()
.getName()));
Set<Job> jobs = client.getJobServices().getJobsForObjectName(nameOfLoadBalancer);
assert ("DeleteLoadBalancer".equals(Iterables.getLast(jobs).getCommand().getName()));
assert loadBalancerLatestJobCompleted.apply(createdLoadBalancer);
int lbCountAfterDeletingTheServer = client.getLoadBalancerServices()
.getLoadBalancerList().size();
int lbCountAfterDeletingTheServer = client.getLoadBalancerServices().getLoadBalancerList().size();
assert lbCountAfterDeletingTheServer == lbCountBeforeTest : "There should be the same # of load balancers as since the test started";
}
@ -335,8 +293,7 @@ public class GoGridLiveTest {
*/
@Test(enabled = true)
public void testImageLifecycle() {
GetImageListOptions options = new GetImageListOptions.Builder()
.publicDatabaseServers();
GetImageListOptions options = new GetImageListOptions.Builder().publicDatabaseServers();
Set<ServerImage> images = client.getImageServices().getImageList(options);
Predicate<ServerImage> isDatabaseServer = new Predicate<ServerImage>() {
@ -349,15 +306,13 @@ public class GoGridLiveTest {
assert Iterables.all(images, isDatabaseServer) : "All of the images should've been of database type";
ServerImage image = Iterables.getLast(images);
ServerImage imageFromServer = Iterables.getOnlyElement(client
.getImageServices().getImagesByName(image.getName()));
ServerImage imageFromServer = Iterables
.getOnlyElement(client.getImageServices().getImagesByName(image.getName()));
assertEquals(image, imageFromServer);
try {
client.getImageServices().editImageDescription(image.getName(),
"newDescription");
throw new TestException(
"An exception hasn't been thrown where expected; expected GoGridResponseException");
client.getImageServices().editImageDescription(image.getName(), "newDescription");
throw new TestException("An exception hasn't been thrown where expected; expected GoGridResponseException");
} catch (GoGridResponseException e) {
// expected situation - check and proceed
assertTrue(e.getMessage().contains("GoGridIllegalArgumentException"));
@ -367,55 +322,47 @@ public class GoGridLiveTest {
@Test(enabled = true)
public void testShellAccess() throws IOException {
final String nameOfServer = "Server"
+ String.valueOf(new Date().getTime()).substring(6);
final String nameOfServer = "Server" + String.valueOf(new Date().getTime()).substring(6);
serversToDeleteAfterTheTests.add(nameOfServer);
Set<Ip> availableIps = client.getIpServices().getUnassignedIpList();
Ip availableIp = Iterables.getLast(availableIps);
Server createdServer = client.getServerServices().addServer(nameOfServer,
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1",
availableIp.getIp());
"GSI-f8979644-e646-4711-ad58-d98a5fa3612c", "1", availableIp.getIp());
assertNotNull(createdServer);
assert serverLatestJobCompleted.apply(createdServer);
// get server by name
Set<Server> response = client.getServerServices().getServersByName(
nameOfServer);
Set<Server> response = client.getServerServices().getServersByName(nameOfServer);
assert (response.size() == 1);
createdServer = Iterables.getOnlyElement(response);
Map<String, Credentials> credsMap = client.getServerServices()
.getServerCredentialsList();
Map<String, Credentials> credsMap = client.getServerServices().getServerCredentialsList();
Credentials instanceCredentials = credsMap.get(createdServer.getName());
assertNotNull(instanceCredentials);
IPSocket socket = new IPSocket(createdServer.getIp().getIp(), 22);
RetryablePredicate<IPSocket> socketOpen = new RetryablePredicate<IPSocket>(
new InetSocketAddressConnect(), 180, 5, TimeUnit.SECONDS);
RetryablePredicate<IPSocket> socketOpen = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180,
5, TimeUnit.SECONDS);
socketOpen.apply(socket);
SshClient sshClient = new JschSshClient(new BackoffLimitedRetryHandler(),
socket, 60000, instanceCredentials.identity,
instanceCredentials.credential, null);
SshClient sshClient = new JschSshClient(new BackoffLimitedRetryHandler(), socket, 60000,
instanceCredentials.identity, instanceCredentials.credential, null);
sshClient.connect();
String output = sshClient.exec("df").getOutput();
assertTrue(
output.contains("Filesystem"),
"The output should've contained filesystem information, but it didn't. Output: "
+ output);
assertTrue(output.contains("Filesystem"),
"The output should've contained filesystem information, but it didn't. Output: " + output);
sshClient.disconnect();
// check that the get credentials call is the same as this
assertEquals(client.getServerServices().getServerCredentials(
createdServer.getId()), instanceCredentials);
try{
assertEquals(client.getServerServices().getServerCredentials(createdServer.getId()), instanceCredentials);
try {
assertEquals(client.getServerServices().getServerCredentials(Long.MAX_VALUE), null);
} catch (AssertionError e){
} catch (AssertionError e) {
e.printStackTrace();
}
@ -424,8 +371,7 @@ public class GoGridLiveTest {
}
/**
* In case anything went wrong during the tests, removes the objects created
* in the tests.
* In case anything went wrong during the tests, removes the objects created in the tests.
*/
@AfterTest
public void cleanup() {

View File

@ -49,9 +49,9 @@ import org.jclouds.gogrid.functions.ParseCredentialsFromJsonResponse;
import org.jclouds.gogrid.functions.ParseOptionsFromJsonResponse;
import org.jclouds.gogrid.functions.ParseServerFromJsonResponse;
import org.jclouds.gogrid.functions.ParseServerListFromJsonResponse;
import org.jclouds.gogrid.functions.ReturnEmptySetOnNotFound;
import org.jclouds.gogrid.options.AddServerOptions;
import org.jclouds.gogrid.options.GetServerListOptions;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.internal.GeneratedHttpRequest;
import org.jclouds.rest.internal.RestAnnotationProcessor;
@ -86,7 +86,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -95,10 +95,10 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
public void testGetServerListWithOptions() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("getServerList", GetServerListOptions[].class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method,
new GetServerListOptions.Builder().onlySandboxServers());
new GetServerListOptions.Builder().onlySandboxServers());
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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -110,7 +110,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/list?"
+ "v=1.5&isSandbox=true&sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "v=1.5&isSandbox=true&sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -126,13 +126,13 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/get?" + "v=1.5&name=server1&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -148,13 +148,13 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
assertResponseParserClassEquals(method, httpRequest, ParseServerListFromJsonResponse.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFound.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -162,12 +162,12 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
@Test
public void testAddServerNoOptions() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("addServer", String.class, String.class, String.class,
String.class, AddServerOptions[].class);
String.class, AddServerOptions[].class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "serverName", "img55",
"memory", "127.0.0.1");
"memory", "127.0.0.1");
assertRequestLineEquals(httpRequest, "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");
+ "name=serverName&server.ram=memory&image=img55&ip=127.0.0.1 " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -179,8 +179,8 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/add?"
+ "v=1.5&name=serverName&server.ram=memory&" + "image=img55&ip=127.0.0.1&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
+ "v=1.5&name=serverName&server.ram=memory&" + "image=img55&ip=127.0.0.1&"
+ "sig=3f446f171455fbb5574aecff4997b273&api_key=foo " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -188,13 +188,13 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
@Test
public void testAddServerOptions() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("addServer", String.class, String.class, String.class,
String.class, AddServerOptions[].class);
String.class, AddServerOptions[].class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "serverName", "img55",
"memory", "127.0.0.1", new AddServerOptions().asSandboxType().withDescription("fooy"));
"memory", "127.0.0.1", new AddServerOptions().asSandboxType().withDescription("fooy"));
assertRequestLineEquals(
httpRequest,
"GET https://api.gogrid.com/api/grid/server/add?v=1.5&name=serverName&server.ram=memory&image=img55&ip=127.0.0.1&isSandbox=true&description=fooy HTTP/1.1");
httpRequest,
"GET https://api.gogrid.com/api/grid/server/add?v=1.5&name=serverName&server.ram=memory&image=img55&ip=127.0.0.1&isSandbox=true&description=fooy HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -206,8 +206,8 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(
httpRequest,
"GET https://api.gogrid.com/api/grid/server/add?v=1.5&name=serverName&server.ram=memory&image=img55&ip=127.0.0.1&isSandbox=true&description=fooy&sig=3f446f171455fbb5574aecff4997b273&api_key=foo HTTP/1.1");
httpRequest,
"GET https://api.gogrid.com/api/grid/server/add?v=1.5&name=serverName&server.ram=memory&image=img55&ip=127.0.0.1&isSandbox=true&description=fooy&sig=3f446f171455fbb5574aecff4997b273&api_key=foo HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -216,10 +216,10 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
public void testPowerServer() throws NoSuchMethodException, IOException {
Method method = GridServerAsyncClient.class.getMethod("power", String.class, PowerCommand.class);
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "PowerServer",
PowerCommand.RESTART);
PowerCommand.RESTART);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -231,7 +231,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -242,7 +242,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, "PowerServer");
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/grid/server/delete?v=1.5&"
+ "name=PowerServer " + "HTTP/1.1");
+ "name=PowerServer " + "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -254,7 +254,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -265,7 +265,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, "GET https://api.gogrid.com/api/common/lookup/list?v=1.5&lookup=server.ram "
+ "HTTP/1.1");
+ "HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -277,7 +277,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, "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, "");
assertPayloadEquals(httpRequest, null, null, false);
}
@ -288,7 +288,7 @@ public class GridServerAsyncClientTest extends BaseGoGridAsyncClientTest<GridSer
GeneratedHttpRequest<GridServerAsyncClient> httpRequest = processor.createRequest(method, 1);
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, "");
assertPayloadEquals(httpRequest, null, null, false);

View File

@ -68,6 +68,7 @@ import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
@ -93,6 +94,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImagesFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Image>> listImages();
/**
@ -122,14 +124,14 @@ public interface IBMDeveloperCloudAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id,
@FormParam("visibility") Image.Visibility visibility);
@FormParam("visibility") Image.Visibility visibility);
/**
* @see IBMDeveloperCloudClient#listInstancesFromRequest(long)
*/
@GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/requests/{requestId}")
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class)
ListenableFuture<Set<? extends Instance>> listInstancesFromRequest(@PathParam("requestId") String requestId);
@ -141,6 +143,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/instances")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseInstancesFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Instance>> listInstances();
/**
@ -162,7 +165,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseExpirationTimeFromJson.class)
ListenableFuture<Date> extendReservationForInstance(@PathParam("instanceId") String id,
@FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime);
@FormParam("expirationTime") @ParamParser(ParseLongFromDate.class) Date expirationTime);
/**
* @see IBMDeveloperCloudClient#restartInstance
@ -181,7 +184,7 @@ public interface IBMDeveloperCloudAsyncClient {
@FormParams(keys = "state", values = "save")
@ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> saveInstanceToImage(@PathParam("instanceId") String id,
@FormParam("name") String toImageName, @FormParam("description") String toImageDescription);
@FormParam("name") String toImageName, @FormParam("description") String toImageDescription);
/**
* @see IBMDeveloperCloudClient#createInstanceInLocation
@ -191,8 +194,8 @@ public interface IBMDeveloperCloudAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(GetFirstInstanceInList.class)
ListenableFuture<Instance> createInstanceInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("imageID") String imageID,
@FormParam("instanceType") String instanceType, CreateInstanceOptions... options);
@FormParam("name") String name, @FormParam("imageID") String imageID,
@FormParam("instanceType") String instanceType, CreateInstanceOptions... options);
/**
* @see IBMDeveloperCloudClient#deleteInstance
@ -209,6 +212,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseKeysFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Key>> listKeys();
/**
@ -239,7 +243,7 @@ public interface IBMDeveloperCloudAsyncClient {
@PUT
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/keys/{keyName}")
ListenableFuture<Void> setDefaultStatusOfKey(@PathParam("keyName") String name,
@FormParam("default") boolean isDefault);
@FormParam("default") boolean isDefault);
/**
* @see IBMDeveloperCloudClient#getKey(String)
@ -265,6 +269,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/storage")
@ResponseParser(ParseVolumesFromJson.class)
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Volume>> listVolumes();
/**
@ -275,7 +280,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size);
@FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size);
/**
* @see IBMDeveloperCloudClient#getVolume(long)
@ -302,6 +307,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/locations")
@Consumes(MediaType.TEXT_XML)
@XMLResponseParser(LocationsHandler.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Location>> listLocations();
/**
@ -321,6 +327,7 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressesFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Address>> listAddresses();
/**

View File

@ -54,6 +54,7 @@ import org.jclouds.ibmdev.xml.LocationsHandler;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.GeneratedHttpRequest;
@ -77,7 +78,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
@ -86,16 +87,16 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
Iterables.getOnlyElement(httpRequest.getFilters()).filter(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
assertNonPayloadHeadersEqual(httpRequest,
"Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n");
"Accept: application/json\nAuthorization: Basic aWRlbnRpdHk6Y3JlZGVudGlhbA==\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseImagesFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -106,7 +107,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
@ -123,7 +124,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -137,12 +138,12 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testSetImageVisibility() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("setImageVisibility", String.class,
Image.Visibility.class);
Image.Visibility.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
Image.Visibility.PUBLIC);
Image.Visibility.PUBLIC);
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");
assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false);
@ -159,13 +160,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseInstancesFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -176,13 +177,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseInstancesFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -193,7 +194,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
@ -207,12 +208,12 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testExtendReservationForInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("extendReservationForInstance", String.class,
Date.class);
Date.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1", new Date(
123215235l));
123215235l));
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, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false);
@ -225,11 +226,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testRestartInstance() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class);
RestartInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false);
@ -242,12 +243,12 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testRestartInstanceNewKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("restartInstance", String.class,
RestartInstanceOptions[].class);
RestartInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
new RestartInstanceOptions().authorizePublicKey("keyName"));
new RestartInstanceOptions().authorizePublicKey("keyName"));
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, "");
assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false);
@ -260,15 +261,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testSaveInstanceToImage() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("saveInstanceToImage", String.class, String.class,
String.class);
String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1",
"imageName", "imageDescription");
"imageName", "imageDescription");
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, "Accept: application/json\n");
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);
assertSaxResponseParserClassEquals(method, null);
@ -282,7 +283,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -299,13 +300,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseKeysFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -316,7 +317,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertPayloadEquals(httpRequest, null, null, false);
@ -333,7 +334,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key");
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, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false);
@ -348,10 +349,10 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testAddPublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("addPublicKey", String.class, String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key",
"publicbits");
"publicbits");
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, "");
assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -366,10 +367,10 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testUpdatePublicKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("updatePublicKey", String.class, String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key",
"publicbits");
"publicbits");
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, "");
assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -383,11 +384,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testSetDefaultStatusOfKey() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class
.getMethod("setDefaultStatusOfKey", String.class, boolean.class);
.getMethod("setDefaultStatusOfKey", String.class, boolean.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key", true);
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, "");
assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false);
@ -404,7 +405,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -421,13 +422,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumesFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -438,7 +439,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
@ -452,15 +453,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException {
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",
"name", "format", "size");
"name", "format", "size");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size",
"application/x-www-form-urlencoded", false);
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class);
assertSaxResponseParserClassEquals(method, null);
@ -472,15 +473,15 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testCreateInstanceInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class,
String.class, String.class, String.class, CreateInstanceOptions[].class);
String.class, String.class, String.class, CreateInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1", "name",
"22", "instanceType");
"22", "instanceType");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1&imageID=22&name=name&instanceType=instanceType",
"application/x-www-form-urlencoded", false);
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, GetFirstInstanceInList.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
@ -491,20 +492,20 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testCreateInstanceInLocationWithOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createInstanceInLocation", String.class,
String.class, String.class, String.class, CreateInstanceOptions[].class);
String.class, String.class, String.class, CreateInstanceOptions[].class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location",
"name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO")
.mountVolume("2", "/mnt").configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", "myPassword2",
"report_user_password", "myPassword3")));
"name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO")
.mountVolume("2", "/mnt").configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password",
"myPassword2", "report_user_password", "myPassword3")));
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(
httpRequest,
"location=location&imageID=22&name=name&instanceType=instanceType&ip=1&publicKey=MOO&volumeID=2&oss.storage.id.0.mnt=%2Fmnt&insight_admin_password=myPassword1&db2_admin_password=myPassword2&report_user_password=myPassword3",
"application/x-www-form-urlencoded", false);
httpRequest,
"location=location&imageID=22&name=name&instanceType=instanceType&ip=1&publicKey=MOO&volumeID=2&oss.storage.id.0.mnt=%2Fmnt&insight_admin_password=myPassword1&db2_admin_password=myPassword2&report_user_password=myPassword3",
"application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, GetFirstInstanceInList.class);
assertSaxResponseParserClassEquals(method, null);
@ -519,7 +520,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, null, null, false);
@ -536,13 +537,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseSax.class);
assertSaxResponseParserClassEquals(method, LocationsHandler.class);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -553,7 +554,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false);
@ -570,13 +571,13 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, ParseAddressesFromJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
@ -587,7 +588,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1", "application/x-www-form-urlencoded", false);
@ -604,7 +605,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
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, "");
assertPayloadEquals(httpRequest, null, null, false);

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.rackspace.cloudservers;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import javax.ws.rs.Consumes;
@ -64,6 +64,7 @@ import org.jclouds.rest.annotations.QueryParams;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
@ -73,14 +74,12 @@ import com.google.common.util.concurrent.ListenableFuture;
/**
* Provides asynchronous access to Cloud Servers via their REST API.
* <p/>
* All commands return a ListenableFuture of the result from Cloud Servers. Any
* exceptions incurred during processing will be wrapped in an
* {@link ExecutionException} as documented in {@link ListenableFuture#get()}.
* All commands return a ListenableFuture of the result from Cloud Servers. Any exceptions incurred
* during processing will be wrapped in an {@link ExecutionException} as documented in
* {@link ListenableFuture#get()}.
*
* @see CloudServersClient
* @see <a
* href="http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf"
* />
* @see <a href="http://docs.rackspacecloud.com/servers/api/cs-devguide-latest.pdf" />
* @author Adrian Cole
*/
@SkipEncoding( { '/', '=' })
@ -96,7 +95,8 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers")
ListenableFuture<? extends List<Server>> listServers(ListOptions... options);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Server>> listServers(ListOptions... options);
/**
* @see CloudServersClient#getServer
@ -124,7 +124,7 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
ListenableFuture<Void> rebootServer(@PathParam("id") int id,
@BinderParam(BindRebootTypeToJsonPayload.class) RebootType rebootType);
@BinderParam(BindRebootTypeToJsonPayload.class) RebootType rebootType);
/**
* @see CloudServersClient#resizeServer
@ -133,7 +133,7 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
ListenableFuture<Void> resizeServer(@PathParam("id") int id,
@BinderParam(BindResizeFlavorToJsonPayload.class) int flavorId);
@BinderParam(BindResizeFlavorToJsonPayload.class) int flavorId);
/**
* @see CloudServersClient#confirmResizeServer
@ -142,8 +142,7 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
ListenableFuture<Void> confirmResizeServer(
@PathParam("id") @BinderParam(BindConfirmResizeToJsonPayload.class) int id);
ListenableFuture<Void> confirmResizeServer(@PathParam("id") @BinderParam(BindConfirmResizeToJsonPayload.class) int id);
/**
* @see CloudServersClient#revertResizeServer
@ -152,8 +151,7 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@Produces(MediaType.APPLICATION_JSON)
ListenableFuture<Void> revertResizeServer(
@PathParam("id") @BinderParam(BindRevertResizeToJsonPayload.class) int id);
ListenableFuture<Void> revertResizeServer(@PathParam("id") @BinderParam(BindRevertResizeToJsonPayload.class) int id);
/**
* @see CloudServersClient#createServer
@ -164,10 +162,8 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers")
@MapBinder(CreateServerOptions.class)
ListenableFuture<Server> createServer(@MapPayloadParam("name") String name,
@MapPayloadParam("imageId") int imageId,
@MapPayloadParam("flavorId") int flavorId,
CreateServerOptions... options);
ListenableFuture<Server> createServer(@MapPayloadParam("name") String name, @MapPayloadParam("imageId") int imageId,
@MapPayloadParam("flavorId") int flavorId, CreateServerOptions... options);
/**
* @see CloudServersClient#rebuildServer
@ -176,8 +172,7 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/action")
@MapBinder(RebuildServerOptions.class)
ListenableFuture<Void> rebuildServer(@PathParam("id") int id,
RebuildServerOptions... options);
ListenableFuture<Void> rebuildServer(@PathParam("id") int id, RebuildServerOptions... options);
/**
* @see CloudServersClient#shareIp
@ -186,9 +181,8 @@ public interface CloudServersAsyncClient {
@Path("/servers/{id}/ips/public/{address}")
@MapBinder(BindSharedIpGroupToJsonPayload.class)
ListenableFuture<Void> shareIp(@PathParam("address") String addressToShare,
@PathParam("id") int serverToTosignBindressTo,
@MapPayloadParam("sharedIpGroupId") int sharedIpGroup,
@MapPayloadParam("configureServer") boolean configureServer);
@PathParam("id") int serverToTosignBindressTo, @MapPayloadParam("sharedIpGroupId") int sharedIpGroup,
@MapPayloadParam("configureServer") boolean configureServer);
/**
* @see CloudServersClient#unshareIp
@ -196,9 +190,8 @@ public interface CloudServersAsyncClient {
@DELETE
@Path("/servers/{id}/ips/public/{address}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> unshareIp(
@PathParam("address") String addressToShare,
@PathParam("id") int serverToTosignBindressTo);
ListenableFuture<Void> unshareIp(@PathParam("address") String addressToShare,
@PathParam("id") int serverToTosignBindressTo);
/**
* @see CloudServersClient#changeAdminPass
@ -206,7 +199,7 @@ public interface CloudServersAsyncClient {
@PUT
@Path("/servers/{id}")
ListenableFuture<Void> changeAdminPass(@PathParam("id") int id,
@BinderParam(BindAdminPassToJsonPayload.class) String adminPass);
@BinderParam(BindAdminPassToJsonPayload.class) String adminPass);
/**
* @see CloudServersClient#renameServer
@ -214,7 +207,7 @@ public interface CloudServersAsyncClient {
@PUT
@Path("/servers/{id}")
ListenableFuture<Void> renameServer(@PathParam("id") int id,
@BinderParam(BindServerNameToJsonPayload.class) String newName);
@BinderParam(BindServerNameToJsonPayload.class) String newName);
/**
* @see CloudServersClient#listFlavors
@ -224,7 +217,8 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/flavors")
ListenableFuture<? extends List<Flavor>> listFlavors(ListOptions... options);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Flavor>> listFlavors(ListOptions... options);
/**
* @see CloudServersClient#getFlavor
@ -245,7 +239,8 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/images")
ListenableFuture<? extends List<Image>> listImages(ListOptions... options);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<Image>> listImages(ListOptions... options);
/**
* @see CloudServersClient#getImage
@ -275,9 +270,8 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@MapBinder(BindCreateImageToJsonPayload.class)
@Path("/images")
ListenableFuture<Image> createImageFromServer(
@MapPayloadParam("imageName") String imageName,
@MapPayloadParam("serverId") int serverId);
ListenableFuture<Image> createImageFromServer(@MapPayloadParam("imageName") String imageName,
@MapPayloadParam("serverId") int serverId);
/**
* @see CloudServersClient#listSharedIpGroups
@ -287,8 +281,8 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
ListenableFuture<? extends List<SharedIpGroup>> listSharedIpGroups(
ListOptions... options);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<SharedIpGroup>> listSharedIpGroups(ListOptions... options);
/**
* @see CloudServersClient#getSharedIpGroup
@ -310,9 +304,8 @@ public interface CloudServersAsyncClient {
@QueryParams(keys = "format", values = "json")
@Path("/shared_ip_groups")
@MapBinder(CreateSharedIpGroupOptions.class)
ListenableFuture<SharedIpGroup> createSharedIpGroup(
@MapPayloadParam("name") String name,
CreateSharedIpGroupOptions... options);
ListenableFuture<SharedIpGroup> createSharedIpGroup(@MapPayloadParam("name") String name,
CreateSharedIpGroupOptions... options);
/**
* @see CloudServersClient#deleteSharedIpGroup
@ -330,8 +323,7 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/backup_schedule")
ListenableFuture<BackupSchedule> getBackupSchedule(
@PathParam("id") int serverId);
ListenableFuture<BackupSchedule> getBackupSchedule(@PathParam("id") int serverId);
/**
* @see CloudServersClient#deleteBackupSchedule
@ -347,9 +339,8 @@ public interface CloudServersAsyncClient {
@POST
@ExceptionParser(ReturnFalseOn404.class)
@Path("/servers/{id}/backup_schedule")
ListenableFuture<Void> replaceBackupSchedule(
@PathParam("id") int id,
@BinderParam(BindBackupScheduleToJsonPayload.class) BackupSchedule backupSchedule);
ListenableFuture<Void> replaceBackupSchedule(@PathParam("id") int id,
@BinderParam(BindBackupScheduleToJsonPayload.class) BackupSchedule backupSchedule);
/**
* @see CloudServersClient#listAddresses
@ -369,8 +360,8 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/public")
ListenableFuture<? extends List<String>> listPublicAddresses(
@PathParam("id") int serverId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPublicAddresses(@PathParam("id") int serverId);
/**
* @see CloudServersClient#listPrivateAddresses
@ -380,7 +371,7 @@ public interface CloudServersAsyncClient {
@Consumes(MediaType.APPLICATION_JSON)
@QueryParams(keys = "format", values = "json")
@Path("/servers/{id}/ips/private")
ListenableFuture<? extends List<String>> listPrivateAddresses(
@PathParam("id") int serverId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<String>> listPrivateAddresses(@PathParam("id") int serverId);
}

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.rackspace.cloudservers;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
@ -64,7 +64,7 @@ public interface CloudServersClient {
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
List<Server> listServers(ListOptions... options);
Set<Server> listServers(ListOptions... options);
/**
*
@ -231,7 +231,7 @@ public interface CloudServersClient {
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
List<Flavor> listFlavors(ListOptions... options);
Set<Flavor> listFlavors(ListOptions... options);
/**
*
@ -249,7 +249,7 @@ public interface CloudServersClient {
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
List<Image> listImages(ListOptions... options);
Set<Image> listImages(ListOptions... options);
/**
*
@ -302,7 +302,7 @@ public interface CloudServersClient {
* in order to retrieve all details, pass the option {@link ListOptions#withDetails()
* withDetails()}
*/
List<SharedIpGroup> listSharedIpGroups(ListOptions... options);
Set<SharedIpGroup> listSharedIpGroups(ListOptions... options);
/**
*
@ -358,25 +358,22 @@ public interface CloudServersClient {
/**
* List all server addresses
*
* @throws ResourceNotFoundException
* , if the server doesn't exist
* returns empty set if the server doesn't exist
*/
Addresses getAddresses(int serverId);
/**
* List all public server addresses
*
* @throws ResourceNotFoundException
* , if the server doesn't exist
* returns empty set if the server doesn't exist
*/
List<String> listPublicAddresses(int serverId);
Set<String> listPublicAddresses(int serverId);
/**
* List all private server addresses
*
* @throws ResourceNotFoundException
* , if the server doesn't exist
* returns empty set if the server doesn't exist
*/
List<String> listPrivateAddresses(int serverId);
Set<String> listPrivateAddresses(int serverId);
}

View File

@ -54,6 +54,8 @@ import org.jclouds.rackspace.filters.AuthenticateRequest;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
@ -73,17 +75,17 @@ import com.google.inject.TypeLiteral;
public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyncClient> {
private static final Class<? extends ListOptions[]> listOptionsVarargsClass = new ListOptions[] {}.getClass();
private static final Class<? extends CreateServerOptions[]> createServerOptionsVarargsClass = new CreateServerOptions[] {}
.getClass();
.getClass();
public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}",
"application/json", false);
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -95,14 +97,14 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withSharedIpGroup(2));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}",
"application/json", false);
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -113,16 +115,16 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
createServerOptionsVarargsClass);
HttpRequest request = processor
.createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes()));
.createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes()));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"application/json", false);
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -134,15 +136,15 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1,
withMetadata(ImmutableMap.of("foo", "bar")));
withMetadata(ImmutableMap.of("foo", "bar")));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"application/json", false);
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -153,18 +155,18 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
}
public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
UnknownHostException {
Method method = CloudServersAsyncClient.class.getMethod("createServer", String.class, int.class, int.class,
createServerOptionsVarargsClass);
createServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withSharedIpGroup(2).withSharedIp(
"127.0.0.1"));
"127.0.0.1"));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
"application/json", false);
request,
"{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"sharedIpGroupId\":2,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}",
"application/json", false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -198,7 +200,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -210,13 +212,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -231,7 +233,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -261,7 +263,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -271,13 +273,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -292,7 +294,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -302,13 +304,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/flavors/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/flavors/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -338,7 +340,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -353,7 +355,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -363,13 +365,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -379,13 +381,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/images/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/images/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -422,7 +424,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Method method = CloudServersAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class,
boolean.class);
boolean.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false);
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1");
@ -439,13 +441,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException {
Method method = CloudServersAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class,
boolean.class);
boolean.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, true);
assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":true}}",
MediaType.APPLICATION_JSON, false);
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
@ -456,7 +458,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
}
public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException,
UnknownHostException {
UnknownHostException {
Method method = CloudServersAsyncClient.class.getMethod("unshareIp", String.class, int.class);
HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false);
@ -475,13 +477,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("replaceBackupSchedule", int.class, BackupSchedule.class);
HttpRequest request = processor.createRequest(method, 2, new BackupSchedule(WeeklyBackup.MONDAY,
DailyBackup.H_0800_1000, true));
DailyBackup.H_0800_1000, true));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/backup_schedule HTTP/1.1");
assertNonPayloadHeadersEqual(request, "");
assertPayloadEquals(request,
"{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}",
MediaType.APPLICATION_JSON, false);
"{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}",
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class);
assertSaxResponseParserClassEquals(method, null);
@ -549,7 +551,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -559,13 +561,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/shared_ip_groups?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/shared_ip_groups?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -580,7 +582,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -590,13 +592,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2));
assertRequestLineEquals(request,
"GET http://serverManagementUrl/shared_ip_groups/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
"GET http://serverManagementUrl/shared_ip_groups/detail?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -617,11 +619,11 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
}
private static final Class<? extends CreateSharedIpGroupOptions[]> createSharedIpGroupOptionsVarargsClass = new CreateSharedIpGroupOptions[] {}
.getClass();
.getClass();
public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass);
createSharedIpGroupOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie");
assertRequestLineEquals(request, "POST http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1");
@ -638,13 +640,13 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("createSharedIpGroup", String.class,
createSharedIpGroupOptionsVarargsClass);
createSharedIpGroupOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, "ralphie", withServer(2));
assertRequestLineEquals(request, "POST http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\",\"server\":2}}",
MediaType.APPLICATION_JSON, false);
MediaType.APPLICATION_JSON, false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -693,7 +695,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -708,7 +710,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -723,7 +725,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class);
checkFilters(request);
}
@ -735,7 +737,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
assertRequestLineEquals(request, "POST http://serverManagementUrl/images?format=json HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/json\n");
assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON,
false);
false);
assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
@ -746,11 +748,11 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
}
private static final Class<? extends RebuildServerOptions[]> rebuildServerOptionsVarargsClass = new RebuildServerOptions[] {}
.getClass();
.getClass();
public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass);
rebuildServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, 3);
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1");
@ -766,7 +768,7 @@ public class CloudServersAsyncClientTest extends RestClientTest<CloudServersAsyn
public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException {
Method method = CloudServersAsyncClient.class.getMethod("rebuildServer", int.class,
rebuildServerOptionsVarargsClass);
rebuildServerOptionsVarargsClass);
HttpRequest request = processor.createRequest(method, 3, withImage(2));
assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1");

View File

@ -30,9 +30,9 @@ import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.security.SecureRandom;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.http.HttpResponseException;
@ -86,10 +86,9 @@ public class CloudServersClientLiveTest {
String identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
Injector injector = new RestContextFactory().createContextBuilder("cloudservers", identity,
credential,
ImmutableSet.<Module> of(new Log4JLoggingModule(), new JschSshClientModule()),
new Properties()).buildInjector();
Injector injector = new RestContextFactory().createContextBuilder("cloudservers", identity, credential,
ImmutableSet.<Module> of(new Log4JLoggingModule(), new JschSshClientModule()), new Properties())
.buildInjector();
client = injector.getInstance(CloudServersClient.class);
sshFactory = injector.getInstance(SshClient.Factory.class);
@ -100,7 +99,7 @@ public class CloudServersClientLiveTest {
public void testListServers() throws Exception {
List<Server> response = client.listServers();
Set<Server> response = client.listServers();
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
@ -108,14 +107,14 @@ public class CloudServersClientLiveTest {
}
public void testListServersDetail() throws Exception {
List<Server> response = client.listServers(withDetails());
Set<Server> response = client.listServers(withDetails());
assert null != response;
long initialContainerCount = response.size();
assertTrue(initialContainerCount >= 0);
}
public void testListImages() throws Exception {
List<Image> response = client.listImages();
Set<Image> response = client.listImages();
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 1);
@ -127,7 +126,7 @@ public class CloudServersClientLiveTest {
}
public void testListImagesDetail() throws Exception {
List<Image> response = client.listImages(withDetails());
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
@ -139,7 +138,7 @@ public class CloudServersClientLiveTest {
}
public void testGetImagesDetail() throws Exception {
List<Image> response = client.listImages(withDetails());
Set<Image> response = client.listImages(withDetails());
assert null != response;
long imageCount = response.size();
assertTrue(imageCount >= 0);
@ -165,7 +164,7 @@ public class CloudServersClientLiveTest {
}
public void testGetServersDetail() throws Exception {
List<Server> response = client.listServers(withDetails());
Set<Server> response = client.listServers(withDetails());
assert null != response;
long serverCount = response.size();
assertTrue(serverCount >= 0);
@ -176,7 +175,7 @@ public class CloudServersClientLiveTest {
}
public void testListFlavors() throws Exception {
List<Flavor> response = client.listFlavors();
Set<Flavor> response = client.listFlavors();
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 1);
@ -188,7 +187,7 @@ public class CloudServersClientLiveTest {
}
public void testListFlavorsDetail() throws Exception {
List<Flavor> response = client.listFlavors(withDetails());
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
@ -201,7 +200,7 @@ public class CloudServersClientLiveTest {
}
public void testGetFlavorsDetail() throws Exception {
List<Flavor> response = client.listFlavors(withDetails());
Set<Flavor> response = client.listFlavors(withDetails());
assert null != response;
long flavorCount = response.size();
assertTrue(flavorCount >= 0);
@ -217,7 +216,7 @@ public class CloudServersClientLiveTest {
}
public void testListSharedIpGroups() throws Exception {
List<SharedIpGroup> response = client.listSharedIpGroups();
Set<SharedIpGroup> response = client.listSharedIpGroups();
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
@ -229,7 +228,7 @@ public class CloudServersClientLiveTest {
}
public void testListSharedIpGroupsDetail() throws Exception {
List<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
@ -241,7 +240,7 @@ public class CloudServersClientLiveTest {
}
public void testGetSharedIpGroupsDetail() throws Exception {
List<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
Set<SharedIpGroup> response = client.listSharedIpGroups(withDetails());
assert null != response;
long sharedIpGroupCount = response.size();
assertTrue(sharedIpGroupCount >= 0);
@ -260,8 +259,7 @@ public class CloudServersClientLiveTest {
public void testCreateSharedIpGroup() throws Exception {
SharedIpGroup sharedIpGroup = null;
while (sharedIpGroup == null) {
String sharedIpGroupName = serverPrefix + "createSharedIpGroup"
+ new SecureRandom().nextInt();
String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt();
try {
sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId));
} catch (UndeclaredThrowableException e) {
@ -296,8 +294,8 @@ public class CloudServersClientLiveTest {
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client.createServer(serverName, imageId, flavorId, withFile(
"/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata));
server = client.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt",
"rackspace".getBytes()).withMetadata(metadata));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
@ -355,8 +353,7 @@ public class CloudServersClientLiveTest {
assertEquals(server.getAddresses().getPublicAddresses().size(), 1);
assertEquals(client.listPublicAddresses(serverId), server.getAddresses().getPublicAddresses());
assertEquals(server.getAddresses().getPrivateAddresses().size(), 1);
assertEquals(client.listPrivateAddresses(serverId), server.getAddresses()
.getPrivateAddresses());
assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses());
// check metadata
assertEquals(server.getMetadata(), metadata);
@ -380,8 +377,7 @@ public class CloudServersClientLiveTest {
}
private void doCheckPass(Server newDetails, String pass) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(),
0), 22);
IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, "root", pass);
@ -397,8 +393,7 @@ public class CloudServersClientLiveTest {
}
private ExecResponse exec(Server details, String pass, String command) throws IOException {
IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0),
22);
IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22);
socketTester.apply(socket);
SshClient client = sshFactory.create(socket, "root", pass);
try {
@ -435,9 +430,9 @@ public class CloudServersClientLiveTest {
while (server == null) {
String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt();
try {
server = client.createServer(serverName, imageId, flavorId, withFile(
"/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata)
.withSharedIpGroup(sharedIpGroupId).withSharedIp(ip));
server = client
.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt", "rackspace".getBytes())
.withMetadata(metadata).withSharedIpGroup(sharedIpGroupId).withSharedIp(ip));
} catch (UndeclaredThrowableException e) {
HttpResponseException htpe = (HttpResponseException) e.getCause().getCause();
if (htpe.getResponse().getStatusCode() == 400)
@ -450,16 +445,15 @@ public class CloudServersClientLiveTest {
adminPass2 = server.getAdminPass();
blockUntilServerActive(serverId2);
assertIpConfigured(server, adminPass2);
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses()
+ " doesn't contain " + ip;
assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses() + " doesn't contain " + ip;
assertEquals(server.getSharedIpGroupId(), new Integer(sharedIpGroupId));
}
private void assertIpConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) > 0 : String.format(
"server %s didn't get ip %s%n%s", server, ip, response);
assert response.getOutput().indexOf(ip) > 0 : String.format("server %s didn't get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
@ -479,8 +473,8 @@ public class CloudServersClientLiveTest {
private void assertIpNotConfigured(Server server, String password) {
try {
ExecResponse response = exec(server, password, "ifconfig -a");
assert response.getOutput().indexOf(ip) == -1 : String.format(
"server %s still has get ip %s%n%s", server, ip, response);
assert response.getOutput().indexOf(ip) == -1 : String.format("server %s still has get ip %s%n%s", server, ip,
response);
} catch (Exception e) {
e.printStackTrace();
} catch (AssertionError e) {
@ -568,8 +562,8 @@ public class CloudServersClientLiveTest {
assertEquals(new Integer(2), client.getServer(serverId2).getFlavorId());
}
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "testRebootSoft",
"testRevertResize", "testConfirmResize" })
@Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "testRebootSoft", "testRevertResize",
"testConfirmResize" })
void deleteServer2() {
if (serverId2 > 0) {
client.deleteServer(serverId2);

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.twitter;
import java.util.SortedSet;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@ -26,7 +26,9 @@ import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.rest.annotations.ExceptionParser;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.twitter.domain.Status;
import com.google.common.util.concurrent.ListenableFuture;
@ -48,6 +50,7 @@ public interface TwitterAsyncClient {
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Path("/statuses/mentions.json")
ListenableFuture<SortedSet<Status>> getMyMentions();
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<Status>> getMyMentions();
}

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.twitter;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
@ -35,6 +35,6 @@ import org.jclouds.twitter.domain.Status;
@Timeout(duration = 4, timeUnit = TimeUnit.SECONDS)
public interface TwitterClient {
SortedSet<Status> getMyMentions();
Set<Status> getMyMentions();
}

View File

@ -29,6 +29,7 @@ import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.functions.ParseJson;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
import org.testng.annotations.Test;
@ -52,7 +53,7 @@ public class TwitterAsyncClientTest extends RestClientTest<TwitterAsyncClient> {
assertResponseParserClassEquals(method, request, ParseJson.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -72,7 +73,7 @@ public class TwitterAsyncClientTest extends RestClientTest<TwitterAsyncClient> {
@Override
public ContextSpec<TwitterClient, TwitterAsyncClient> createContextSpec() {
return contextSpec("test", "http://twitter.com", "1", "identity", "credential", TwitterClient.class,
TwitterAsyncClient.class);
TwitterAsyncClient.class);
}
}

View File

@ -22,7 +22,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
import static org.jclouds.rest.RestContextFactory.contextSpec;
import static org.jclouds.rest.RestContextFactory.createContext;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -49,21 +49,18 @@ public class TwitterClientLiveTest {
@BeforeGroups(groups = "live")
public void setupClient() throws InterruptedException, ExecutionException, TimeoutException {
String identity = checkNotNull(System.getProperty("jclouds.test.identity"),
"jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"),
"jclouds.test.credential");
String identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
context = createContext(contextSpec("twitter", "http://twitter.com", "1", identity,
credential, TwitterClient.class, TwitterAsyncClient.class), ImmutableSet
.<Module> of(new Log4JLoggingModule()));
context = createContext(contextSpec("twitter", "http://twitter.com", "1", identity, credential,
TwitterClient.class, TwitterAsyncClient.class), ImmutableSet.<Module> of(new Log4JLoggingModule()));
connection = context.getApi();
}
@Test
public void testGetMyMentions() throws Exception {
SortedSet<Status> response = connection.getMyMentions();
Set<Status> response = connection.getMyMentions();
assert (response.size() > 0);
}

View File

@ -39,9 +39,9 @@ public class ResourceAllocation implements Comparable<ResourceAllocation> {
private final long virtualQuantity;
private final String virtualQuantityUnits;
public ResourceAllocation(int id, String name, String description, ResourceType type,
String subType, String hostResource, Integer address, Integer addressOnParent,
Integer parent, Boolean connected, long virtualQuantity, String virtualQuantityUnits) {
public ResourceAllocation(int id, String name, String description, ResourceType type, String subType,
String hostResource, Integer address, Integer addressOnParent, Integer parent, Boolean connected,
long virtualQuantity, String virtualQuantityUnits) {
this.id = id;
this.name = checkNotNull(name, "name");
this.description = description;
@ -126,104 +126,96 @@ public class ResourceAllocation implements Comparable<ResourceAllocation> {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result
+ ((addressOnParent == null) ? 0 : addressOnParent.hashCode());
result = prime * result + ((connected == null) ? 0 : connected.hashCode());
result = prime * result
+ ((description == null) ? 0 : description.hashCode());
result = prime * result
+ ((hostResource == null) ? 0 : hostResource.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
result = prime * result + ((subType == null) ? 0 : subType.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result
+ (int) (virtualQuantity ^ (virtualQuantity >>> 32));
result = prime
* result
+ ((virtualQuantityUnits == null) ? 0 : virtualQuantityUnits
.hashCode());
return result;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((address == null) ? 0 : address.hashCode());
result = prime * result + ((addressOnParent == null) ? 0 : addressOnParent.hashCode());
result = prime * result + ((connected == null) ? 0 : connected.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((hostResource == null) ? 0 : hostResource.hashCode());
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((parent == null) ? 0 : parent.hashCode());
result = prime * result + ((subType == null) ? 0 : subType.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
result = prime * result + (int) (virtualQuantity ^ (virtualQuantity >>> 32));
result = prime * result + ((virtualQuantityUnits == null) ? 0 : virtualQuantityUnits.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;
ResourceAllocation other = (ResourceAllocation) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (addressOnParent == null) {
if (other.addressOnParent != null)
return false;
} else if (!addressOnParent.equals(other.addressOnParent))
return false;
if (connected == null) {
if (other.connected != null)
return false;
} else if (!connected.equals(other.connected))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (hostResource == null) {
if (other.hostResource != null)
return false;
} else if (!hostResource.equals(other.hostResource))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (parent == null) {
if (other.parent != null)
return false;
} else if (!parent.equals(other.parent))
return false;
if (subType == null) {
if (other.subType != null)
return false;
} else if (!subType.equals(other.subType))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (virtualQuantity != other.virtualQuantity)
return false;
if (virtualQuantityUnits == null) {
if (other.virtualQuantityUnits != null)
return false;
} else if (!virtualQuantityUnits.equals(other.virtualQuantityUnits))
return false;
return true;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResourceAllocation other = (ResourceAllocation) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
if (addressOnParent == null) {
if (other.addressOnParent != null)
return false;
} else if (!addressOnParent.equals(other.addressOnParent))
return false;
if (connected == null) {
if (other.connected != null)
return false;
} else if (!connected.equals(other.connected))
return false;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (hostResource == null) {
if (other.hostResource != null)
return false;
} else if (!hostResource.equals(other.hostResource))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (parent == null) {
if (other.parent != null)
return false;
} else if (!parent.equals(other.parent))
return false;
if (subType == null) {
if (other.subType != null)
return false;
} else if (!subType.equals(other.subType))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
if (virtualQuantity != other.virtualQuantity)
return false;
if (virtualQuantityUnits == null) {
if (other.virtualQuantityUnits != null)
return false;
} else if (!virtualQuantityUnits.equals(other.virtualQuantityUnits))
return false;
return true;
}
@Override
public String toString() {
return "ResourceAllocation [address=" + address + ", addressOnParent=" + addressOnParent
+ ", connected=" + connected + ", description=" + description + ", hostResource="
+ hostResource + ", id=" + id + ", name=" + name + ", parent=" + parent
+ ", subType=" + subType + ", type=" + type + ", virtualQuantity=" + virtualQuantity
+ ", virtualQuantityUnits=" + virtualQuantityUnits + "]";
return "ResourceAllocation [address=" + address + ", addressOnParent=" + addressOnParent + ", connected="
+ connected + ", description=" + description + ", hostResource=" + hostResource + ", id=" + id
+ ", name=" + name + ", parent=" + parent + ", subType=" + subType + ", type=" + type
+ ", virtualQuantity=" + virtualQuantity + ", virtualQuantityUnits=" + virtualQuantityUnits + "]";
}
}

View File

@ -21,7 +21,7 @@ package org.jclouds.vcloud.terremark;
import static org.jclouds.vcloud.terremark.TerremarkECloudMediaType.INTERNETSERVICESLIST_XML;
import static org.jclouds.vcloud.terremark.TerremarkECloudMediaType.INTERNETSERVICE_XML;
import java.util.SortedSet;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
@ -36,6 +36,7 @@ import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.MapPayloadParam;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.vcloud.filters.SetVCloudTokenCookie;
import org.jclouds.vcloud.terremark.domain.InternetService;
@ -67,10 +68,9 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient {
@XMLResponseParser(InternetServiceHandler.class)
@MapBinder(AddInternetServiceOptions.class)
@Override
ListenableFuture<? extends InternetService> addInternetServiceToVDC(
@PathParam("vDCId") String vDCId, @MapPayloadParam("name") String serviceName,
@MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port,
AddInternetServiceOptions... options);
ListenableFuture<? extends InternetService> addInternetServiceToVDC(@PathParam("vDCId") String vDCId,
@MapPayloadParam("name") String serviceName, @MapPayloadParam("protocol") Protocol protocol,
@MapPayloadParam("port") int port, AddInternetServiceOptions... options);
/**
* @see TerremarkVCloudExpressClient#getAllInternetServices
@ -81,8 +81,7 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient {
@Consumes(INTERNETSERVICESLIST_XML)
@XMLResponseParser(InternetServicesHandler.class)
@Override
ListenableFuture<? extends SortedSet<InternetService>> getAllInternetServicesInVDC(
@PathParam("vDCId") String vDCId);
ListenableFuture<? extends Set<InternetService>> getAllInternetServicesInVDC(@PathParam("vDCId") String vDCId);
/**
* @see TerremarkVCloudExpressClient#addInternetServiceToExistingIp
@ -95,10 +94,9 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient {
@XMLResponseParser(InternetServiceHandler.class)
@MapBinder(AddInternetServiceOptions.class)
@Override
ListenableFuture<? extends InternetService> addInternetServiceToExistingIp(
@PathParam("ipId") int existingIpId, @MapPayloadParam("name") String serviceName,
@MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port,
AddInternetServiceOptions... options);
ListenableFuture<? extends InternetService> addInternetServiceToExistingIp(@PathParam("ipId") int existingIpId,
@MapPayloadParam("name") String serviceName, @MapPayloadParam("protocol") Protocol protocol,
@MapPayloadParam("port") int port, AddInternetServiceOptions... options);
/**
* @see TerremarkVCloudExpressClient#getInternetServicesOnPublicIP
@ -108,9 +106,9 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient {
@Path("/extensions/publicIp/{ipId}/internetServices")
@Consumes(INTERNETSERVICESLIST_XML)
@XMLResponseParser(InternetServicesHandler.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Override
ListenableFuture<? extends SortedSet<InternetService>> getInternetServicesOnPublicIp(
@PathParam("ipId") int ipId);
ListenableFuture<? extends Set<InternetService>> getInternetServicesOnPublicIp(@PathParam("ipId") int ipId);
/**
* @see TerremarkVCloudExpressClient#getInternetService
@ -122,7 +120,6 @@ public interface TerremarkECloudAsyncClient extends TerremarkVCloudAsyncClient {
@XMLResponseParser(InternetServiceHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Override
ListenableFuture<? extends InternetService> getInternetService(
@PathParam("internetServiceId") int internetServiceId);
ListenableFuture<? extends InternetService> getInternetService(@PathParam("internetServiceId") int internetServiceId);
}

View File

@ -29,7 +29,7 @@ import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.NODESERVICE_
import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.PUBLICIPSLIST_XML;
import static org.jclouds.vcloud.terremark.TerremarkVCloudMediaType.PUBLICIP_XML;
import java.util.SortedSet;
import java.util.Set;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@ -51,6 +51,7 @@ import org.jclouds.rest.annotations.ParamValidators;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.vcloud.VCloudAsyncClient;
@ -75,7 +76,6 @@ import org.jclouds.vcloud.terremark.domain.PublicIpAddress;
import org.jclouds.vcloud.terremark.domain.TerremarkOrganization;
import org.jclouds.vcloud.terremark.domain.VAppConfiguration;
import org.jclouds.vcloud.terremark.functions.ParseTaskFromLocationHeader;
import org.jclouds.vcloud.terremark.functions.ReturnEmptySetOnResourceNotFoundException;
import org.jclouds.vcloud.terremark.functions.ReturnVoidOnDeleteDefaultIp;
import org.jclouds.vcloud.terremark.options.AddInternetServiceOptions;
import org.jclouds.vcloud.terremark.options.AddNodeOptions;
@ -91,6 +91,7 @@ import org.jclouds.vcloud.xml.CatalogHandler;
import org.jclouds.vcloud.xml.VAppHandler;
import com.google.common.util.concurrent.ListenableFuture;
/**
* Provides access to VCloud resources via their REST API.
* <p/>
@ -113,8 +114,7 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@XMLResponseParser(TerremarkOrgHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Consumes(ORG_XML)
ListenableFuture<? extends TerremarkOrganization> getOrganization(
@PathParam("orgId") String orgId);
ListenableFuture<? extends TerremarkOrganization> getOrganization(@PathParam("orgId") String orgId);
/**
* @see TerremarkVCloudExpressClient#getDefaultVDC
@ -171,10 +171,9 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Consumes(INTERNETSERVICE_XML)
@XMLResponseParser(InternetServiceHandler.class)
@MapBinder(AddInternetServiceOptions.class)
ListenableFuture<? extends InternetService> addInternetServiceToVDC(
@PathParam("vDCId") String vDCId, @MapPayloadParam("name") String serviceName,
@MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port,
AddInternetServiceOptions... options);
ListenableFuture<? extends InternetService> addInternetServiceToVDC(@PathParam("vDCId") String vDCId,
@MapPayloadParam("name") String serviceName, @MapPayloadParam("protocol") Protocol protocol,
@MapPayloadParam("port") int port, AddInternetServiceOptions... options);
/**
* @see TerremarkVCloudExpressClient#getAllInternetServices
@ -184,8 +183,8 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Path("/extensions/vdc/{vDCId}/internetServices")
@Consumes(INTERNETSERVICESLIST_XML)
@XMLResponseParser(InternetServicesHandler.class)
ListenableFuture<? extends SortedSet<InternetService>> getAllInternetServicesInVDC(
@PathParam("vDCId") String vDCId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<InternetService>> getAllInternetServicesInVDC(@PathParam("vDCId") String vDCId);
/**
* @see TerremarkVCloudExpressClient#addInternetServiceToExistingIp
@ -197,10 +196,9 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Consumes(INTERNETSERVICE_XML)
@XMLResponseParser(InternetServiceHandler.class)
@MapBinder(AddInternetServiceOptions.class)
ListenableFuture<? extends InternetService> addInternetServiceToExistingIp(
@PathParam("ipId") int existingIpId, @MapPayloadParam("name") String serviceName,
@MapPayloadParam("protocol") Protocol protocol, @MapPayloadParam("port") int port,
AddInternetServiceOptions... options);
ListenableFuture<? extends InternetService> addInternetServiceToExistingIp(@PathParam("ipId") int existingIpId,
@MapPayloadParam("name") String serviceName, @MapPayloadParam("protocol") Protocol protocol,
@MapPayloadParam("port") int port, AddInternetServiceOptions... options);
/**
* @see TerremarkVCloudExpressClient#deletePublicIp
@ -219,8 +217,8 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Path("/extensions/publicIp/{ipId}/internetServices")
@Consumes(INTERNETSERVICESLIST_XML)
@XMLResponseParser(InternetServicesHandler.class)
ListenableFuture<? extends SortedSet<InternetService>> getInternetServicesOnPublicIp(
@PathParam("ipId") int ipId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<InternetService>> getInternetServicesOnPublicIp(@PathParam("ipId") int ipId);
/**
* @see TerremarkVCloudExpressClient#getPublicIp
@ -230,8 +228,8 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Path("/extensions/publicIp/{ipId}")
@Consumes(PUBLICIP_XML)
@XMLResponseParser(InternetServicesHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<? extends SortedSet<InternetService>> getPublicIp(@PathParam("ipId") int ipId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<InternetService>> getPublicIp(@PathParam("ipId") int ipId);
/**
* @see TerremarkVCloudExpressClient#getPublicIpsAssociatedWithVDC
@ -241,8 +239,8 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Path("/extensions/vdc/{vDCId}/publicIps")
@Consumes(PUBLICIPSLIST_XML)
@XMLResponseParser(PublicIpAddressesHandler.class)
ListenableFuture<? extends SortedSet<PublicIpAddress>> getPublicIpsAssociatedWithVDC(
@PathParam("vDCId") String vDCId);
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<PublicIpAddress>> getPublicIpsAssociatedWithVDC(@PathParam("vDCId") String vDCId);
/**
* @see TerremarkVCloudExpressClient#activatePublicIpInVDC
@ -261,8 +259,7 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class)
@Path("/extensions/internetService/{internetServiceId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteInternetService(
@PathParam("internetServiceId") int internetServiceId);
ListenableFuture<Void> deleteInternetService(@PathParam("internetServiceId") int internetServiceId);
/**
* @see TerremarkVCloudExpressClient#getInternetService
@ -273,8 +270,7 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Consumes(INTERNETSERVICESLIST_XML)
@XMLResponseParser(InternetServiceHandler.class)
@ExceptionParser(ReturnNullOnNotFoundOr404.class)
ListenableFuture<? extends InternetService> getInternetService(
@PathParam("internetServiceId") int internetServiceId);
ListenableFuture<? extends InternetService> getInternetService(@PathParam("internetServiceId") int internetServiceId);
/**
* @see TerremarkVCloudExpressClient#addNode
@ -297,10 +293,9 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Endpoint(org.jclouds.vcloud.endpoints.VCloudApi.class)
@Path("/extensions/internetService/{internetServiceId}/nodeServices")
@XMLResponseParser(NodesHandler.class)
@ExceptionParser(ReturnEmptySetOnResourceNotFoundException.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@Consumes(NODESERVICE_XML)
ListenableFuture<? extends SortedSet<Node>> getNodes(
@PathParam("internetServiceId") int internetServiceId);
ListenableFuture<? extends Set<Node>> getNodes(@PathParam("internetServiceId") int internetServiceId);
/**
* @see TerremarkVCloudExpressClient#getNode
@ -322,8 +317,7 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Produces(NODESERVICE_XML)
@Consumes(NODESERVICE_XML)
@XMLResponseParser(NodeHandler.class)
ListenableFuture<? extends Node> configureNode(
@PathParam("nodeId") int nodeId,
ListenableFuture<? extends Node> configureNode(@PathParam("nodeId") int nodeId,
@BinderParam(BindNodeConfigurationToXmlPayload.class) NodeConfiguration nodeConfiguration);
/**
@ -345,8 +339,7 @@ public interface TerremarkVCloudAsyncClient extends VCloudAsyncClient {
@Consumes(VAPP_XML)
@MapBinder(BindVAppConfigurationToXmlPayload.class)
@ResponseParser(ParseTaskFromLocationHeader.class)
ListenableFuture<? extends Task> configureVApp(
@PathParam("vAppId") @ParamParser(VAppId.class) VApp vApp,
ListenableFuture<? extends Task> configureVApp(@PathParam("vAppId") @ParamParser(VAppId.class) VApp vApp,
VAppConfiguration configuration);
/**

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.vcloud.terremark;
import java.util.SortedSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.jclouds.concurrent.Timeout;
@ -55,7 +55,7 @@ public interface TerremarkVCloudClient extends VCloudClient {
/**
* This call returns a list of public IP addresses.
*/
SortedSet<PublicIpAddress> getPublicIpsAssociatedWithVDC(String vDCId);
Set<PublicIpAddress> getPublicIpsAssociatedWithVDC(String vDCId);
void deletePublicIp(int ipId);
@ -87,14 +87,14 @@ public interface TerremarkVCloudClient extends VCloudClient {
InternetService getInternetService(int internetServiceId);
SortedSet<InternetService> getAllInternetServicesInVDC(String vDCId);
Set<InternetService> getAllInternetServicesInVDC(String vDCId);
/**
* This call returns information about the internet service on a public IP.
*/
SortedSet<InternetService> getInternetServicesOnPublicIp(int ipId);
Set<InternetService> getInternetServicesOnPublicIp(int ipId);
SortedSet<InternetService> getPublicIp(int ipId);
Set<InternetService> getPublicIp(int ipId);
/**
* This call adds a node to an existing internet service.
@ -119,7 +119,7 @@ public interface TerremarkVCloudClient extends VCloudClient {
void deleteNode(int nodeId);
SortedSet<Node> getNodes(int internetServiceId);
Set<Node> getNodes(int internetServiceId);
/**
* This call configures the settings of an existing vApp by passing the new configuration. The

View File

@ -37,6 +37,7 @@ import org.jclouds.rest.annotations.MapBinder;
import org.jclouds.rest.annotations.MapPayloadParam;
import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.vcloud.filters.SetVCloudTokenCookie;
@ -65,6 +66,7 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC
@Endpoint(KeysList.class)
@Consumes(KEYSLIST_XML)
@XMLResponseParser(KeyPairsHandler.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<KeyPair>> listKeyPairs();
/**
@ -75,6 +77,7 @@ public interface TerremarkVCloudExpressAsyncClient extends TerremarkVCloudAsyncC
@Path("/extensions/org/{orgId}/keys")
@Consumes(KEYSLIST_XML)
@XMLResponseParser(KeyPairsHandler.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<? extends Set<KeyPair>> listKeyPairsInOrg(@PathParam("orgId") String orgId);
/**

View File

@ -26,7 +26,6 @@ import java.util.LinkedHashMap;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
import java.util.SortedSet;
import javax.inject.Inject;
import javax.inject.Named;
@ -167,7 +166,7 @@ public class TerremarkVCloudComputeClient extends BaseVCloudComputeClient {
node.getPort());
client.deleteNode(node.getId());
logger.debug("<< deleted Node(%s)", node.getId());
SortedSet<Node> nodes = client.getNodes(service.getId());
Set<Node> nodes = client.getNodes(service.getId());
if (nodes.size() == 0) {
logger.debug(">> deleting InternetService(%s) %s:%d", service.getId(), service
.getPublicIpAddress().getAddress(), service.getPort());
@ -183,7 +182,7 @@ public class TerremarkVCloudComputeClient extends BaseVCloudComputeClient {
private void deletePublicIpAddressesWithNoServicesAttached(Set<PublicIpAddress> ipAddresses) {
IPADDRESS: for (PublicIpAddress address : ipAddresses) {
SortedSet<InternetService> services = client
Set<InternetService> services = client
.getInternetServicesOnPublicIp(address.getId());
if (services.size() == 0) {
logger.debug(">> deleting PublicIpAddress(%s) %s", address.getId(), address

View File

@ -82,7 +82,7 @@ public class VAppConfiguration {
* Ex.
*
* <pre>
* SortedSet&lt;ResourceAllocation&gt; disks = Sets.newTreeSet(vApp.getResourceAllocationByType().get(
* Set&lt;ResourceAllocation&gt; disks = Sets.newLinkedHashSet(vApp.getResourceAllocationByType().get(
* ResourceType.DISK_DRIVE));
* ResourceAllocation lastDisk = disks.last();
* VAppConfiguration config = deleteDiskWithAddressOnParent(lastDisk.getAddressOnParent());

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.vcloud.terremark.xml;
import java.util.SortedSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -34,12 +34,12 @@ import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class InternetServicesHandler extends HandlerWithResult<SortedSet<InternetService>> {
public class InternetServicesHandler extends HandlerWithResult<Set<InternetService>> {
@Resource
protected Logger logger = Logger.NULL;
private final InternetServiceHandler handler;
SortedSet<InternetService> result = Sets.newTreeSet();
Set<InternetService> result = Sets.newLinkedHashSet();
@Inject
public InternetServicesHandler(InternetServiceHandler handler) {
@ -47,7 +47,7 @@ public class InternetServicesHandler extends HandlerWithResult<SortedSet<Interne
}
@Override
public SortedSet<InternetService> getResult() {
public Set<InternetService> getResult() {
return result;
}

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.vcloud.terremark.xml;
import java.util.SortedSet;
import java.util.Set;
import javax.annotation.Nullable;
import javax.annotation.Resource;
@ -35,20 +35,20 @@ import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class IpAddressesHandler extends ParseSax.HandlerWithResult<SortedSet<IpAddress>> {
public class IpAddressesHandler extends ParseSax.HandlerWithResult<Set<IpAddress>> {
protected StringBuilder currentText = new StringBuilder();
@Resource
protected Logger logger = Logger.NULL;
private SortedSet<IpAddress> addresses = Sets.newTreeSet();
private Set<IpAddress> addresses = Sets.newLinkedHashSet();
private String address;
private Status status;
@Nullable
private String server;
private boolean skip;
public SortedSet<IpAddress> getResult() {
public Set<IpAddress> getResult() {
return addresses;
}

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.vcloud.terremark.xml;
import java.util.SortedSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -34,12 +34,12 @@ import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class NodesHandler extends HandlerWithResult<SortedSet<Node>> {
public class NodesHandler extends HandlerWithResult<Set<Node>> {
@Resource
protected Logger logger = Logger.NULL;
private final NodeHandler handler;
SortedSet<Node> result = Sets.newTreeSet();
Set<Node> result = Sets.newLinkedHashSet();
@Inject
public NodesHandler(NodeHandler handler) {
@ -47,7 +47,7 @@ public class NodesHandler extends HandlerWithResult<SortedSet<Node>> {
}
@Override
public SortedSet<Node> getResult() {
public Set<Node> getResult() {
return result;
}

View File

@ -18,7 +18,7 @@
*/
package org.jclouds.vcloud.terremark.xml;
import java.util.SortedSet;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
@ -34,12 +34,12 @@ import com.google.common.collect.Sets;
/**
* @author Adrian Cole
*/
public class PublicIpAddressesHandler extends HandlerWithResult<SortedSet<PublicIpAddress>> {
public class PublicIpAddressesHandler extends HandlerWithResult<Set<PublicIpAddress>> {
@Resource
protected Logger logger = Logger.NULL;
private final PublicIpAddressHandler handler;
SortedSet<PublicIpAddress> result = Sets.newTreeSet();
Set<PublicIpAddress> result = Sets.newLinkedHashSet();
@Inject
public PublicIpAddressesHandler(PublicIpAddressHandler handler) {
@ -47,7 +47,7 @@ public class PublicIpAddressesHandler extends HandlerWithResult<SortedSet<Public
}
@Override
public SortedSet<PublicIpAddress> getResult() {
public Set<PublicIpAddress> getResult() {
return result;
}

View File

@ -22,7 +22,6 @@ import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Properties;
import java.util.Set;
import java.util.SortedSet;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
@ -50,7 +49,7 @@ import com.google.inject.Module;
public class InternetServiceLiveTest {
TerremarkVCloudExpressClient tmClient;
private SortedSet<InternetService> services = Sets.newTreeSet();
private Set<InternetService> services = Sets.newLinkedHashSet();
private RestContext<TerremarkVCloudExpressClient, TerremarkVCloudExpressAsyncClient> context;
@ -61,7 +60,7 @@ public class InternetServiceLiveTest {
tmClient.getAllInternetServicesInVDC(tmClient.getDefaultVDC().getId());
}
private void delete(SortedSet<InternetService> set) {
private void delete(Set<InternetService> set) {
Set<Integer> publicIps = Sets.newHashSet();
for (InternetService service : set) {
for (Node node : tmClient.getNodes(service.getId())) {
@ -104,7 +103,7 @@ public class InternetServiceLiveTest {
}
void print(SortedSet<InternetService> set) {
void print(Set<InternetService> set) {
for (InternetService service : set) {
System.out.printf("%d (%s:%d%n)", service.getId(), service.getPublicIpAddress()
.getAddress(), service.getPort());

View File

@ -39,6 +39,7 @@ import org.jclouds.rest.ConfiguresRestClient;
import org.jclouds.rest.RestClientTest;
import org.jclouds.rest.RestContextFactory;
import org.jclouds.rest.RestContextFactory.ContextSpec;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404;
import org.jclouds.rest.internal.RestAnnotationProcessor;
@ -54,7 +55,6 @@ import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions;
import org.jclouds.vcloud.terremark.config.TerremarkVCloudExpressRestClientModule;
import org.jclouds.vcloud.terremark.domain.NodeConfiguration;
import org.jclouds.vcloud.terremark.domain.Protocol;
import org.jclouds.vcloud.terremark.functions.ReturnEmptySetOnResourceNotFoundException;
import org.jclouds.vcloud.terremark.options.AddInternetServiceOptions;
import org.jclouds.vcloud.terremark.options.AddNodeOptions;
import org.jclouds.vcloud.terremark.options.TerremarkInstantiateVAppTemplateOptions;
@ -131,14 +131,14 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testInstantiateVAppTemplate() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("instantiateVAppTemplateInVDC", String.class,
String.class, String.class, Array.newInstance(InstantiateVAppTemplateOptions.class, 0).getClass());
String.class, String.class, Array.newInstance(InstantiateVAppTemplateOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "1", "name", 3 + "");
assertRequestLineEquals(request, "POST https://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/InstantiateVAppTemplateParams-test.xml")),
"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false);
"/terremark/InstantiateVAppTemplateParams-test.xml")),
"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, VAppHandler.class);
@ -149,16 +149,16 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testInstantiateVAppTemplateOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("instantiateVAppTemplateInVDC", String.class,
String.class, String.class, Array.newInstance(InstantiateVAppTemplateOptions.class, 0).getClass());
String.class, String.class, Array.newInstance(InstantiateVAppTemplateOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, "1", "name", 3 + "",
TerremarkInstantiateVAppTemplateOptions.Builder.processorCount(2).memory(512).inRow("row").inGroup("group")
.withPassword("password").inNetwork(URI.create("http://network")));
TerremarkInstantiateVAppTemplateOptions.Builder.processorCount(2).memory(512).inRow("row").inGroup(
"group").withPassword("password").inNetwork(URI.create("http://network")));
assertRequestLineEquals(request, "POST https://vcloud/vdc/1/action/instantiateVAppTemplate HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.vApp+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/InstantiateVAppTemplateParams-options-test.xml")),
"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false);
"/terremark/InstantiateVAppTemplateParams-options-test.xml")),
"application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, VAppHandler.class);
@ -184,13 +184,14 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddInternetService() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addInternetServiceToVDC", String.class,
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0).getClass());
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0)
.getClass());
HttpRequest request = processor.createRequest(method, "1", "name", Protocol.TCP, 22);
assertRequestLineEquals(request, "POST https://vcloud/extensions/vdc/1/internetServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateInternetService-test2.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false);
"/terremark/CreateInternetService-test2.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InternetServiceHandler.class);
@ -201,15 +202,16 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddInternetServiceOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addInternetServiceToVDC", String.class,
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0).getClass());
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0)
.getClass());
HttpRequest request = processor.createRequest(method, "1", "name", Protocol.TCP, 22, disabled().withDescription(
"yahoo"));
"yahoo"));
assertRequestLineEquals(request, "POST https://vcloud/extensions/vdc/1/internetServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateInternetService-options-test.xml")), "application/vnd.tmrk.vCloud.internetService+xml",
false);
"/terremark/CreateInternetService-options-test.xml")),
"application/vnd.tmrk.vCloud.internetService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InternetServiceHandler.class);
assertExceptionParserClassEquals(method, null);
@ -227,7 +229,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InternetServicesHandler.class);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -264,13 +266,14 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddInternetServiceToExistingIp() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addInternetServiceToExistingIp", int.class,
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0).getClass());
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0)
.getClass());
HttpRequest request = processor.createRequest(method, 12, "name", Protocol.TCP, 22);
assertRequestLineEquals(request, "POST https://vcloud/extensions/publicIp/12/internetServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateInternetService-test2.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false);
"/terremark/CreateInternetService-test2.xml")), "application/vnd.tmrk.vCloud.internetService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InternetServiceHandler.class);
@ -281,15 +284,16 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddInternetServiceToExistingIpOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addInternetServiceToExistingIp", int.class,
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0).getClass());
String.class, Protocol.class, int.class, Array.newInstance(AddInternetServiceOptions.class, 0)
.getClass());
HttpRequest request = processor.createRequest(method, 12, "name", Protocol.TCP, 22, disabled().withDescription(
"yahoo"));
"yahoo"));
assertRequestLineEquals(request, "POST https://vcloud/extensions/publicIp/12/internetServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.internetService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateInternetService-options-test.xml")), "application/vnd.tmrk.vCloud.internetService+xml",
false);
"/terremark/CreateInternetService-options-test.xml")),
"application/vnd.tmrk.vCloud.internetService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, InternetServiceHandler.class);
assertExceptionParserClassEquals(method, null);
@ -299,13 +303,13 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddNode() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addNode", int.class, String.class,
String.class, int.class, Array.newInstance(AddNodeOptions.class, 0).getClass());
String.class, int.class, Array.newInstance(AddNodeOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, 12, "10.2.2.2", "name", 22);
assertRequestLineEquals(request, "POST https://vcloud/extensions/internetService/12/nodeServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateNodeService-test2.xml")), "application/vnd.tmrk.vCloud.nodeService+xml", false);
"/terremark/CreateNodeService-test2.xml")), "application/vnd.tmrk.vCloud.nodeService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, NodeHandler.class);
@ -316,15 +320,15 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testAddNodeOptions() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("addNode", int.class, String.class,
String.class, int.class, Array.newInstance(AddNodeOptions.class, 0).getClass());
String.class, int.class, Array.newInstance(AddNodeOptions.class, 0).getClass());
HttpRequest request = processor.createRequest(method, 12, "10.2.2.2", "name", 22, AddNodeOptions.Builder
.disabled().withDescription("yahoo"));
.disabled().withDescription("yahoo"));
assertRequestLineEquals(request, "POST https://vcloud/extensions/internetService/12/nodeServices HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n");
assertPayloadEquals(request, Utils.toStringAndClose(getClass().getResourceAsStream(
"/terremark/CreateNodeService-options-test.xml")), "application/vnd.tmrk.vCloud.nodeService+xml", false);
"/terremark/CreateNodeService-options-test.xml")), "application/vnd.tmrk.vCloud.nodeService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, NodeHandler.class);
assertExceptionParserClassEquals(method, null);
@ -349,15 +353,15 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testConfigureNode() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("configureNode", int.class,
NodeConfiguration.class);
NodeConfiguration.class);
HttpRequest request = processor.createRequest(method, 12, new NodeConfiguration().changeDescriptionTo("eggs"));
assertRequestLineEquals(request, "PUT https://vcloud/extensions/nodeService/12 HTTP/1.1");
assertNonPayloadHeadersEqual(request, "Accept: application/vnd.tmrk.vCloud.nodeService+xml\n");
assertPayloadEquals(
request,
"<NodeService xmlns=\"urn:tmrk:vCloudExpressExtensions-1.6\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Description>eggs</Description></NodeService>",
"application/vnd.tmrk.vCloud.nodeService+xml", false);
request,
"<NodeService xmlns=\"urn:tmrk:vCloudExpressExtensions-1.6\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"><Description>eggs</Description></NodeService>",
"application/vnd.tmrk.vCloud.nodeService+xml", false);
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, NodeHandler.class);
assertExceptionParserClassEquals(method, null);
@ -375,7 +379,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, NodesHandler.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnResourceNotFoundException.class);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -397,12 +401,12 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
public void testGetCustomizationOptionsOfCatalogItem() throws SecurityException, NoSuchMethodException, IOException {
Method method = TerremarkVCloudExpressAsyncClient.class.getMethod("getCustomizationOptionsOfCatalogItem",
String.class);
String.class);
HttpRequest request = processor.createRequest(method, 12);
assertRequestLineEquals(request, "GET https://vcloud/extensions/template/12/options/customization HTTP/1.1");
assertNonPayloadHeadersEqual(request,
"Accept: application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml\n");
"Accept: application/vnd.tmrk.vCloud.catalogItemCustomizationParameters+xml\n");
assertPayloadEquals(request, null, null, false);
assertResponseParserClassEquals(method, request, ParseSax.class);
@ -422,7 +426,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, KeyPairsHandler.class);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -437,7 +441,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
assertResponseParserClassEquals(method, request, ParseSax.class);
assertSaxResponseParserClassEquals(method, KeyPairsHandler.class);
assertExceptionParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(request);
}
@ -516,7 +520,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
@Override
public ContextSpec<?, ?> createContextSpec() {
return new RestContextFactory().createContextSpec("trmk-vcloudexpress", "identity", "credential",
new Properties());
new Properties());
}
@RequiresHttp
@ -524,7 +528,7 @@ public class TerremarkVCloudAsyncClientTest extends RestClientTest<TerremarkVClo
protected static class TerremarkVCloudRestClientModuleExtension extends TerremarkVCloudExpressRestClientModule {
@Override
protected URI provideAuthenticationURI(VCloudVersionsAsyncClient versionService,
@Named(PROPERTY_API_VERSION) String version) {
@Named(PROPERTY_API_VERSION) String version) {
return URI.create("https://vcloud/login");
}

View File

@ -40,7 +40,7 @@ import org.jclouds.vcloud.terremark.domain.VAppConfiguration;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
@ -68,7 +68,7 @@ public class BindVAppConfigurationToXmlPayloadTest {
VAppImpl vApp = new VAppImpl("4213", "MyAppServer6", URI
.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"),
VAppStatus.OFF, 4194304l, null, ImmutableListMultimap.<String, String> of(), null,
null, ImmutableSortedSet.of(new ResourceAllocation(1, "n/a", null,
null, ImmutableSet.of(new ResourceAllocation(1, "n/a", null,
ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null),
new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null,
null, null, null, null, 1024, null), new ResourceAllocation(9,
@ -99,7 +99,7 @@ public class BindVAppConfigurationToXmlPayloadTest {
VAppImpl vApp = new VAppImpl("4213", "MyAppServer6", URI
.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"),
VAppStatus.OFF, 4194304l, null, ImmutableListMultimap.<String, String> of(), null,
null, ImmutableSortedSet.of(new ResourceAllocation(1, "n/a", null,
null, ImmutableSet.of(new ResourceAllocation(1, "n/a", null,
ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null),
new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null,
null, null, null, null, 1024, null), new ResourceAllocation(9,
@ -132,7 +132,7 @@ public class BindVAppConfigurationToXmlPayloadTest {
VAppImpl vApp = new VAppImpl("4213", "eduardo", URI
.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"),
VAppStatus.OFF, 4194304l, null, ImmutableListMultimap.<String, String> of(), null,
null, ImmutableSortedSet.of(new ResourceAllocation(1, "n/a", null,
null, ImmutableSet.of(new ResourceAllocation(1, "n/a", null,
ResourceType.PROCESSOR, null, null, null, null, null, null, 4, null),
new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null,
null, null, null, null, 1024, null), new ResourceAllocation(9,
@ -161,7 +161,7 @@ public class BindVAppConfigurationToXmlPayloadTest {
VAppImpl vApp = new VAppImpl("4213", "MyAppServer6", URI
.create("https://services.vcloudexpress/terremark.com/api/v0.8/vapp/4213"),
VAppStatus.OFF, 4194304l, null, ImmutableListMultimap.<String, String> of(), null,
null, ImmutableSortedSet.of(new ResourceAllocation(1, "n/a", null,
null, ImmutableSet.of(new ResourceAllocation(1, "n/a", null,
ResourceType.PROCESSOR, null, null, null, null, null, null, 2, null),
new ResourceAllocation(2, "n/a", null, ResourceType.MEMORY, null, null,
null, null, null, null, 1536, null), new ResourceAllocation(9,

View File

@ -23,7 +23,7 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.SortedSet;
import java.util.Set;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.vcloud.terremark.domain.InternetService;
@ -31,7 +31,7 @@ import org.jclouds.vcloud.terremark.domain.Protocol;
import org.jclouds.vcloud.terremark.domain.PublicIpAddress;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code InternetServicesHandler}
@ -44,11 +44,11 @@ public class InternetServicesHandlerTest extends BaseHandlerTest {
public void test2() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/terremark/InternetServices.xml");
SortedSet<InternetService> result = factory.create(
Set<InternetService> result = factory.create(
injector.getInstance(InternetServicesHandler.class)).parse(is);
assertEquals(
result,
ImmutableSortedSet
ImmutableSet
.of(new InternetService(
524,
"IS_for_Jim2",

View File

@ -22,14 +22,14 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.SortedSet;
import java.util.Set;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.vcloud.terremark.domain.IpAddress;
import org.jclouds.vcloud.terremark.domain.IpAddress.Status;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code IpAddressesHandler}
@ -42,9 +42,9 @@ public class IpAddressesHandlerTest extends BaseHandlerTest {
public void test1() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/terremark/ipAddresses.xml");
SortedSet<IpAddress> result = factory.create(injector.getInstance(IpAddressesHandler.class))
Set<IpAddress> result = factory.create(injector.getInstance(IpAddressesHandler.class))
.parse(is);
assertEquals(result, ImmutableSortedSet.of(new IpAddress("10.114.34.131", Status.ASSIGNED,
assertEquals(result, ImmutableSet.of(new IpAddress("10.114.34.131", Status.ASSIGNED,
"testforjcloud2"), new IpAddress("10.114.34.132", Status.AVAILABLE, null)));
}
}

View File

@ -23,13 +23,13 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.SortedSet;
import java.util.Set;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.vcloud.terremark.domain.Node;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code NodesHandler}
@ -42,8 +42,8 @@ public class NodesHandlerTest extends BaseHandlerTest {
public void test1() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/terremark/NodeServices.xml");
SortedSet<Node> result = factory.create(injector.getInstance(NodesHandler.class)).parse(is);
assertEquals(result, ImmutableSortedSet.of(new Node(242, "Node for Jim", URI
Set<Node> result = factory.create(injector.getInstance(NodesHandler.class)).parse(is);
assertEquals(result, ImmutableSet.of(new Node(242, "Node for Jim", URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/NodeServices/242"),
"172.16.20.3", 80, false, "Some test node")));
}

View File

@ -23,13 +23,13 @@ import static org.testng.Assert.assertEquals;
import java.io.InputStream;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.SortedSet;
import java.util.Set;
import org.jclouds.http.functions.BaseHandlerTest;
import org.jclouds.vcloud.terremark.domain.PublicIpAddress;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
/**
* Tests behavior of {@code PublicIpAddressesHandler}
@ -42,11 +42,11 @@ public class PublicIpAddressesHandlerTest extends BaseHandlerTest {
public void test1() throws UnknownHostException {
InputStream is = getClass().getResourceAsStream("/terremark/PublicIpAddresses.xml");
SortedSet<PublicIpAddress> result = factory.create(
Set<PublicIpAddress> result = factory.create(
injector.getInstance(PublicIpAddressesHandler.class)).parse(is);
assertEquals(
result,
ImmutableSortedSet
ImmutableSet
.of(
new PublicIpAddress(
8720,

View File

@ -41,7 +41,7 @@ import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
@ -87,11 +87,9 @@ public class VAppHandlerTest extends BaseHandlerTest {
assertEquals(result.getSize().longValue(), 4l);
assertEquals(result.getLocation(), URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/13775"));
assertEquals(result.getVDC(), new NamedResourceImpl("32", null,
"application/vnd.vmware.vcloud.vdc+xml", URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vdc/32")));
assertEquals(result.getLocation(), URI.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/13775"));
assertEquals(result.getVDC(), new NamedResourceImpl("32", null, "application/vnd.vmware.vcloud.vdc+xml", URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vdc/32")));
}
@ -107,44 +105,33 @@ public class VAppHandlerTest extends BaseHandlerTest {
assertEquals(result.getSize().longValue(), 10485760);
assertEquals(result.getOperatingSystemDescription(), "Red Hat Enterprise Linux 5 (64-bit)");
assertEquals(result.getLocation(), URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/16238"));
assertEquals(result.getLocation(), URI.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/16238"));
assertEquals(result.getVDC(), new NamedResourceImpl("32", null, VCloudMediaType.VDC_XML, URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vdc/32")));
assertEquals(result.getSystem(), new VirtualSystem(0, "Virtual Hardware Family", "centos-53",
"vmx-07"));
assertEquals(result.getNetworkToAddresses().get("Internal"), ImmutableList
.<String> of("10.114.34.132"));
assertEquals(result.getSystem(), new VirtualSystem(0, "Virtual Hardware Family", "centos-53", "vmx-07"));
assertEquals(result.getNetworkToAddresses().get("Internal"), ImmutableList.<String> of("10.114.34.132"));
ResourceAllocation cpu = new ResourceAllocation(1, "1 virtual CPU(s)",
"Number of Virtual CPUs", ResourceType.PROCESSOR, null, null, null, null, null,
null, 1, "hertz * 10^6");
ResourceAllocation cpu = new ResourceAllocation(1, "1 virtual CPU(s)", "Number of Virtual CPUs",
ResourceType.PROCESSOR, null, null, null, null, null, null, 1, "hertz * 10^6");
ResourceAllocation controller = new ResourceAllocation(3, "SCSI Controller 0",
"SCSI Controller", ResourceType.SCSI_CONTROLLER, "lsilogic", null, 0, null, null,
null, 1, null);
ResourceAllocation memory = new ResourceAllocation(2, "512MB of memory", "Memory Size",
ResourceType.MEMORY, null, null, null, null, null, null, 512, "byte * 2^20");
ResourceAllocation disk = new ResourceAllocation(9, "Hard Disk 1", null,
ResourceType.DISK_DRIVE, null, "10485760", null, 0, 3, null, 10485760, "byte * 2^20");
assertEquals(result.getResourceAllocations(), ImmutableSortedSet.of(cpu, controller, memory,
disk));
assertEquals(Iterables.getOnlyElement(
result.getResourceAllocationByType().get(ResourceType.PROCESSOR))
ResourceAllocation controller = new ResourceAllocation(3, "SCSI Controller 0", "SCSI Controller",
ResourceType.SCSI_CONTROLLER, "lsilogic", null, 0, null, null, null, 1, null);
ResourceAllocation memory = new ResourceAllocation(2, "512MB of memory", "Memory Size", ResourceType.MEMORY,
null, null, null, null, null, null, 512, "byte * 2^20");
ResourceAllocation disk = new ResourceAllocation(9, "Hard Disk 1", null, ResourceType.DISK_DRIVE, null,
"10485760", null, 0, 3, null, 10485760, "byte * 2^20");
assertEquals(result.getResourceAllocations(), ImmutableSet.of(cpu, memory, controller, disk));
assertEquals(Iterables.getOnlyElement(result.getResourceAllocationByType().get(ResourceType.PROCESSOR))
.getVirtualQuantity(), 1);
assertEquals(Iterables.getOnlyElement(
result.getResourceAllocationByType().get(ResourceType.SCSI_CONTROLLER))
assertEquals(Iterables.getOnlyElement(result.getResourceAllocationByType().get(ResourceType.SCSI_CONTROLLER))
.getVirtualQuantity(), 1);
assertEquals(Iterables.getOnlyElement(
result.getResourceAllocationByType().get(ResourceType.MEMORY)).getVirtualQuantity(),
512);
assertEquals(Iterables.getOnlyElement(
result.getResourceAllocationByType().get(ResourceType.DISK_DRIVE))
assertEquals(Iterables.getOnlyElement(result.getResourceAllocationByType().get(ResourceType.MEMORY))
.getVirtualQuantity(), 512);
assertEquals(Iterables.getOnlyElement(result.getResourceAllocationByType().get(ResourceType.DISK_DRIVE))
.getVirtualQuantity(), 10485760);
assertEquals(result.getSize().longValue(), Iterables.getOnlyElement(
result.getResourceAllocationByType().get(ResourceType.DISK_DRIVE))
.getVirtualQuantity());
result.getResourceAllocationByType().get(ResourceType.DISK_DRIVE)).getVirtualQuantity());
}
public void testGetVApp2disks() throws UnknownHostException {
@ -159,41 +146,32 @@ public class VAppHandlerTest extends BaseHandlerTest {
assertEquals(vApp.getSize().longValue(), 30408704);
assertEquals(vApp.getOperatingSystemDescription(), "Ubuntu Linux (32-bit)");
assertEquals(vApp.getLocation(), URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/15639"));
assertEquals(vApp.getLocation(), URI.create("https://services.vcloudexpress.terremark.com/api/v0.8/vapp/15639"));
assertEquals(vApp.getVDC(), new NamedResourceImpl("32", null, VCloudMediaType.VDC_XML, URI
.create("https://services.vcloudexpress.terremark.com/api/v0.8/vdc/32")));
assertEquals(vApp.getSystem(), new VirtualSystem(0, "Virtual Hardware Family", "eduardo",
"vmx-07"));
assertEquals(vApp.getSystem(), new VirtualSystem(0, "Virtual Hardware Family", "eduardo", "vmx-07"));
assertEquals(vApp.getNetworkToAddresses().get("Internal"), ImmutableList.of("10.114.34.131"));
ResourceAllocation cpu = new ResourceAllocation(1, "2 virtual CPU(s)",
"Number of Virtual CPUs", ResourceType.PROCESSOR, null, null, null, null, null,
null, 2, "hertz * 10^6");
ResourceAllocation cpu = new ResourceAllocation(1, "2 virtual CPU(s)", "Number of Virtual CPUs",
ResourceType.PROCESSOR, null, null, null, null, null, null, 2, "hertz * 10^6");
ResourceAllocation controller = new ResourceAllocation(3, "SCSI Controller 0",
"SCSI Controller", ResourceType.SCSI_CONTROLLER, "lsilogic", null, 0, null, null,
null, 1, null);
ResourceAllocation memory = new ResourceAllocation(2, "1024MB of memory", "Memory Size",
ResourceType.MEMORY, null, null, null, null, null, null, 1024, "byte * 2^20");
ResourceAllocation disk = new ResourceAllocation(9, "Hard Disk 1", null,
ResourceType.DISK_DRIVE, null, "4194304", null, 0, 3, null, 4194304, "byte * 2^20");
ResourceAllocation disk2 = new ResourceAllocation(9, "Hard Disk 2", null,
ResourceType.DISK_DRIVE, null, "26214400", null, 1, 3, null, 26214400, "byte * 2^20");
ResourceAllocation controller = new ResourceAllocation(3, "SCSI Controller 0", "SCSI Controller",
ResourceType.SCSI_CONTROLLER, "lsilogic", null, 0, null, null, null, 1, null);
ResourceAllocation memory = new ResourceAllocation(2, "1024MB of memory", "Memory Size", ResourceType.MEMORY,
null, null, null, null, null, null, 1024, "byte * 2^20");
ResourceAllocation disk = new ResourceAllocation(9, "Hard Disk 1", null, ResourceType.DISK_DRIVE, null,
"4194304", null, 0, 3, null, 4194304, "byte * 2^20");
ResourceAllocation disk2 = new ResourceAllocation(9, "Hard Disk 2", null, ResourceType.DISK_DRIVE, null,
"26214400", null, 1, 3, null, 26214400, "byte * 2^20");
assertEquals(vApp.getResourceAllocations(), ImmutableSortedSet.of(cpu, controller, memory,
disk, disk2));
assertEquals(
Iterables.getOnlyElement(
vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR))
.getVirtualQuantity(), 2);
assertEquals(Iterables.getOnlyElement(
vApp.getResourceAllocationByType().get(ResourceType.SCSI_CONTROLLER))
assertEquals(vApp.getResourceAllocations(), ImmutableSet.of(cpu, memory, controller, disk, disk2));
assertEquals(Iterables.getOnlyElement(vApp.getResourceAllocationByType().get(ResourceType.PROCESSOR))
.getVirtualQuantity(), 2);
assertEquals(Iterables.getOnlyElement(vApp.getResourceAllocationByType().get(ResourceType.SCSI_CONTROLLER))
.getVirtualQuantity(), 1);
assertEquals(Iterables.getOnlyElement(
vApp.getResourceAllocationByType().get(ResourceType.MEMORY)).getVirtualQuantity(),
1024);
assertEquals(Iterables.getOnlyElement(vApp.getResourceAllocationByType().get(ResourceType.MEMORY))
.getVirtualQuantity(), 1024);
// extract the disks on the vApp sorted by addressOnParent
List<ResourceAllocation> disks = Lists.newArrayList(vApp.getResourceAllocationByType().get(