From 2b111b2604462c3ead1c1d8b8ca04efca164ee3d Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Tue, 19 Apr 2011 16:57:37 -0700 Subject: [PATCH 01/95] Issue 536:terremark delete operation now returns tasks --- .../src/main/java/org/jclouds/s3/Bucket.java | 6 +- .../java/org/jclouds/s3/S3AsyncClient.java | 118 ++++----- .../binders/BindAsHostPrefixIfConfigured.java | 8 +- .../jclouds/s3/config/S3RestClientModule.java | 12 +- .../s3/functions/BindRegionToXmlPayload.java | 2 + .../s3/xml/LocationConstraintHandler.java | 26 ++ .../vcloud/VCloudExpressAsyncClient.java | 27 +- .../jclouds/vcloud/VCloudExpressClient.java | 6 +- .../ParseOsFromVAppTemplateName.java | 3 +- .../VCloudExpressComputeClientImpl.java | 5 +- .../ParseTaskFromLocationHeader.java | 3 +- .../vcloud/VCloudExpressAsyncClientTest.java | 6 +- .../terremark/TerremarkVCloudAsyncClient.java | 4 +- .../terremark/TerremarkVCloudClient.java | 3 +- .../compute/TerremarkVCloudComputeClient.java | 64 ++--- .../org/jclouds/json/config/GsonModule.java | 31 ++- .../test/java/org/jclouds/json/JsonTest.java | 14 ++ .../org/jclouds/aws/s3/AWSS3AsyncClient.java | 74 +++--- .../aws/s3/config/AWSS3RestClientModule.java | 23 ++ .../jclouds/aws/s3/AWSS3AsyncClientTest.java | 80 ++++-- .../TerremarkECloudAsyncClientTest.java | 213 +++++++++------- ...TerremarkVCloudExpressAsyncClientTest.java | 232 ++++++++++-------- 22 files changed, 597 insertions(+), 363 deletions(-) rename {common/trmk/src/main/java/org/jclouds/vcloud/terremark => apis/vcloudexpress/src/main/java/org/jclouds/vcloud}/functions/ParseTaskFromLocationHeader.java (97%) diff --git a/apis/s3/src/main/java/org/jclouds/s3/Bucket.java b/apis/s3/src/main/java/org/jclouds/s3/Bucket.java index bc7a76c26d..819912163e 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/Bucket.java +++ b/apis/s3/src/main/java/org/jclouds/s3/Bucket.java @@ -18,16 +18,20 @@ */ package org.jclouds.s3; +import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import javax.inject.Qualifier; + /** * Annotates the parameter that this is a bucket. */ -@Target(PARAMETER) +@Target({ PARAMETER, METHOD }) @Retention(RUNTIME) +@Qualifier public @interface Bucket { } diff --git a/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java b/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java index faafe7b954..1f53e212cc 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java +++ b/apis/s3/src/main/java/org/jclouds/s3/S3AsyncClient.java @@ -33,6 +33,28 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.jclouds.blobstore.attr.BlobScope; +import org.jclouds.blobstore.functions.ReturnFalseOnContainerNotFound; +import org.jclouds.blobstore.functions.ReturnFalseOnKeyNotFound; +import org.jclouds.blobstore.functions.ReturnNullOnKeyNotFound; +import org.jclouds.blobstore.functions.ThrowContainerNotFoundOn404; +import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404; +import org.jclouds.http.functions.ParseETagHeader; +import org.jclouds.http.options.GetOptions; +import org.jclouds.location.functions.RegionToEndpointOrProviderIfNull; +import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.EndpointParam; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.Headers; +import org.jclouds.rest.annotations.ParamParser; +import org.jclouds.rest.annotations.ParamValidators; +import org.jclouds.rest.annotations.QueryParams; +import org.jclouds.rest.annotations.RequestFilters; +import org.jclouds.rest.annotations.ResponseParser; +import org.jclouds.rest.annotations.SkipEncoding; +import org.jclouds.rest.annotations.VirtualHost; +import org.jclouds.rest.annotations.XMLResponseParser; +import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.s3.binders.BindACLToXMLPayload; import org.jclouds.s3.binders.BindAsHostPrefixIfConfigured; import org.jclouds.s3.binders.BindBucketLoggingToXmlPayload; @@ -65,26 +87,6 @@ import org.jclouds.s3.xml.ListAllMyBucketsHandler; import org.jclouds.s3.xml.ListBucketHandler; import org.jclouds.s3.xml.LocationConstraintHandler; import org.jclouds.s3.xml.PayerHandler; -import org.jclouds.blobstore.attr.BlobScope; -import org.jclouds.blobstore.functions.ReturnFalseOnContainerNotFound; -import org.jclouds.blobstore.functions.ReturnFalseOnKeyNotFound; -import org.jclouds.blobstore.functions.ReturnNullOnKeyNotFound; -import org.jclouds.blobstore.functions.ThrowContainerNotFoundOn404; -import org.jclouds.blobstore.functions.ThrowKeyNotFoundOn404; -import org.jclouds.http.functions.ParseETagHeader; -import org.jclouds.http.options.GetOptions; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.Headers; -import org.jclouds.rest.annotations.ParamParser; -import org.jclouds.rest.annotations.ParamValidators; -import org.jclouds.rest.annotations.QueryParams; -import org.jclouds.rest.annotations.RequestFilters; -import org.jclouds.rest.annotations.ResponseParser; -import org.jclouds.rest.annotations.SkipEncoding; -import org.jclouds.rest.annotations.VirtualHost; -import org.jclouds.rest.annotations.XMLResponseParser; -import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import com.google.common.util.concurrent.ListenableFuture; import com.google.inject.Provides; @@ -121,8 +123,8 @@ public interface S3AsyncClient { @ExceptionParser(ReturnNullOnKeyNotFound.class) @ResponseParser(ParseObjectFromHeadersAndHttpContent.class) ListenableFuture getObject( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key, GetOptions... options); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key, GetOptions... options); /** * @see S3Client#headObject @@ -132,8 +134,8 @@ public interface S3AsyncClient { @ExceptionParser(ReturnNullOnKeyNotFound.class) @ResponseParser(ParseObjectMetadataFromHeaders.class) ListenableFuture headObject( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key); /** * @see S3Client#objectExists @@ -142,8 +144,8 @@ public interface S3AsyncClient { @Path("/{key}") @ExceptionParser(ReturnFalseOnKeyNotFound.class) ListenableFuture objectExists( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key); /** * @see S3Client#deleteObject @@ -152,8 +154,8 @@ public interface S3AsyncClient { @Path("/{key}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture deleteObject( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key); /** * @see S3Client#putObject @@ -162,9 +164,9 @@ public interface S3AsyncClient { @Path("/{key}") @ResponseParser(ParseETagHeader.class) ListenableFuture putObject( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") @ParamParser(ObjectKey.class) @BinderParam(BindS3ObjectMetadataToRequest.class) S3Object object, - PutObjectOptions... options); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") @ParamParser(ObjectKey.class) @BinderParam(BindS3ObjectMetadataToRequest.class) S3Object object, + PutObjectOptions... options); /** * @see S3Client#putBucketInRegion @@ -173,10 +175,9 @@ public interface S3AsyncClient { @Path("/") @ExceptionParser(ReturnFalseIfBucketAlreadyOwnedByYouOrIllegalState.class) ListenableFuture putBucketInRegion( - // TODO endpoint based on region - @BinderParam(BindRegionToXmlPayload.class) @Nullable String region, - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - PutBucketOptions... options); + @EndpointParam(parser = RegionToEndpointOrProviderIfNull.class) @BinderParam(BindRegionToXmlPayload.class) @Nullable String region, + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + PutBucketOptions... options); /** * @see S3Client#deleteBucketIfEmpty @@ -185,7 +186,7 @@ public interface S3AsyncClient { @Path("/") @ExceptionParser(ReturnTrueOn404OrNotFoundFalseOnIllegalState.class) ListenableFuture deleteBucketIfEmpty( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#bucketExists @@ -195,7 +196,7 @@ public interface S3AsyncClient { @QueryParams(keys = "max-keys", values = "0") @ExceptionParser(ReturnFalseOnContainerNotFound.class) ListenableFuture bucketExists( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#getBucketLocation @@ -205,7 +206,7 @@ public interface S3AsyncClient { @Path("/") @XMLResponseParser(LocationConstraintHandler.class) ListenableFuture getBucketLocation( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#getBucketPayer @@ -215,7 +216,7 @@ public interface S3AsyncClient { @Path("/") @XMLResponseParser(PayerHandler.class) ListenableFuture getBucketPayer( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#setBucketPayer @@ -224,8 +225,8 @@ public interface S3AsyncClient { @QueryParams(keys = "requestPayment") @Path("/") ListenableFuture setBucketPayer( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @BinderParam(BindPayerToXmlPayload.class) Payer payer); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @BinderParam(BindPayerToXmlPayload.class) Payer payer); /** * @see S3Client#listBucket @@ -234,8 +235,8 @@ public interface S3AsyncClient { @Path("/") @XMLResponseParser(ListBucketHandler.class) ListenableFuture listBucket( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - ListBucketOptions... options); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + ListBucketOptions... options); /** * @see S3Client#listOwnedBuckets @@ -254,10 +255,10 @@ public interface S3AsyncClient { @Headers(keys = "x-amz-copy-source", values = "/{sourceBucket}/{sourceObject}") @XMLResponseParser(CopyObjectHandler.class) ListenableFuture copyObject( - @PathParam("sourceBucket") String sourceBucket, - @PathParam("sourceObject") String sourceObject, - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String destinationBucket, - @PathParam("destinationObject") String destinationObject, CopyObjectOptions... options); + @PathParam("sourceBucket") String sourceBucket, + @PathParam("sourceObject") String sourceObject, + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String destinationBucket, + @PathParam("destinationObject") String destinationObject, CopyObjectOptions... options); /** * @see S3Client#getBucketACL @@ -268,7 +269,7 @@ public interface S3AsyncClient { @ExceptionParser(ThrowContainerNotFoundOn404.class) @Path("/") ListenableFuture getBucketACL( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#putBucketACL @@ -277,8 +278,8 @@ public interface S3AsyncClient { @Path("/") @QueryParams(keys = "acl") ListenableFuture putBucketACL( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @BinderParam(BindACLToXMLPayload.class) AccessControlList acl); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @BinderParam(BindACLToXMLPayload.class) AccessControlList acl); /** * @see S3Client#getObjectACL @@ -289,8 +290,8 @@ public interface S3AsyncClient { @XMLResponseParser(AccessControlListHandler.class) @ExceptionParser(ThrowKeyNotFoundOn404.class) ListenableFuture getObjectACL( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key); /** * @see S3Client#putObjectACL @@ -299,9 +300,8 @@ public interface S3AsyncClient { @QueryParams(keys = "acl") @Path("/{key}") ListenableFuture putObjectACL( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key, - @BinderParam(BindACLToXMLPayload.class) AccessControlList acl); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key, @BinderParam(BindACLToXMLPayload.class) AccessControlList acl); /** * @see S3Client#getBucketLogging @@ -312,7 +312,7 @@ public interface S3AsyncClient { @ExceptionParser(ThrowContainerNotFoundOn404.class) @Path("/") ListenableFuture getBucketLogging( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); /** * @see S3Client#enableBucketLogging @@ -321,8 +321,8 @@ public interface S3AsyncClient { @Path("/") @QueryParams(keys = "logging") ListenableFuture enableBucketLogging( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @BinderParam(BindBucketLoggingToXmlPayload.class) BucketLogging logging); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @BinderParam(BindBucketLoggingToXmlPayload.class) BucketLogging logging); /** * @see S3Client#putBucketLogging @@ -332,6 +332,6 @@ public interface S3AsyncClient { @QueryParams(keys = "logging") @Produces(MediaType.TEXT_XML) ListenableFuture disableBucketLogging( - @Bucket @BinderParam(BindNoBucketLoggingToXmlPayload.class) @ParamValidators( { BucketNameValidator.class }) String bucketName); + @Bucket @BinderParam(BindNoBucketLoggingToXmlPayload.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); } diff --git a/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java b/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java index 4699f5a626..f08c59e92a 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java +++ b/apis/s3/src/main/java/org/jclouds/s3/binders/BindAsHostPrefixIfConfigured.java @@ -45,10 +45,10 @@ import com.google.common.collect.Maps; @Singleton public class BindAsHostPrefixIfConfigured implements Binder { - private final Provider uriBuilderProvider; - private final BindAsHostPrefix bindAsHostPrefix; - private final boolean isVhostStyle; - private final String servicePath; + protected final Provider uriBuilderProvider; + protected final BindAsHostPrefix bindAsHostPrefix; + protected final boolean isVhostStyle; + protected final String servicePath; @Inject public BindAsHostPrefixIfConfigured(BindAsHostPrefix bindAsHostPrefix, diff --git a/apis/s3/src/main/java/org/jclouds/s3/config/S3RestClientModule.java b/apis/s3/src/main/java/org/jclouds/s3/config/S3RestClientModule.java index a70558c1a0..4efaf99ac4 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/config/S3RestClientModule.java +++ b/apis/s3/src/main/java/org/jclouds/s3/config/S3RestClientModule.java @@ -18,6 +18,7 @@ */ package org.jclouds.s3.config; +import java.util.Map; import java.util.concurrent.TimeUnit; import javax.inject.Named; @@ -34,6 +35,7 @@ import org.jclouds.http.annotation.Redirection; import org.jclouds.http.annotation.ServerError; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RequestSigner; +import org.jclouds.s3.Bucket; import org.jclouds.s3.S3AsyncClient; import org.jclouds.s3.S3Client; import org.jclouds.s3.filters.RequestAuthorizeSignature; @@ -41,6 +43,7 @@ import org.jclouds.s3.handlers.ParseS3ErrorFromXmlContent; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; +import com.google.common.collect.Maps; import com.google.inject.Provides; import com.google.inject.Scopes; @@ -60,6 +63,13 @@ public class S3RestClientModule ext super(sync, async); } + @Provides + @Bucket + @Singleton + protected Map bucketToRegion() { + return Maps.newConcurrentMap(); + } + @Override protected void configure() { install(new S3ObjectModule()); @@ -94,7 +104,7 @@ public class S3RestClientModule ext @TimeStamp @Singleton protected Supplier provideTimeStampCache(@Named(Constants.PROPERTY_SESSION_INTERVAL) long seconds, - final DateService dateService) { + final DateService dateService) { return Suppliers.memoizeWithExpiration(new Supplier() { public String get() { return dateService.rfc822DateFormat(); diff --git a/apis/s3/src/main/java/org/jclouds/s3/functions/BindRegionToXmlPayload.java b/apis/s3/src/main/java/org/jclouds/s3/functions/BindRegionToXmlPayload.java index 2a085bf311..4668ec06f9 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/functions/BindRegionToXmlPayload.java +++ b/apis/s3/src/main/java/org/jclouds/s3/functions/BindRegionToXmlPayload.java @@ -20,6 +20,8 @@ package org.jclouds.s3.functions; import static com.google.common.base.Preconditions.checkArgument; +import java.net.URI; +import java.util.Map; import java.util.Set; import javax.annotation.Nullable; diff --git a/apis/s3/src/main/java/org/jclouds/s3/xml/LocationConstraintHandler.java b/apis/s3/src/main/java/org/jclouds/s3/xml/LocationConstraintHandler.java index 7528d79a55..6d9f1c25f6 100644 --- a/apis/s3/src/main/java/org/jclouds/s3/xml/LocationConstraintHandler.java +++ b/apis/s3/src/main/java/org/jclouds/s3/xml/LocationConstraintHandler.java @@ -20,8 +20,15 @@ package org.jclouds.s3.xml; import static org.jclouds.util.SaxUtils.currentOrNull; +import java.util.concurrent.ConcurrentMap; + +import javax.inject.Inject; + import org.jclouds.aws.domain.Region; +import org.jclouds.http.HttpRequest; import org.jclouds.http.functions.ParseSax; +import org.jclouds.rest.internal.GeneratedHttpRequest; +import org.jclouds.s3.Bucket; /** * Parses the response from Amazon S3 GET Bucket Location @@ -32,8 +39,15 @@ import org.jclouds.http.functions.ParseSax; * @author Adrian Cole */ public class LocationConstraintHandler extends ParseSax.HandlerWithResult { + private final ConcurrentMap bucketToRegion; private StringBuilder currentText = new StringBuilder(); private String region; + private String bucket; + + @Inject + public LocationConstraintHandler(@Bucket ConcurrentMap bucketToRegion) { + this.bucketToRegion = bucketToRegion; + } public String getResult() { return region; @@ -41,6 +55,18 @@ public class LocationConstraintHandler extends ParseSax.HandlerWithResult getVApp(@EndpointParam URI vApp); /** - * @see CommonVCloudClient#deployVApp + * @see VCloudExpressClient#deployVApp */ @POST @Consumes(TASK_XML) @@ -173,7 +174,7 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture deployVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#undeployVApp + * @see VCloudExpressClient#undeployVApp */ @POST @Consumes(TASK_XML) @@ -182,7 +183,7 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture undeployVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#powerOnVApp + * @see VCloudExpressClient#powerOnVApp */ @POST @Consumes(TASK_XML) @@ -191,7 +192,7 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture powerOnVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#powerOffVApp + * @see VCloudExpressClient#powerOffVApp */ @POST @Consumes(TASK_XML) @@ -200,14 +201,14 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture powerOffVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#shutdownVApp + * @see VCloudExpressClient#shutdownVApp */ @POST @Path("/power/action/shutdown") ListenableFuture shutdownVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#resetVApp + * @see VCloudExpressClient#resetVApp */ @POST @Consumes(TASK_XML) @@ -216,7 +217,7 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture resetVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#suspendVApp + * @see VCloudExpressClient#suspendVApp */ @POST @Consumes(TASK_XML) @@ -225,10 +226,10 @@ public interface VCloudExpressAsyncClient extends CommonVCloudAsyncClient { ListenableFuture suspendVApp(@EndpointParam URI vAppId); /** - * @see CommonVCloudClient#deleteVApp + * @see VCloudExpressClient#deleteVApp */ @DELETE - @ExceptionParser(ReturnVoidOnNotFoundOr404.class) - ListenableFuture deleteVApp(@EndpointParam URI vAppId); - + @ResponseParser(ParseTaskFromLocationHeader.class) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture deleteVApp(@EndpointParam URI vAppId); } diff --git a/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/VCloudExpressClient.java b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/VCloudExpressClient.java index 808c473405..8c4138f5c8 100644 --- a/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/VCloudExpressClient.java +++ b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/VCloudExpressClient.java @@ -42,7 +42,7 @@ import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; public interface VCloudExpressClient extends CommonVCloudClient { VCloudExpressVApp instantiateVAppTemplateInVDC(URI vDC, URI template, String appName, - InstantiateVAppTemplateOptions... options); + InstantiateVAppTemplateOptions... options); Task cloneVAppInVDC(URI vDC, URI toClone, String newName, CloneVAppOptions... options); @@ -63,7 +63,7 @@ public interface VCloudExpressClient extends CommonVCloudClient { * if you specified an org, catalog, or catalog item name that isn't present */ VCloudExpressVAppTemplate findVAppTemplateInOrgCatalogNamed(@Nullable String orgName, @Nullable String catalogName, - String itemName); + String itemName); VCloudExpressVApp findVAppInOrgVDCNamed(@Nullable String orgName, @Nullable String catalogName, String vAppName); @@ -101,6 +101,6 @@ public interface VCloudExpressClient extends CommonVCloudClient { */ Task suspendVApp(URI vAppId); - void deleteVApp(URI vAppId); + Task deleteVApp(URI vAppId); } diff --git a/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/compute/functions/ParseOsFromVAppTemplateName.java b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/compute/functions/ParseOsFromVAppTemplateName.java index a33c44a847..932d535739 100644 --- a/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/compute/functions/ParseOsFromVAppTemplateName.java +++ b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/compute/functions/ParseOsFromVAppTemplateName.java @@ -29,7 +29,6 @@ import javax.inject.Inject; import javax.inject.Singleton; import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OperatingSystemBuilder; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.util.ComputeServiceUtils; @@ -51,7 +50,7 @@ public class ParseOsFromVAppTemplateName implements Function> deleting vApp(%s)", vApp.getName()); - VCloudExpressClient.class.cast(client).deleteVApp(vApp.getHref()); + Task task = VCloudExpressClient.class.cast(client).deleteVApp(vApp.getHref()); + if (task != null) + if (!taskTester.apply(task.getHref())) + throw new RuntimeException(String.format("failed to %s %s: %s", "delete", vApp.getName(), task)); } @Override diff --git a/common/trmk/src/main/java/org/jclouds/vcloud/terremark/functions/ParseTaskFromLocationHeader.java b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/functions/ParseTaskFromLocationHeader.java similarity index 97% rename from common/trmk/src/main/java/org/jclouds/vcloud/terremark/functions/ParseTaskFromLocationHeader.java rename to apis/vcloudexpress/src/main/java/org/jclouds/vcloud/functions/ParseTaskFromLocationHeader.java index 31e98d186a..388933f8ac 100644 --- a/common/trmk/src/main/java/org/jclouds/vcloud/terremark/functions/ParseTaskFromLocationHeader.java +++ b/apis/vcloudexpress/src/main/java/org/jclouds/vcloud/functions/ParseTaskFromLocationHeader.java @@ -16,7 +16,8 @@ * limitations under the License. * ==================================================================== */ -package org.jclouds.vcloud.terremark.functions; + +package org.jclouds.vcloud.functions; import java.net.URI; import java.util.Date; diff --git a/apis/vcloudexpress/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java b/apis/vcloudexpress/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java index baaf3a9591..3dae72731f 100644 --- a/apis/vcloudexpress/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java +++ b/apis/vcloudexpress/src/test/java/org/jclouds/vcloud/VCloudExpressAsyncClientTest.java @@ -44,7 +44,6 @@ import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.util.Strings2; import org.jclouds.vcloud.config.VCloudExpressRestClientModule; @@ -60,6 +59,7 @@ import org.jclouds.vcloud.domain.internal.VDCImpl; import org.jclouds.vcloud.domain.network.FenceMode; import org.jclouds.vcloud.domain.network.NetworkConfig; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; +import org.jclouds.vcloud.functions.ParseTaskFromLocationHeader; import org.jclouds.vcloud.options.CloneVAppOptions; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.jclouds.vcloud.xml.CatalogHandler; @@ -500,9 +500,9 @@ public class VCloudExpressAsyncClientTest extends RestClientTest passwordGenerator, Predicate successTester, - Map vAppStatusToNodeState, Map credentialStore, - InternetServiceAndPublicIpAddressSupplier internetServiceAndPublicIpAddressSupplier) { + PopulateDefaultLoginCredentialsForImageStrategy credentialsProvider, + @Named("PASSWORD") Provider passwordGenerator, Predicate successTester, + Map vAppStatusToNodeState, Map credentialStore, + InternetServiceAndPublicIpAddressSupplier internetServiceAndPublicIpAddressSupplier) { super(client, successTester, vAppStatusToNodeState); this.client = client; this.credentialsProvider = credentialsProvider; @@ -85,7 +85,7 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl @Override public VCloudExpressVApp start(@Nullable URI VDC, URI templateId, String name, - InstantiateVAppTemplateOptions options, int... portsToOpen) { + InstantiateVAppTemplateOptions options, int... portsToOpen) { if (options.getDiskSizeKilobytes() != null) { logger.warn("trmk does not support resizing the primary disk; unsetting disk size"); } @@ -95,7 +95,7 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl String password = null; VCloudExpressVAppTemplate template = client.getVAppTemplate(templateId); if (template.getDescription().indexOf("Windows") != -1 - && options instanceof TerremarkInstantiateVAppTemplateOptions) { + && options instanceof TerremarkInstantiateVAppTemplateOptions) { password = passwordGenerator.get(); TerremarkInstantiateVAppTemplateOptions.class.cast(options).getProperties().put("password", password); } @@ -104,7 +104,7 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl VCloudExpressVApp vAppResponse = super.start(VDC, templateId, name, options, portsToOpen); if (password != null) { credentialStore.put("node#" + vAppResponse.getHref().toASCIIString(), new Credentials( - defaultCredentials.identity, password)); + defaultCredentials.identity, password)); } if (portsToOpen.length > 0) createPublicAddressMappedToPorts(vAppResponse.getHref(), portsToOpen); @@ -119,37 +119,41 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl InternetService is = null; Protocol protocol; switch (port) { - case 22: - protocol = Protocol.TCP; - break; - case 80: - case 8080: - protocol = Protocol.HTTP; - break; - case 443: - protocol = Protocol.HTTPS; - break; - default: - protocol = Protocol.HTTP; - break; + case 22: + protocol = Protocol.TCP; + break; + case 80: + case 8080: + protocol = Protocol.HTTP; + break; + case 443: + protocol = Protocol.HTTPS; + break; + default: + protocol = Protocol.HTTP; + break; } if (ip == null) { Entry entry = internetServiceAndPublicIpAddressSupplier - .getNewInternetServiceAndIp(vApp, port, protocol); + .getNewInternetServiceAndIp(vApp, port, protocol); is = entry.getKey(); ip = entry.getValue(); } else { logger.debug(">> adding InternetService %s:%s:%d", ip.getAddress(), protocol, port); - is = client.addInternetServiceToExistingIp(ip.getId(), vApp.getName() + "-" + port, protocol, port, - withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), - vApp.getName()))); + is = client.addInternetServiceToExistingIp( + ip.getId(), + vApp.getName() + "-" + port, + protocol, + port, + withDescription(String.format("port %d access to serverId: %s name: %s", port, vApp.getName(), + vApp.getName()))); } - logger.debug("<< created InternetService(%s) %s:%s:%d", is.getName(), is.getPublicIpAddress().getAddress(), is - .getProtocol(), is.getPort()); + logger.debug("<< created InternetService(%s) %s:%s:%d", is.getName(), is.getPublicIpAddress().getAddress(), + is.getProtocol(), is.getPort()); logger.debug(">> adding Node %s:%d -> %s:%d", is.getPublicIpAddress().getAddress(), is.getPort(), - privateAddress, port); + privateAddress, port); Node node = client.addNode(is.getId(), privateAddress, vApp.getName() + "-" + port, port); logger.debug("<< added Node(%s)", node.getName()); } @@ -163,13 +167,13 @@ public class TerremarkVCloudComputeClient extends VCloudExpressComputeClientImpl if (vApp.getNetworkToAddresses().containsValue(node.getIpAddress())) { ipAddresses.add(service.getPublicIpAddress()); logger.debug(">> deleting Node(%s) %s:%d -> %s:%d", node.getName(), service.getPublicIpAddress() - .getAddress(), service.getPort(), node.getIpAddress(), node.getPort()); + .getAddress(), service.getPort(), node.getIpAddress(), node.getPort()); client.deleteNode(node.getId()); logger.debug("<< deleted Node(%s)", node.getName()); Set nodes = client.getNodes(service.getId()); if (nodes.size() == 0) { logger.debug(">> deleting InternetService(%s) %s:%d", service.getName(), service.getPublicIpAddress() - .getAddress(), service.getPort()); + .getAddress(), service.getPort()); client.deleteInternetService(service.getId()); logger.debug("<< deleted InternetService(%s)", service.getName()); continue SERVICE; diff --git a/core/src/main/java/org/jclouds/json/config/GsonModule.java b/core/src/main/java/org/jclouds/json/config/GsonModule.java index 1760798702..e0353efc7c 100644 --- a/core/src/main/java/org/jclouds/json/config/GsonModule.java +++ b/core/src/main/java/org/jclouds/json/config/GsonModule.java @@ -20,8 +20,10 @@ package org.jclouds.json.config; import java.lang.reflect.Type; import java.util.Date; +import java.util.Enumeration; import java.util.List; import java.util.Map; +import java.util.Properties; import javax.inject.Inject; import javax.inject.Singleton; @@ -33,6 +35,8 @@ import org.jclouds.json.Json; import org.jclouds.json.internal.EnumTypeAdapterThatReturnsFromValue; import org.jclouds.json.internal.GsonWrapper; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableMap.Builder; import com.google.common.collect.Maps; import com.google.common.primitives.Bytes; import com.google.gson.Gson; @@ -51,6 +55,7 @@ import com.google.gson.reflect.TypeToken; import com.google.inject.AbstractModule; import com.google.inject.ImplementedBy; import com.google.inject.Provides; +import com.google.inject.TypeLiteral; /** * Contains logic for parsing objects from Strings. @@ -63,13 +68,15 @@ public class GsonModule extends AbstractModule { @Provides @Singleton Gson provideGson(JsonBallAdapter jsonAdapter, DateAdapter adapter, ByteListAdapter byteListAdapter, - ByteArrayAdapter byteArrayAdapter, JsonAdapterBindings bindings) throws ClassNotFoundException, Exception { + ByteArrayAdapter byteArrayAdapter, SerializePropertiesDefaults propertiesAdapter, JsonAdapterBindings bindings) + throws ClassNotFoundException, Exception { GsonBuilder builder = new GsonBuilder(); JcloudsGsonPackageAccessor.registerTypeHierarchyAdapter(builder, Enum.class, new EnumTypeAdapterThatReturnsFromValue()); JcloudsGsonPackageAccessor.registerTypeHierarchyAdapter(builder, Map.class, new MapTypeAdapter()); builder.registerTypeAdapter(JsonBall.class, jsonAdapter); builder.registerTypeAdapter(Date.class, adapter); + builder.registerTypeAdapter(Properties.class, propertiesAdapter); builder.registerTypeAdapter(new TypeToken>() { }.getType(), byteListAdapter); builder.registerTypeAdapter(byte[].class, byteArrayAdapter); @@ -169,6 +176,28 @@ public class GsonModule extends AbstractModule { } + @Singleton + public static class SerializePropertiesDefaults implements JsonSerializer { + private final Json json; + private final Type mapType = new TypeLiteral>() { + }.getRawType(); + + @Inject + public SerializePropertiesDefaults(Json json) { + this.json = json; + } + + public JsonElement serialize(Properties src, Type typeOfSrc, JsonSerializationContext context) { + Builder srcMap = ImmutableMap. builder(); + for (Enumeration propNames = src.propertyNames(); propNames.hasMoreElements();) { + String propName = (String) propNames.nextElement(); + srcMap.put(propName, src.getProperty(propName)); + } + return new JsonLiteral(json.toJson(srcMap.build(), mapType)); + } + + } + @Singleton public static class CDateAdapter implements DateAdapter { private final DateService dateService; diff --git a/core/src/test/java/org/jclouds/json/JsonTest.java b/core/src/test/java/org/jclouds/json/JsonTest.java index 5b7d8bcb49..9224822a84 100644 --- a/core/src/test/java/org/jclouds/json/JsonTest.java +++ b/core/src/test/java/org/jclouds/json/JsonTest.java @@ -21,6 +21,7 @@ package org.jclouds.json; import static org.testng.Assert.assertEquals; import java.util.Map; +import java.util.Properties; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; @@ -44,6 +45,19 @@ public class JsonTest { private Test enumValue; } + public void testPropertiesSerializesDefaults() { + Properties props = new Properties(); + props.put("string", "string"); + props.put("number", "1"); + props.put("boolean", "true"); + assertEquals(json.toJson(props), "{\"string\":\"string\",\"boolean\":\"true\",\"number\":\"1\"}"); + Properties props3 = new Properties(props); + assertEquals(json.toJson(props3), "{\"string\":\"string\",\"boolean\":\"true\",\"number\":\"1\"}"); + Properties props2 = json.fromJson(json.toJson(props), Properties.class); + assertEquals(props2, props); + assertEquals(json.toJson(props2), json.toJson(props)); + } + public void testMapStringObjectWithAllValidValuesOneDeep() { Map map = Maps.newHashMap(); map.put("string", "string"); diff --git a/providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3AsyncClient.java b/providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3AsyncClient.java index 5c5ed564b2..1a0ea3e205 100644 --- a/providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3AsyncClient.java +++ b/providers/aws-s3/src/main/java/org/jclouds/aws/s3/AWSS3AsyncClient.java @@ -18,29 +18,13 @@ */ package org.jclouds.aws.s3; -/** - * - * - * ==================================================================== - * 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. - * ==================================================================== - */ - import static org.jclouds.blobstore.attr.BlobScopes.CONTAINER; import java.util.Map; +import javax.annotation.Nullable; import javax.ws.rs.DELETE; +import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; @@ -56,6 +40,7 @@ import org.jclouds.blobstore.attr.BlobScope; import org.jclouds.http.functions.ParseETagHeader; import org.jclouds.io.Payload; import org.jclouds.rest.annotations.BinderParam; +import org.jclouds.rest.annotations.Endpoint; import org.jclouds.rest.annotations.ExceptionParser; import org.jclouds.rest.annotations.ParamParser; import org.jclouds.rest.annotations.ParamValidators; @@ -63,14 +48,20 @@ import org.jclouds.rest.annotations.QueryParams; 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.ReturnVoidOnNotFoundOr404; import org.jclouds.s3.Bucket; import org.jclouds.s3.S3AsyncClient; +import org.jclouds.s3.S3Client; import org.jclouds.s3.binders.BindAsHostPrefixIfConfigured; import org.jclouds.s3.domain.ObjectMetadata; import org.jclouds.s3.filters.RequestAuthorizeSignature; +import org.jclouds.s3.functions.BindRegionToXmlPayload; +import org.jclouds.s3.functions.ReturnFalseIfBucketAlreadyOwnedByYouOrIllegalState; +import org.jclouds.s3.options.PutBucketOptions; import org.jclouds.s3.options.PutObjectOptions; import org.jclouds.s3.predicates.validators.BucketNameValidator; +import org.jclouds.s3.xml.LocationConstraintHandler; import com.google.common.util.concurrent.ListenableFuture; @@ -83,6 +74,31 @@ import com.google.common.util.concurrent.ListenableFuture; @RequestFilters(RequestAuthorizeSignature.class) @BlobScope(CONTAINER) public interface AWSS3AsyncClient extends S3AsyncClient { + /** + * @see S3Client#putBucketInRegion + */ + @Override + @PUT + @Path("/") + @Endpoint(Bucket.class) + @ExceptionParser(ReturnFalseIfBucketAlreadyOwnedByYouOrIllegalState.class) + ListenableFuture putBucketInRegion( + @BinderParam(BindRegionToXmlPayload.class) @Nullable String region, + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + PutBucketOptions... options); + + /** + * @see S3Client#getBucketLocation + */ + @Override + @GET + @QueryParams(keys = "location") + @Path("/") + @Endpoint(Bucket.class) + @XMLResponseParser(LocationConstraintHandler.class) + ListenableFuture getBucketLocation( + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName); + /** * @see AWSS3Client#initiateMultipartUpload */ @@ -91,9 +107,9 @@ public interface AWSS3AsyncClient extends S3AsyncClient { @Path("/{key}") @ResponseParser(UploadIdFromHttpResponseViaRegex.class) ListenableFuture initiateMultipartUpload( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") @ParamParser(ObjectMetadataKey.class) @BinderParam(BindObjectMetadataToRequest.class) ObjectMetadata objectMetadata, - PutObjectOptions... options); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") @ParamParser(ObjectMetadataKey.class) @BinderParam(BindObjectMetadataToRequest.class) ObjectMetadata objectMetadata, + PutObjectOptions... options); /** * @see AWSS3Client#abortMultipartUpload @@ -102,8 +118,8 @@ public interface AWSS3AsyncClient extends S3AsyncClient { @Path("/{key}") @ExceptionParser(ReturnVoidOnNotFoundOr404.class) ListenableFuture abortMultipartUpload( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key, @QueryParam("uploadId") String uploadId); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key, @QueryParam("uploadId") String uploadId); /** * @see AWSS3Client#uploadPart @@ -112,9 +128,9 @@ public interface AWSS3AsyncClient extends S3AsyncClient { @Path("/{key}") @ResponseParser(ParseETagHeader.class) ListenableFuture uploadPart( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key, @QueryParam("partNumber") int partNumber, - @QueryParam("uploadId") String uploadId, Payload part); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key, @QueryParam("partNumber") int partNumber, + @QueryParam("uploadId") String uploadId, Payload part); /** * @see AWSS3Client#completeMultipartUpload @@ -123,8 +139,8 @@ public interface AWSS3AsyncClient extends S3AsyncClient { @Path("/{key}") @ResponseParser(ETagFromHttpResponseViaRegex.class) ListenableFuture completeMultipartUpload( - @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators( { BucketNameValidator.class }) String bucketName, - @PathParam("key") String key, @QueryParam("uploadId") String uploadId, - @BinderParam(BindPartIdsAndETagsToRequest.class) Map parts); + @Bucket @BinderParam(BindAsHostPrefixIfConfigured.class) @ParamValidators({ BucketNameValidator.class }) String bucketName, + @PathParam("key") String key, @QueryParam("uploadId") String uploadId, + @BinderParam(BindPartIdsAndETagsToRequest.class) Map parts); } diff --git a/providers/aws-s3/src/main/java/org/jclouds/aws/s3/config/AWSS3RestClientModule.java b/providers/aws-s3/src/main/java/org/jclouds/aws/s3/config/AWSS3RestClientModule.java index fbd3933472..b2b8465fed 100644 --- a/providers/aws-s3/src/main/java/org/jclouds/aws/s3/config/AWSS3RestClientModule.java +++ b/providers/aws-s3/src/main/java/org/jclouds/aws/s3/config/AWSS3RestClientModule.java @@ -18,14 +18,24 @@ */ package org.jclouds.aws.s3.config; +import static org.jclouds.aws.domain.Region.US_STANDARD; +import static org.jclouds.location.reference.LocationConstants.ENDPOINT; +import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGION; + +import java.net.URI; + +import javax.inject.Named; import javax.inject.Singleton; import org.jclouds.aws.s3.AWSS3AsyncClient; import org.jclouds.aws.s3.AWSS3Client; +import org.jclouds.aws.s3.binders.AssignCorrectHostnameAndBindAsHostPrefixIfConfigured; import org.jclouds.http.RequiresHttp; import org.jclouds.rest.ConfiguresRestClient; +import org.jclouds.s3.Bucket; import org.jclouds.s3.S3AsyncClient; import org.jclouds.s3.S3Client; +import org.jclouds.s3.binders.BindAsHostPrefixIfConfigured; import org.jclouds.s3.config.S3RestClientModule; import com.google.inject.Provides; @@ -39,6 +49,19 @@ import com.google.inject.Provides; @ConfiguresRestClient public class AWSS3RestClientModule extends S3RestClientModule { + @Provides + @Singleton + @Bucket + protected URI provideLocationURI(@Named(PROPERTY_REGION + "." + US_STANDARD + "." + ENDPOINT) String endpoint) { + return URI.create(endpoint); + } + + @Override + protected void configure() { + bind(BindAsHostPrefixIfConfigured.class).to(AssignCorrectHostnameAndBindAsHostPrefixIfConfigured.class); + super.configure(); + } + public AWSS3RestClientModule() { super(AWSS3Client.class, AWSS3AsyncClient.class); } diff --git a/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3AsyncClientTest.java b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3AsyncClientTest.java index 865c31c3a9..0ee634a309 100644 --- a/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3AsyncClientTest.java +++ b/providers/aws-s3/src/test/java/org/jclouds/aws/s3/AWSS3AsyncClientTest.java @@ -21,8 +21,10 @@ package org.jclouds.aws.s3; import java.io.IOException; import java.lang.reflect.Array; import java.lang.reflect.Method; +import java.net.URI; import java.util.Map; import java.util.Properties; +import java.util.concurrent.ConcurrentMap; import org.jclouds.aws.s3.config.AWSS3RestClientModule; import org.jclouds.aws.s3.functions.ETagFromHttpResponseViaRegex; @@ -31,6 +33,7 @@ import org.jclouds.date.TimeStamp; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.http.functions.ParseETagHeader; +import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.io.Payload; @@ -40,15 +43,18 @@ import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.functions.MapHttp4xxCodesToExceptions; import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; +import org.jclouds.s3.S3AsyncClient; import org.jclouds.s3.domain.ObjectMetadata; import org.jclouds.s3.domain.ObjectMetadataBuilder; import org.jclouds.s3.functions.ReturnFalseIfBucketAlreadyOwnedByYouOrIllegalState; import org.jclouds.s3.options.PutBucketOptions; import org.jclouds.s3.options.PutObjectOptions; +import org.jclouds.s3.xml.LocationConstraintHandler; import org.testng.annotations.Test; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; import com.google.inject.Module; import com.google.inject.TypeLiteral; @@ -63,6 +69,21 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest> createTypeLiteral() { return new TypeLiteral>() { @@ -75,15 +96,15 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest of(1, "\"a54357aff0632cce46d942af68356b38\"")); + String.class, Map.class); + HttpRequest request = processor.createRequest(method, "bucket", "foo", "asdsadasdas", + ImmutableMap. of(1, "\"a54357aff0632cce46d942af68356b38\"")); assertRequestLineEquals(request, "POST https://bucket." + url + "/foo?uploadId=asdsadasdas HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Host: bucket." + url + "\n"); assertPayloadEquals( - request, - "1\"a54357aff0632cce46d942af68356b38\"", - "text/xml", false); + request, + "1\"a54357aff0632cce46d942af68356b38\"", + "text/xml", false); assertResponseParserClassEquals(method, request, ETagFromHttpResponseViaRegex.class); assertSaxResponseParserClassEquals(method, null); @@ -160,16 +180,16 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTestEU", - "text/xml", false); + "EU", + "text/xml", false); assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); assertSaxResponseParserClassEquals(method, null); @@ -186,6 +206,18 @@ public class AWSS3AsyncClientTest extends org.jclouds.s3.S3AsyncClientTest bucketToRegion() { + ConcurrentMap returnVal = Maps.newConcurrentMap(); + returnVal.put("eubucket", "EU"); + return returnVal; + } + + @Override + protected URI provideLocationURI(String endpoint) { + return URI.create("https://bucket"); + } + @Override protected String provideTimeStamp(@TimeStamp Supplier cache) { return "2009-11-08T15:54:08.897Z"; diff --git a/providers/trmk-ecloud/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java b/providers/trmk-ecloud/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java index 34b49a0880..6bf0e59cc5 100644 --- a/providers/trmk-ecloud/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java +++ b/providers/trmk-ecloud/src/test/java/org/jclouds/vcloud/terremark/TerremarkECloudAsyncClientTest.java @@ -48,9 +48,9 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.util.Strings2; import org.jclouds.vcloud.CommonVCloudClient; -import org.jclouds.vcloud.VCloudVersionsAsyncClient; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogItemSupplier; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogSupplier; +import org.jclouds.vcloud.VCloudVersionsAsyncClient; import org.jclouds.vcloud.config.CommonVCloudRestClientModule.OrgVDCSupplier; import org.jclouds.vcloud.domain.AllocationModel; import org.jclouds.vcloud.domain.Capacity; @@ -62,6 +62,7 @@ import org.jclouds.vcloud.domain.VDCStatus; import org.jclouds.vcloud.domain.internal.ReferenceTypeImpl; import org.jclouds.vcloud.domain.network.NetworkConfig; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; +import org.jclouds.vcloud.functions.ParseTaskFromLocationHeader; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.jclouds.vcloud.terremark.config.TerremarkECloudRestClientModule; import org.jclouds.vcloud.terremark.domain.Protocol; @@ -104,8 +105,8 @@ import com.google.inject.TypeLiteral; public class TerremarkECloudAsyncClientTest extends RestClientTest { public void testNetwork() throws SecurityException, NoSuchMethodException, IOException { Method method = TerremarkECloudAsyncClient.class.getMethod("getNetwork", URI.class); - HttpRequest request = processor.createRequest(method, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2")); + HttpRequest request = processor.createRequest(method, + URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2")); assertRequestLineEquals(request, "GET https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2 HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/vnd.vmware.vcloud.network+xml\n"); @@ -118,9 +119,25 @@ public class TerremarkECloudAsyncClientTest extends RestClientTestnametrueeggs", - "application/vnd.tmrk.vCloud.nodeService+xml", false); + request, + "nametrueeggs", + "application/vnd.tmrk.vCloud.nodeService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -390,16 +414,16 @@ public class TerremarkECloudAsyncClientTest extends RestClientTestnametrue", - "application/vnd.tmrk.vCloud.nodeService+xml", false); + request, + "nametrue", + "application/vnd.tmrk.vCloud.nodeService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -443,7 +467,7 @@ public class TerremarkECloudAsyncClientTest extends RestClientTest get() { - return ImmutableMap. of("org", new TerremarkOrgImpl("org", null, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/org/1"), null, ImmutableMap - . of("catalog", new ReferenceTypeImpl("catalog", - TerremarkECloudMediaType.CATALOG_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1"))), ImmutableMap - . of("vdc", new ReferenceTypeImpl("vdc", TerremarkECloudMediaType.VDC_XML, - URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"))), ImmutableMap - . of(), new ReferenceTypeImpl("tasksList", - TerremarkECloudMediaType.TASKSLIST_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/tasksList/1")), new ReferenceTypeImpl( - "keysList", TerremarkECloudMediaType.KEYSLIST_XML, URI + return ImmutableMap. of( + "org", + new TerremarkOrgImpl("org", null, URI.create("https://vcloud.safesecureweb.com/api/v0.8/org/1"), + null, ImmutableMap. of( + "catalog", + new ReferenceTypeImpl("catalog", TerremarkECloudMediaType.CATALOG_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1"))), ImmutableMap + . of( + "vdc", + new ReferenceTypeImpl("vdc", TerremarkECloudMediaType.VDC_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"))), ImmutableMap + . of(), new ReferenceTypeImpl("tasksList", + TerremarkECloudMediaType.TASKSLIST_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/tasksList/1")), + new ReferenceTypeImpl("keysList", TerremarkECloudMediaType.KEYSLIST_XML, URI .create("https://vcloud.safesecureweb.com/api/v0.8/keysList/1")))); } } @@ -643,7 +670,7 @@ public class TerremarkECloudAsyncClientTest extends RestClientTest> vDCtoOrgSupplier) { + @org.jclouds.vcloud.endpoints.VDC Supplier> vDCtoOrgSupplier) { return "vdc"; } @@ -664,21 +691,25 @@ public class TerremarkECloudAsyncClientTest extends RestClientTest> get() { return ImmutableMap.> of("org", - ImmutableMap. of("vdc", new TerremarkVDCImpl("vdc", null, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), VDCStatus.READY, null, "description", - ImmutableSet. of(), AllocationModel.UNRECOGNIZED, new Capacity("MB", 0, 0, 0, 0), new Capacity( - "MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), ImmutableMap. of( - "vapp", new ReferenceTypeImpl("vapp", "application/vnd.vmware.vcloud.vApp+xml", URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vApp/188849-1")), "network", + ImmutableMap. of( + "vdc", + new TerremarkVDCImpl("vdc", null, URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), + VDCStatus.READY, null, "description", ImmutableSet. of(), AllocationModel.UNRECOGNIZED, + new Capacity("MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), + ImmutableMap. of( + "vapp", + new ReferenceTypeImpl("vapp", "application/vnd.vmware.vcloud.vApp+xml", URI + .create("https://vcloud.safesecureweb.com/api/v0.8/vApp/188849-1")), + "network", new ReferenceTypeImpl("network", "application/vnd.vmware.vcloud.vAppTemplate+xml", URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2"))), ImmutableMap + .create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2"))), ImmutableMap . of(), 0, 0, 0, false, new ReferenceTypeImpl("catalog", TerremarkVCloudMediaType.CATALOG_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1")), - new ReferenceTypeImpl("publicIps", TerremarkVCloudMediaType.PUBLICIPSLIST_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1")), + new ReferenceTypeImpl("publicIps", TerremarkVCloudMediaType.PUBLICIPSLIST_XML, URI .create("https://vcloud.safesecureweb.com/api/v0.8/publicIps/1")), new ReferenceTypeImpl( "internetServices", TerremarkVCloudMediaType.INTERNETSERVICESLIST_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/internetServices/1"))))); + .create("https://vcloud.safesecureweb.com/api/v0.8/internetServices/1"))))); } } } diff --git a/providers/trmk-vcloudexpress/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClientTest.java b/providers/trmk-vcloudexpress/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClientTest.java index 08bbd70143..f92608bdb6 100644 --- a/providers/trmk-vcloudexpress/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClientTest.java +++ b/providers/trmk-vcloudexpress/src/test/java/org/jclouds/vcloud/terremark/TerremarkVCloudExpressAsyncClientTest.java @@ -48,9 +48,9 @@ import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.jclouds.util.Strings2; import org.jclouds.vcloud.CommonVCloudClient; -import org.jclouds.vcloud.VCloudVersionsAsyncClient; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogItemSupplier; import org.jclouds.vcloud.VCloudExpressAsyncClientTest.VCloudRestClientModuleExtension.TestOrgCatalogSupplier; +import org.jclouds.vcloud.VCloudVersionsAsyncClient; import org.jclouds.vcloud.domain.AllocationModel; import org.jclouds.vcloud.domain.Capacity; import org.jclouds.vcloud.domain.Catalog; @@ -62,6 +62,7 @@ import org.jclouds.vcloud.domain.VDCStatus; import org.jclouds.vcloud.domain.internal.ReferenceTypeImpl; import org.jclouds.vcloud.domain.network.NetworkConfig; import org.jclouds.vcloud.filters.SetVCloudTokenCookie; +import org.jclouds.vcloud.functions.ParseTaskFromLocationHeader; import org.jclouds.vcloud.options.InstantiateVAppTemplateOptions; import org.jclouds.vcloud.terremark.config.TerremarkVCloudExpressRestClientModule; import org.jclouds.vcloud.terremark.domain.Protocol; @@ -104,8 +105,8 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTestnametrueeggs", - "application/vnd.tmrk.vCloud.nodeService+xml", false); + request, + "nametrueeggs", + "application/vnd.tmrk.vCloud.nodeService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -404,16 +436,16 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTestnametrue", - "application/vnd.tmrk.vCloud.nodeService+xml", false); + request, + "nametrue", + "application/vnd.tmrk.vCloud.nodeService+xml", false); assertResponseParserClassEquals(method, request, ParseSax.class); assertSaxResponseParserClassEquals(method, NodeHandler.class); assertExceptionParserClassEquals(method, null); @@ -453,12 +485,12 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTest createContextSpec() { return new RestContextFactory().createContextSpec("trmk-vcloudexpress", "identity", "credential", - new Properties()); + new Properties()); } @RequiresHttp @@ -604,7 +636,7 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTest get() { - return ImmutableMap. of("org", new TerremarkOrgImpl("org", null, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/org/1"), null, ImmutableMap - . of("catalog", new ReferenceTypeImpl("catalog", - TerremarkVCloudExpressMediaType.CATALOG_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1"))), ImmutableMap - . of("vdc", new ReferenceTypeImpl("vdc", - TerremarkVCloudExpressMediaType.VDC_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"))), ImmutableMap - . of(), new ReferenceTypeImpl("tasksList", - TerremarkVCloudExpressMediaType.TASKSLIST_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/tasksList/1")), new ReferenceTypeImpl( - "keysList", TerremarkVCloudExpressMediaType.KEYSLIST_XML, URI + return ImmutableMap. of( + "org", + new TerremarkOrgImpl("org", null, URI.create("https://vcloud.safesecureweb.com/api/v0.8/org/1"), + null, ImmutableMap. of( + "catalog", + new ReferenceTypeImpl("catalog", TerremarkVCloudExpressMediaType.CATALOG_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1"))), ImmutableMap + . of( + "vdc", + new ReferenceTypeImpl("vdc", TerremarkVCloudExpressMediaType.VDC_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"))), ImmutableMap + . of(), new ReferenceTypeImpl("tasksList", + TerremarkVCloudExpressMediaType.TASKSLIST_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/tasksList/1")), + new ReferenceTypeImpl("keysList", TerremarkVCloudExpressMediaType.KEYSLIST_XML, URI .create("https://vcloud.safesecureweb.com/api/v0.8/keysList/1")))); } } @@ -703,22 +738,25 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTest> get() { return ImmutableMap.> of("org", - ImmutableMap. of("vdc", new TerremarkVDCImpl("vdc", null, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), VDCStatus.READY, null, "description", - ImmutableSet. of(), AllocationModel.UNRECOGNIZED, new Capacity("MB", 0, 0, 0, 0), - new Capacity("MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), - ImmutableMap. of("vapp", new ReferenceTypeImpl("vapp", - "application/vnd.vmware.vcloud.vApp+xml", URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vApp/188849-1")), "network", + ImmutableMap. of( + "vdc", + new TerremarkVDCImpl("vdc", null, URI.create("https://vcloud.safesecureweb.com/api/v0.8/vdc/1"), + VDCStatus.READY, null, "description", ImmutableSet. of(), AllocationModel.UNRECOGNIZED, + new Capacity("MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), new Capacity("MB", 0, 0, 0, 0), + ImmutableMap. of( + "vapp", + new ReferenceTypeImpl("vapp", "application/vnd.vmware.vcloud.vApp+xml", URI + .create("https://vcloud.safesecureweb.com/api/v0.8/vApp/188849-1")), + "network", new ReferenceTypeImpl("network", "application/vnd.vmware.vcloud.vAppTemplate+xml", URI - .create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2"))), ImmutableMap + .create("https://vcloud.safesecureweb.com/api/v0.8/vdcItem/2"))), ImmutableMap . of(), 0, 0, 0, false, new ReferenceTypeImpl("catalog", TerremarkVCloudExpressMediaType.CATALOG_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1")), - new ReferenceTypeImpl("publicIps", TerremarkVCloudExpressMediaType.PUBLICIPSLIST_XML, URI + .create("https://vcloud.safesecureweb.com/api/v0.8/catalog/1")), + new ReferenceTypeImpl("publicIps", TerremarkVCloudExpressMediaType.PUBLICIPSLIST_XML, URI .create("https://vcloud.safesecureweb.com/api/v0.8/publicIps/1")), new ReferenceTypeImpl( "internetServices", TerremarkVCloudExpressMediaType.INTERNETSERVICESLIST_XML, URI - .create("https://vcloud.safesecureweb.com/api/v0.8/internetServices/1"))))); + .create("https://vcloud.safesecureweb.com/api/v0.8/internetServices/1"))))); } } @@ -734,7 +772,7 @@ public class TerremarkVCloudExpressAsyncClientTest extends RestClientTest> vDCtoOrgSupplier) { + @org.jclouds.vcloud.endpoints.VDC Supplier> vDCtoOrgSupplier) { return "vdc"; } From cea0e7d7ad0581cb404098b1480ce1473ecf695f Mon Sep 17 00:00:00 2001 From: David Santiago Date: Thu, 21 Apr 2011 04:03:58 -0500 Subject: [PATCH 02/95] Update blobstore2 to have a convenience protocol for building blob payloads. * Added PayloadSource protocol with a number of implementations, including all currently covered classes. * Added implementation for clojure.lang.IFn, so that you can pass in a closure. * Updated blob function to pass the :payload argument through the payload protocol function. * Added some tests for the payload protocol. --- .../main/clojure/org/jclouds/blobstore2.clj | 43 +++++++++++++++++-- .../clojure/org/jclouds/blobstore2_test.clj | 36 +++++++++++++++- 2 files changed, 75 insertions(+), 4 deletions(-) diff --git a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj index 7621f98334..f3190da05a 100644 --- a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj +++ b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj @@ -50,7 +50,7 @@ See http://code.google.com/p/jclouds for details." domain.Blob domain.internal.BlobBuilderImpl options.PutOptions options.PutOptions$Builder options.CreateContainerOptions options.ListContainerOptions] - org.jclouds.io.Payloads + [org.jclouds.io Payload Payloads payloads.StreamingPayload] java.util.Arrays [java.security DigestOutputStream MessageDigest] com.google.common.collect.ImmutableSet @@ -73,6 +73,39 @@ See http://code.google.com/p/jclouds for details." (catch Exception e (JCECrypto.)))) +;; +;; Payload support for creating Blobs. +;; + +(def ^{:doc "Type object for a Java primitive byte array, for use in the + PayloadSource protocol." + :private true} + byte-array-type (class (make-array Byte/TYPE 0))) + +(defprotocol PayloadSource + "Various types can have PayloadSource extended onto them so that they are + easily coerced into a Payload." + (^Payload payload [arg] "Coerce arg into a Payload.")) + +(extend-protocol PayloadSource + Payload + (payload [p] p) + java.io.InputStream + (payload [is] (Payloads/newInputStreamPayload is)) + byte-array-type + (payload [ba] (Payloads/newByteArrayPayload ba)) + String + (payload [s] (Payloads/newStringPayload s)) + java.io.File + (payload [f] (Payloads/newFilePayload f)) + clojure.lang.IFn + ;; This will let you pass a closure to payload that takes an OutputStream + ;; as argument and writes to it when called from a StreamingPayload. + (payload [func] + (StreamingPayload. (reify org.jclouds.io.WriteTo + (writeTo [this output-stream] + (func output-stream)))))) + (defn blobstore "Create a logged in context. Options for communication style @@ -278,7 +311,10 @@ Options can also be specified for extension modules (.countBlobs blobstore container-name)) (defn blob - "Create a new blob with the specified payload and options." + "Create a new blob with the specified payload and options. + + The payload argument can be anything accepted by org.jclouds.io.Payloads, or + you can make one manually (recommended) with the payload protocol function." ([^String name & {:keys [payload content-type content-length content-md5 calculate-md5 content-disposition content-encoding content-language metadata]}] @@ -286,7 +322,8 @@ Options can also be specified for extension modules (not (and (nil? payload) calculate-md5))]} (let [blob-builder (.name (BlobBuilderImpl. crypto-impl) name) blob-builder (if payload - (.payload blob-builder payload) + (.payload blob-builder + (org.jclouds.blobstore2/payload payload)) (.forSigning blob-builder)) blob-builder (if content-length ;; Special case, arg is prim. (.contentLength blob-builder content-length) diff --git a/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj b/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj index 02673198e7..1afa747e39 100644 --- a/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj +++ b/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj @@ -22,7 +22,8 @@ (:use [clojure.test]) (:import [org.jclouds.blobstore BlobStoreContextFactory] [org.jclouds.crypto CryptoStreams] - [java.io ByteArrayOutputStream] + [java.io ByteArrayInputStream ByteArrayOutputStream + StringBufferInputStream] [org.jclouds.util Strings2])) (defn clean-stub-fixture @@ -157,4 +158,37 @@ (is (= (seq (.. a-blob (getPayload) (getContentMetadata) (getContentMD5))) (seq (CryptoStreams/md5 (.getBytes "test-payload"))))))) +(deftest payload-protocol-test + (is (instance? org.jclouds.io.Payload (payload "test"))) + (is (blob "blob1" :payload (payload "blob1"))) + (is (create-container *blobstore* "container")) + (is (= "blob1" + (do + (put-blob *blobstore* "container" + (blob "blob1" + :payload "blob1")) + (Strings2/toStringAndClose (get-blob-stream *blobstore* + "container" "blob1"))))) + (is (= "blob1" + (do + (put-blob *blobstore* "container" + (blob "blob1" + :payload (StringBufferInputStream. "blob1"))) + (Strings2/toStringAndClose (get-blob-stream *blobstore* + "container" "blob1"))))) + (is (= "blob1" + (do + (put-blob *blobstore* "container" + (blob "blob1" + :payload (.getBytes "blob1"))) + (Strings2/toStringAndClose (get-blob-stream *blobstore* + "container" "blob1"))))) + (is (= "blob1" + (do + (put-blob *blobstore* "container" + (blob "blob1" + :payload #(.write % (.getBytes "blob1")))) + (Strings2/toStringAndClose (get-blob-stream *blobstore* + "container" "blob1")))))) + ;; TODO: more tests involving blob-specific functions From 6152de91c5b17dc866a14b389d3ad4440bbca3f9 Mon Sep 17 00:00:00 2001 From: David Santiago Date: Thu, 21 Apr 2011 11:32:42 -0500 Subject: [PATCH 03/95] Small enhancements to blobstore2_test. Made each test clause insert a uniquely named blob, to reduce risk that an earlier correct result masquerades as a success in a later clause. --- .../clojure/org/jclouds/blobstore2_test.clj | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj b/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj index 1afa747e39..b520995709 100644 --- a/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj +++ b/blobstore/src/test/clojure/org/jclouds/blobstore2_test.clj @@ -169,26 +169,26 @@ :payload "blob1")) (Strings2/toStringAndClose (get-blob-stream *blobstore* "container" "blob1"))))) - (is (= "blob1" + (is (= "blob2" (do (put-blob *blobstore* "container" - (blob "blob1" - :payload (StringBufferInputStream. "blob1"))) + (blob "blob2" + :payload (StringBufferInputStream. "blob2"))) (Strings2/toStringAndClose (get-blob-stream *blobstore* - "container" "blob1"))))) - (is (= "blob1" + "container" "blob2"))))) + (is (= "blob3" (do (put-blob *blobstore* "container" - (blob "blob1" - :payload (.getBytes "blob1"))) + (blob "blob3" + :payload (.getBytes "blob3"))) (Strings2/toStringAndClose (get-blob-stream *blobstore* - "container" "blob1"))))) - (is (= "blob1" + "container" "blob3"))))) + (is (= "blob4" (do (put-blob *blobstore* "container" - (blob "blob1" - :payload #(.write % (.getBytes "blob1")))) + (blob "blob4" + :payload #(.write % (.getBytes "blob4")))) (Strings2/toStringAndClose (get-blob-stream *blobstore* - "container" "blob1")))))) + "container" "blob4")))))) ;; TODO: more tests involving blob-specific functions From 29744fdddadd1fcb708584be449c20bd7b1db698 Mon Sep 17 00:00:00 2001 From: David Santiago Date: Thu, 21 Apr 2011 11:36:47 -0500 Subject: [PATCH 04/95] Clean up a comment on the blobstore2/blob function. --- blobstore/src/main/clojure/org/jclouds/blobstore2.clj | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj index f3190da05a..af244898bf 100644 --- a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj +++ b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj @@ -313,8 +313,7 @@ Options can also be specified for extension modules (defn blob "Create a new blob with the specified payload and options. - The payload argument can be anything accepted by org.jclouds.io.Payloads, or - you can make one manually (recommended) with the payload protocol function." + The payload argument can be anything accepted by org.jclouds.io.Payloads." ([^String name & {:keys [payload content-type content-length content-md5 calculate-md5 content-disposition content-encoding content-language metadata]}] From 6a3ce93d26873da89b9547f1eeb4bf8a4fe60ef5 Mon Sep 17 00:00:00 2001 From: David Santiago Date: Thu, 21 Apr 2011 14:05:51 -0500 Subject: [PATCH 05/95] Clean up a comment on the blobstore2/blob function. For realsies. --- blobstore/src/main/clojure/org/jclouds/blobstore2.clj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj index af244898bf..d98dc74ad8 100644 --- a/blobstore/src/main/clojure/org/jclouds/blobstore2.clj +++ b/blobstore/src/main/clojure/org/jclouds/blobstore2.clj @@ -313,7 +313,7 @@ Options can also be specified for extension modules (defn blob "Create a new blob with the specified payload and options. - The payload argument can be anything accepted by org.jclouds.io.Payloads." + The payload argument can be anything accepted by the PayloadSource protocol." ([^String name & {:keys [payload content-type content-length content-md5 calculate-md5 content-disposition content-encoding content-language metadata]}] From 159224de89090c1f6d8d9b199fc8dd1cb7da73d3 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Tue, 5 Apr 2011 22:06:20 +0400 Subject: [PATCH 06/95] Properties builder for Nova, simple client app to test API --- .../openstack/nova/NovaPropertiesBuilder.java | 45 +++++++++++++++++++ .../jclouds/openstack/nova/_NovaClient.java | 24 ++++++++++ 2 files changed, 69 insertions(+) create mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java new file mode 100644 index 0000000000..051a8b532b --- /dev/null +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java @@ -0,0 +1,45 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova; + +import org.jclouds.PropertiesBuilder; + +import java.util.Properties; + +/** + * Builds properties used in Openstack Nova Clients + * + * @author Dmitri Babaev + */ +public class NovaPropertiesBuilder extends PropertiesBuilder { + @Override + protected Properties defaultProperties() { + Properties properties = super.defaultProperties(); + return properties; + } + + public NovaPropertiesBuilder(Properties properties) { + super(properties); + } + + public NovaPropertiesBuilder() { + super(); + } +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java new file mode 100644 index 0000000000..e438d2f906 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -0,0 +1,24 @@ +package org.jclouds.openstack.nova; + +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.ssh.jsch.config.JschSshClientModule; + +import java.util.Collections; +import java.util.Properties; + +import static org.jclouds.Constants.PROPERTY_ENDPOINT; + +public class _NovaClient { + static public void main(String[] args) { + String identity = "admin"; + String credential = ""; + String endpoint = ""; + + ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); + + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_ENDPOINT, endpoint); + ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, Collections.singleton(new JschSshClientModule()), overrides); + } +} From 402ee2adbec9dbdac7820f98b83e8ba482349fe5 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Tue, 5 Apr 2011 23:27:42 +0400 Subject: [PATCH 07/95] api version in properties builder, more methods in simple client app --- .../openstack/nova/NovaPropertiesBuilder.java | 3 +++ .../org/jclouds/openstack/nova/_NovaClient.java | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java index 051a8b532b..9c0607d835 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java @@ -23,6 +23,8 @@ import org.jclouds.PropertiesBuilder; import java.util.Properties; +import static org.jclouds.Constants.PROPERTY_API_VERSION; + /** * Builds properties used in Openstack Nova Clients * @@ -32,6 +34,7 @@ public class NovaPropertiesBuilder extends PropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); + properties.setProperty(PROPERTY_API_VERSION, "1.0"); return properties; } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index e438d2f906..d9a7efa5a2 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,5 +1,6 @@ package org.jclouds.openstack.nova; +import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.ssh.jsch.config.JschSshClientModule; @@ -11,14 +12,23 @@ import static org.jclouds.Constants.PROPERTY_ENDPOINT; public class _NovaClient { static public void main(String[] args) { + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json + String identity = "admin"; - String credential = ""; - String endpoint = ""; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + String endpoint = "http://172.18.34.40:8774"; ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); Properties overrides = new Properties(); overrides.setProperty(PROPERTY_ENDPOINT, endpoint); ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, Collections.singleton(new JschSshClientModule()), overrides); + + ComputeService cs = context.getComputeService(); + System.out.println(cs.listImages()); + System.out.println(cs.listNodes()); + System.out.println(cs.listAssignableLocations()); + System.out.println(cs.listHardwareProfiles()); } } From e0a76aa08be824085b98cd06620c683916cba534 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Thu, 7 Apr 2011 20:46:51 +0400 Subject: [PATCH 08/95] API version is set to 1.1 by default ignoring nulls in name and field for image descriptions --- .../openstack/nova/NovaPropertiesBuilder.java | 2 +- .../compute/functions/NovaImageToImage.java | 6 ++--- .../strategy/NovaListNodesStrategy.java | 2 +- .../jclouds/openstack/nova/_NovaClient.java | 23 +++++++++++++++---- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java index 9c0607d835..5c808e974b 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaPropertiesBuilder.java @@ -34,7 +34,7 @@ public class NovaPropertiesBuilder extends PropertiesBuilder { @Override protected Properties defaultProperties() { Properties properties = super.defaultProperties(); - properties.setProperty(PROPERTY_API_VERSION, "1.0"); + properties.setProperty(PROPERTY_API_VERSION, "1.1"); return properties; } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index 23660c95d4..677a2262d5 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -44,10 +44,10 @@ public class NovaImageToImage implements Function listDetailsOnNodesMatching(Predicate filter) { - return Iterables.filter(Iterables.transform(client.listServers(ListOptions.Builder.withDetails()), + return Iterables.filter(Iterables.transform(client.listServers(/*ListOptions.Builder.withDetails()*/), serverToNodeMetadata), filter); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index d9a7efa5a2..6fdbedc28f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -3,6 +3,10 @@ package org.jclouds.openstack.nova; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.options.TemplateOptions; import org.jclouds.ssh.jsch.config.JschSshClientModule; import java.util.Collections; @@ -26,9 +30,20 @@ public class _NovaClient { ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, Collections.singleton(new JschSshClientModule()), overrides); ComputeService cs = context.getComputeService(); - System.out.println(cs.listImages()); - System.out.println(cs.listNodes()); - System.out.println(cs.listAssignableLocations()); - System.out.println(cs.listHardwareProfiles()); + + TemplateOptions options = new TemplateOptions(); + //options.authorizePublicKey(""); + Template template = cs.templateBuilder().hardwareId("m1.small").imageId("ami-0000000d").options(options).build(); + try { + cs.runNodesWithTag("test", 1, template); + } catch (RunNodesException e) { + e.printStackTrace(); + } + + //System.out.println(cs.listNodes()); + //System.out.println(cs.listImages()); + //System.out.println(cs.listNodes()); + //System.out.println(cs.listAssignableLocations()); + //System.out.println(cs.listHardwareProfiles()); } } From 4019137687cf262a913341abaf9159f65ca21ffb Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Thu, 7 Apr 2011 23:01:21 +0400 Subject: [PATCH 09/95] unspecified string instead of empty image name or description --- .../nova/compute/functions/NovaImageToImage.java | 6 +++--- .../functions/NovaImageToOperatingSystem.java | 12 +++++++----- .../nova/compute/strategy/NovaListNodesStrategy.java | 2 +- .../java/org/jclouds/openstack/nova/_NovaClient.java | 9 ++++++--- 4 files changed, 17 insertions(+), 12 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index 677a2262d5..9822046e8d 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -44,10 +44,10 @@ public class NovaImageToImage implements Function listDetailsOnNodesMatching(Predicate filter) { - return Iterables.filter(Iterables.transform(client.listServers(/*ListOptions.Builder.withDetails()*/), + return Iterables.filter(Iterables.transform(client.listServers(ListOptions.Builder.withDetails()), serverToNodeMetadata), filter); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index 6fdbedc28f..23f86b6b35 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -31,14 +31,17 @@ public class _NovaClient { ComputeService cs = context.getComputeService(); + System.out.println(cs.listImages()); + //System.out.println(cs.listNodes()); + TemplateOptions options = new TemplateOptions(); //options.authorizePublicKey(""); - Template template = cs.templateBuilder().hardwareId("m1.small").imageId("ami-0000000d").options(options).build(); - try { + Template template = cs.templateBuilder().hardwareId("m1.small").imageId("13").options(options).build(); + /*try { cs.runNodesWithTag("test", 1, template); } catch (RunNodesException e) { e.printStackTrace(); - } + }*/ //System.out.println(cs.listNodes()); //System.out.println(cs.listImages()); From 8fb5ec95552efa38f6460804250f569828fa3a75 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 8 Apr 2011 17:52:32 +0400 Subject: [PATCH 10/95] Added test properties template. Rearranged tests. --- sandbox-apis/nova/pom.xml | 15 +- .../openstack/nova/NovaClientLiveTest.java | 1076 +++++++++-------- .../compute/NovaComputeServiceLiveTest.java | 699 ++++++++++- .../test/resources/test.properties.template | 7 + 4 files changed, 1217 insertions(+), 580 deletions(-) create mode 100644 sandbox-apis/nova/src/test/resources/test.properties.template diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 13e3dda25b..4c7d2d609f 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -21,7 +21,7 @@ --> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4.0.0.xsd"> 4.0.0 org.jclouds @@ -42,6 +42,11 @@ + + org.jclouds.provider + aws-ec2 + ${project.version} + org.jclouds.common openstack-common @@ -131,6 +136,14 @@ test.nova.credential ${test.nova.credential} + + test.nova.credential + ${test.ssh.keyfile.public} + + + test.nova.credential + ${test.ssh.keyfile.private} + test.initializer ${test.initializer} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index abbd1a4d0a..e23449bd10 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -18,40 +18,21 @@ */ package org.jclouds.openstack.nova; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import java.security.SecureRandom; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.TimeUnit; - +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.Injector; +import com.google.inject.Module; import org.jclouds.Constants; -import org.jclouds.openstack.nova.domain.BackupSchedule; -import org.jclouds.openstack.nova.domain.DailyBackup; -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.ImageStatus; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.jclouds.openstack.nova.domain.SharedIpGroup; -import org.jclouds.openstack.nova.domain.WeeklyBackup; -import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.domain.*; +import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.SocketOpen; import org.jclouds.rest.RestContextFactory; @@ -63,576 +44,613 @@ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Injector; -import com.google.inject.Module; +import java.io.IOException; +import java.lang.reflect.UndeclaredThrowableException; +import java.security.SecureRandom; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.testng.Assert.*; /** * Tests behavior of {@code NovaClient} - * + * * @author Adrian Cole */ // disabled [Web Hosting #129069 @Test(groups = "live", sequential = true) public class NovaClientLiveTest { - protected NovaClient client; - protected SshClient.Factory sshFactory; - private Predicate socketTester; - protected String provider = "nova"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; + protected NovaClient client; + protected SshClient.Factory sshFactory; + private Predicate socketTester; + protected String provider = "nova"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; - protected void setupCredentials() { - identity = checkNotNull(System.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(System.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = System.getProperty("test." + provider + ".endpoint"); - apiversion = System.getProperty("test." + provider + ".apiversion"); - } + private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); + } - protected Properties setupProperties() { - Properties overrides = new Properties(); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - overrides.setProperty(provider + ".identity", identity); - overrides.setProperty(provider + ".credential", credential); - if (endpoint != null) - overrides.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - overrides.setProperty(provider + ".apiversion", apiversion); - return overrides; - } - @BeforeGroups(groups = { "live" }) - public void setupClient() { - setupCredentials(); - Properties overrides = setupProperties(); + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } - Injector injector = new RestContextFactory().createContextBuilder(provider, - ImmutableSet. of(new Log4JLoggingModule(), new JschSshClientModule()), overrides) - .buildInjector(); + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } - client = injector.getInstance(NovaClient.class); - sshFactory = injector.getInstance(SshClient.Factory.class); - SocketOpen socketOpen = injector.getInstance(SocketOpen.class); - socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); - injector.injectMembers(socketOpen); // add logger - } + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - public void testListServers() throws Exception { + return overrides; + } - Set response = client.listServers(); - assert null != response; - long initialContainerCount = response.size(); - assertTrue(initialContainerCount >= 0); + @BeforeGroups(groups = {"live"}) + public void setupClient() throws IOException { + Properties overrides = setupProperties(); + setupCredentials(overrides); + updateProperties(overrides); - } + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; +// ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); +// ComputeServiceContext context = contextFactory.createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides); - public void testListServersDetail() throws Exception { - Set response = client.listServers(withDetails()); - assert null != response; - long initialContainerCount = response.size(); - assertTrue(initialContainerCount >= 0); - } + Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, + ImmutableSet.of(new Log4JLoggingModule(), new JschSshClientModule()), overrides) + .buildInjector(); - public void testListImages() throws Exception { - Set response = client.listImages(); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 1); - for (Image image : response) { - assertTrue(image.getId() >= 0); - assert null != image.getName() : image; - } + client = injector.getInstance(NovaClient.class); - } + sshFactory = injector.getInstance(SshClient.Factory.class); + SocketOpen socketOpen = injector.getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); + injector.injectMembers(socketOpen); // add logger + } - public void testListImagesDetail() throws Exception { - Set response = client.listImages(withDetails()); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 0); - for (Image image : response) { - assertTrue(image.getId() >= 1); - assert null != image.getName() : image; - assert null != image.getStatus() : image; - } - } + @Test + public void testListServers() throws Exception { - public void testGetImagesDetail() throws Exception { - Set response = client.listImages(withDetails()); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 0); - for (Image image : response) { - try { - Image newDetails = client.getImage(image.getId()); - assertEquals(image, newDetails); - } catch (HttpResponseException e) {// Ticket #9867 - if (e.getResponse().getStatusCode() != 400) - throw e; - } - } - } + Set response = client.listServers(); + assert null != response; + long initialContainerCount = response.size(); + assertTrue(initialContainerCount >= 0); - @Test - public void testGetImageDetailsNotFound() throws Exception { - assert client.getImage(12312987) == null; - } + } - @Test - public void testGetServerDetailsNotFound() throws Exception { - assert client.getServer(12312987) == null; - } + @Test + public void testListServersDetail() throws Exception { + Set response = client.listServers(withDetails()); + assert null != response; + long initialContainerCount = response.size(); + assertTrue(initialContainerCount >= 0); + } - public void testGetServersDetail() throws Exception { - Set response = client.listServers(withDetails()); - assert null != response; - long serverCount = response.size(); - assertTrue(serverCount >= 0); - for (Server server : response) { - Server newDetails = client.getServer(server.getId()); - assertEquals(server, newDetails); - } - } + @Test + public void testListImages() throws Exception { + Set response = client.listImages(); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 1); + for (Image image : response) { + assertTrue(image.getId() >= 0); + assert null != image.getName() : image; + } - public void testListFlavors() throws Exception { - Set response = client.listFlavors(); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 1); - for (Flavor flavor : response) { - assertTrue(flavor.getId() >= 0); - assert null != flavor.getName() : flavor; - } + } - } + @Test + public void testListImagesDetail() throws Exception { + Set response = client.listImages(withDetails()); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 0); + for (Image image : response) { + assertTrue(image.getId() >= 1); + assert null != image.getName() : image; + assert null != image.getStatus() : image; + } + } - public void testListFlavorsDetail() throws Exception { - Set response = client.listFlavors(withDetails()); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 0); - for (Flavor flavor : response) { - assertTrue(flavor.getId() >= 1); - assert null != flavor.getName() : flavor; - assert null != flavor.getDisk() : flavor; - assert null != flavor.getRam() : flavor; - } - } + @Test + public void testGetImagesDetail() throws Exception { + Set response = client.listImages(withDetails()); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 0); + for (Image image : response) { + try { + Image newDetails = client.getImage(image.getId()); + assertEquals(image, newDetails); + } catch (HttpResponseException e) {// Ticket #9867 + if (e.getResponse().getStatusCode() != 400) + throw e; + } + } + } - public void testGetFlavorsDetail() throws Exception { - Set response = client.listFlavors(withDetails()); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 0); - for (Flavor flavor : response) { - Flavor newDetails = client.getFlavor(flavor.getId()); - assertEquals(flavor, newDetails); - } - } + @Test + public void testGetImageDetailsNotFound() throws Exception { + assert client.getImage(12312987) == null; + } - @Test - public void testGetFlavorDetailsNotFound() throws Exception { - assert client.getFlavor(12312987) == null; - } + @Test + public void testGetServerDetailsNotFound() throws Exception { + assert client.getServer(12312987) == null; + } - public void testListSharedIpGroups() throws Exception { - Set response = client.listSharedIpGroups(); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - assertTrue(sharedIpGroup.getId() >= 0); - assert null != sharedIpGroup.getName() : sharedIpGroup; - } + @Test + public void testGetServersDetail() throws Exception { + Set response = client.listServers(withDetails()); + assert null != response; + long serverCount = response.size(); + assertTrue(serverCount >= 0); + for (Server server : response) { + Server newDetails = client.getServer(server.getId()); + assertEquals(server, newDetails); + } + } - } + public void testListFlavors() throws Exception { + Set response = client.listFlavors(); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 1); + for (Flavor flavor : response) { + assertTrue(flavor.getId() >= 0); + assert null != flavor.getName() : flavor; + } - public void testListSharedIpGroupsDetail() throws Exception { - Set response = client.listSharedIpGroups(withDetails()); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - assertTrue(sharedIpGroup.getId() >= 1); - assert null != sharedIpGroup.getName() : sharedIpGroup; - assert null != sharedIpGroup.getServers() : sharedIpGroup; - } - } + } - public void testGetSharedIpGroupsDetail() throws Exception { - Set response = client.listSharedIpGroups(withDetails()); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - SharedIpGroup newDetails = client.getSharedIpGroup(sharedIpGroup.getId()); - assertEquals(sharedIpGroup, newDetails); - } - } + public void testListFlavorsDetail() throws Exception { + Set response = client.listFlavors(withDetails()); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 0); + for (Flavor flavor : response) { + assertTrue(flavor.getId() >= 1); + assert null != flavor.getName() : flavor; + assert null != flavor.getDisk() : flavor; + assert null != flavor.getRam() : flavor; + } + } - @Test - public void testGetSharedIpGroupDetailsNotFound() throws Exception { - assert client.getSharedIpGroup(12312987) == null; - } + public void testGetFlavorsDetail() throws Exception { + Set response = client.listFlavors(withDetails()); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 0); + for (Flavor flavor : response) { + Flavor newDetails = client.getFlavor(flavor.getId()); + assertEquals(flavor, newDetails); + } + } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testCreateSharedIpGroup() throws Exception { - SharedIpGroup sharedIpGroup = null; - while (sharedIpGroup == null) { - String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt(); - try { - sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } - assertNotNull(sharedIpGroup.getName()); - sharedIpGroupId = sharedIpGroup.getId(); - // Response doesn't include the server id Web Hosting #119311 - // assertEquals(sharedIpGroup.getServers(), ImmutableList.of(serverId)); - } + @Test + public void testGetFlavorDetailsNotFound() throws Exception { + assert client.getFlavor(12312987) == null; + } - private int sharedIpGroupId; + public void testListSharedIpGroups() throws Exception { + Set response = client.listSharedIpGroups(); + assert null != response; + long sharedIpGroupCount = response.size(); + assertTrue(sharedIpGroupCount >= 0); + for (SharedIpGroup sharedIpGroup : response) { + assertTrue(sharedIpGroup.getId() >= 0); + assert null != sharedIpGroup.getName() : sharedIpGroup; + } - private String serverPrefix = System.getProperty("user.name") + ".cs"; - private int serverId; - private String adminPass; - Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private String ip; - private int serverId2; - private String adminPass2; - private int imageId; + } - @Test(enabled = false) - public void testCreateServer() throws Exception { - int imageId = 14362; - int flavorId = 1; - Server server = null; - 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)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } - assertNotNull(server.getAdminPass()); - serverId = server.getId(); - adminPass = server.getAdminPass(); - ip = server.getAddresses().getPublicAddresses().iterator().next(); - assertEquals(server.getStatus(), ServerStatus.BUILD); - blockUntilServerActive(serverId); - } + public void testListSharedIpGroupsDetail() throws Exception { + Set response = client.listSharedIpGroups(withDetails()); + assert null != response; + long sharedIpGroupCount = response.size(); + assertTrue(sharedIpGroupCount >= 0); + for (SharedIpGroup sharedIpGroup : response) { + assertTrue(sharedIpGroup.getId() >= 1); + assert null != sharedIpGroup.getName() : sharedIpGroup; + assert null != sharedIpGroup.getServers() : sharedIpGroup; + } + } - private void blockUntilServerActive(int serverId) throws InterruptedException { - Server currentDetails = null; - for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client - .getServer(serverId)) { - System.out.printf("blocking on status active%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + public void testGetSharedIpGroupsDetail() throws Exception { + Set response = client.listSharedIpGroups(withDetails()); + assert null != response; + long sharedIpGroupCount = response.size(); + assertTrue(sharedIpGroupCount >= 0); + for (SharedIpGroup sharedIpGroup : response) { + SharedIpGroup newDetails = client.getSharedIpGroup(sharedIpGroup.getId()); + assertEquals(sharedIpGroup, newDetails); + } + } - private void blockUntilServerVerifyResize(int serverId) throws InterruptedException { - Server currentDetails = null; - for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client - .getServer(serverId)) { - System.out.printf("blocking on status verify resize%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + @Test + public void testGetSharedIpGroupDetailsNotFound() throws Exception { + assert client.getSharedIpGroup(12312987) == null; + } - private void blockUntilImageActive(int imageId) throws InterruptedException { - Image currentDetails = null; - for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client - .getImage(imageId)) { - System.out.printf("blocking on status active%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testCreateSharedIpGroup() throws Exception { + SharedIpGroup sharedIpGroup = null; + while (sharedIpGroup == null) { + String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt(); + try { + sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId)); + } catch (UndeclaredThrowableException e) { + HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); + if (htpe.getResponse().getStatusCode() == 400) + continue; + throw e; + } + } + assertNotNull(sharedIpGroup.getName()); + sharedIpGroupId = sharedIpGroup.getId(); + // Response doesn't include the server id Web Hosting #119311 + // assertEquals(sharedIpGroup.getServers(), ImmutableList.of(serverId)); + } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testServerDetails() throws Exception { - Server server = client.getServer(serverId); + private int sharedIpGroupId; - assertNotNull(server.getHostId()); - assertEquals(server.getStatus(), ServerStatus.ACTIVE); - assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals(new Integer(14362), server.getImageId()); - assertEquals(new Integer(1), server.getFlavorId()); - assertNotNull(server.getAddresses()); - // listAddresses tests.. - assertEquals(client.getAddresses(serverId), server.getAddresses()); - 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()); + private String serverPrefix = System.getProperty("user.name") + ".cs"; + private int serverId; + private String adminPass; + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + private String ip; + private int serverId2; + private String adminPass2; + private int imageId; - // check metadata - assertEquals(server.getMetadata(), metadata); + @Test(enabled = true) + public void testCreateServer() throws Exception { + int imageId = 14362; + int flavorId = 1; + Server server = null; + 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)); + } catch (UndeclaredThrowableException e) { + HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); + if (htpe.getResponse().getStatusCode() == 400) + continue; + throw e; + } + } + assertNotNull(server.getAdminPass()); + serverId = server.getId(); + adminPass = server.getAdminPass(); + ip = server.getAddresses().getPublicAddresses().iterator().next(); + assertEquals(server.getStatus(), ServerStatus.BUILD); + blockUntilServerActive(serverId); + } - checkPassOk(server, adminPass); - } + private void blockUntilServerActive(int serverId) throws InterruptedException { + Server currentDetails = null; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - /** - * this tests "personality" as the file looked up was sent during server creation - */ - private void checkPassOk(Server newDetails, String pass) throws IOException { - try { - doCheckPass(newDetails, pass); - } catch (SshException e) {// try twice in case there is a network timeout - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e1) { - } - doCheckPass(newDetails, pass); - } - } + private void blockUntilServerVerifyResize(int serverId) throws InterruptedException { + Server currentDetails = null; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status verify resize%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - private void doCheckPass(Server newDetails, String pass) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22); - socketTester.apply(socket); + private void blockUntilImageActive(int imageId) throws InterruptedException { + Image currentDetails = null; + for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client + .getImage(imageId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - Payload etcPasswd = client.get("/etc/jclouds.txt"); - String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput()); - assertEquals("rackspace", etcPasswdContents.trim()); - } finally { - if (client != null) - client.disconnect(); - } - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testServerDetails() throws Exception { + Server server = client.getServer(serverId); - private ExecResponse exec(Server details, String pass, String command) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22); - socketTester.apply(socket); - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - return client.exec(command); - } finally { - if (client != null) - client.disconnect(); - } - } + assertNotNull(server.getHostId()); + assertEquals(server.getStatus(), ServerStatus.ACTIVE); + assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); + assertEquals(new Integer(14362), server.getImageId()); + assertEquals(new Integer(1), server.getFlavorId()); + assertNotNull(server.getAddresses()); + // listAddresses tests.. + assertEquals(client.getAddresses(serverId), server.getAddresses()); + 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()); - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testRenameServer() throws Exception { - Server server = client.getServer(serverId); - String oldName = server.getName(); - client.renameServer(serverId, oldName + "new"); - blockUntilServerActive(serverId); - assertEquals(oldName + "new", client.getServer(serverId).getName()); - } + // check metadata + assertEquals(server.getMetadata(), metadata); - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testChangePassword() throws Exception { - client.changeAdminPass(serverId, "elmo"); - blockUntilServerActive(serverId); - checkPassOk(client.getServer(serverId), "elmo"); - this.adminPass = "elmo"; - } + checkPassOk(server, adminPass); + } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateSharedIpGroup") - public void testCreateServerIp() throws Exception { - int imageId = 14362; - int flavorId = 1; - Server server = null; - 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)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } - assertNotNull(server.getAdminPass()); - serverId2 = server.getId(); - adminPass2 = server.getAdminPass(); - blockUntilServerActive(serverId2); - assertIpConfigured(server, adminPass2); - assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses() + " doesn't contain " + ip; - assertEquals(server.getSharedIpGroupId(), new Integer(sharedIpGroupId)); - } + /** + * this tests "personality" as the file looked up was sent during server creation + */ - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } - } + private void checkPassOk(Server newDetails, String pass) throws IOException { + try { + doCheckPass(newDetails, pass); + } catch (SshException e) {// try twice in case there is a network timeout + try { + Thread.sleep(10 * 1000); + } catch (InterruptedException e1) { + } + doCheckPass(newDetails, pass); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateServerIp") - public void testUnshare() throws Exception { - client.unshareIp(ip, serverId2); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert !server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpNotConfigured(server, adminPass2); - } + private void doCheckPass(Server newDetails, String pass) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22); + socketTester.apply(socket); - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } - } + SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + try { + client.connect(); + Payload etcPasswd = client.get("/etc/jclouds.txt"); + String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput()); + assertEquals("rackspace", etcPasswdContents.trim()); + } finally { + if (client != null) + client.disconnect(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testUnshare") - public void testShareConfig() throws Exception { - client.shareIp(ip, serverId2, sharedIpGroupId, true); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpConfigured(server, adminPass2); - testUnshare(); - } + private ExecResponse exec(Server details, String pass, String command) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22); + socketTester.apply(socket); + SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + try { + client.connect(); + return client.exec(command); + } finally { + if (client != null) + client.disconnect(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareConfig") - public void testShareNoConfig() throws Exception { - client.shareIp(ip, serverId2, sharedIpGroupId, false); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpNotConfigured(server, adminPass2); - testUnshare(); - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testRenameServer() throws Exception { + Server server = client.getServer(serverId); + String oldName = server.getName(); + client.renameServer(serverId, oldName + "new"); + blockUntilServerActive(serverId); + assertEquals(oldName + "new", client.getServer(serverId).getName()); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareNoConfig") - public void testBackup() throws Exception { - assertEquals(new BackupSchedule(), client.getBackupSchedule(serverId)); - BackupSchedule dailyWeekly = new BackupSchedule(); - dailyWeekly.setEnabled(true); - dailyWeekly.setWeekly(WeeklyBackup.FRIDAY); - dailyWeekly.setDaily(DailyBackup.H_0400_0600); - client.replaceBackupSchedule(serverId, dailyWeekly); - client.deleteBackupSchedule(serverId); - // disables, doesn't delete: Web Hosting #119571 - assertEquals(client.getBackupSchedule(serverId).isEnabled(), false); - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testChangePassword() throws Exception { + client.changeAdminPass(serverId, "elmo"); + blockUntilServerActive(serverId); + checkPassOk(client.getServer(serverId), "elmo"); + this.adminPass = "elmo"; + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") - public void testCreateImage() throws Exception { - Image image = client.createImageFromServer("hoofie", serverId); - assertEquals("hoofie", image.getName()); - assertEquals(new Integer(serverId), image.getServerId()); - imageId = image.getId(); - blockUntilImageActive(imageId); - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateSharedIpGroup") + public void testCreateServerIp() throws Exception { + int imageId = 14362; + int flavorId = 1; + Server server = null; + 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)); + } catch (UndeclaredThrowableException e) { + HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); + if (htpe.getResponse().getStatusCode() == 400) + continue; + throw e; + } + } + assertNotNull(server.getAdminPass()); + serverId2 = server.getId(); + adminPass2 = server.getAdminPass(); + blockUntilServerActive(serverId2); + assertIpConfigured(server, adminPass2); + assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses() + " doesn't contain " + ip; + assertEquals(server.getSharedIpGroupId(), new Integer(sharedIpGroupId)); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") - public void testRebuildServer() throws Exception { - client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); - blockUntilServerActive(serverId); - // issue Web Hosting #119580 imageId comes back incorrect after rebuild - // assertEquals(new Integer(imageId), client.getServer(serverId).getImageId()); - } + 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); + } catch (Exception e) { + e.printStackTrace(); + } catch (AssertionError e) { + e.printStackTrace(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") - public void testRebootHard() throws Exception { - client.rebootServer(serverId, RebootType.HARD); - blockUntilServerActive(serverId); - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateServerIp") + public void testUnshare() throws Exception { + client.unshareIp(ip, serverId2); + blockUntilServerActive(serverId2); + Server server = client.getServer(serverId2); + assert !server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); + assertIpNotConfigured(server, adminPass2); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard") - public void testRebootSoft() throws Exception { - client.rebootServer(serverId, RebootType.SOFT); - blockUntilServerActive(serverId); - } + 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); + } catch (Exception e) { + e.printStackTrace(); + } catch (AssertionError e) { + e.printStackTrace(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") - public void testRevertResize() throws Exception { - client.resizeServer(serverId, 2); - blockUntilServerVerifyResize(serverId); - client.revertResizeServer(serverId); - blockUntilServerActive(serverId); - assertEquals(new Integer(1), client.getServer(serverId).getFlavorId()); - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testUnshare") + public void testShareConfig() throws Exception { + client.shareIp(ip, serverId2, sharedIpGroupId, true); + blockUntilServerActive(serverId2); + Server server = client.getServer(serverId2); + assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); + assertIpConfigured(server, adminPass2); + testUnshare(); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") - public void testConfirmResize() throws Exception { - client.resizeServer(serverId2, 2); - blockUntilServerVerifyResize(serverId2); - client.confirmResizeServer(serverId2); - blockUntilServerActive(serverId2); - assertEquals(new Integer(2), client.getServer(serverId2).getFlavorId()); - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareConfig") + public void testShareNoConfig() throws Exception { + client.shareIp(ip, serverId2, sharedIpGroupId, false); + blockUntilServerActive(serverId2); + Server server = client.getServer(serverId2); + assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); + assertIpNotConfigured(server, adminPass2); + testUnshare(); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "testRebootSoft", "testRevertResize", - "testConfirmResize" }) - void deleteServer2() { - if (serverId2 > 0) { - client.deleteServer(serverId2); - assert client.getServer(serverId2) == null; - } - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareNoConfig") + public void testBackup() throws Exception { + assertEquals(new BackupSchedule(), client.getBackupSchedule(serverId)); + BackupSchedule dailyWeekly = new BackupSchedule(); + dailyWeekly.setEnabled(true); + dailyWeekly.setWeekly(WeeklyBackup.FRIDAY); + dailyWeekly.setDaily(DailyBackup.H_0400_0600); + client.replaceBackupSchedule(serverId, dailyWeekly); + client.deleteBackupSchedule(serverId); + // disables, doesn't delete: Web Hosting #119571 + assertEquals(client.getBackupSchedule(serverId).isEnabled(), false); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2") - void testDeleteImage() { - if (imageId > 0) { - client.deleteImage(imageId); - assert client.getImage(imageId) == null; - } - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") + public void testCreateImage() throws Exception { + Image image = client.createImageFromServer("hoofie", serverId); + assertEquals("hoofie", image.getName()); + assertEquals(new Integer(serverId), image.getServerId()); + imageId = image.getId(); + blockUntilImageActive(imageId); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage") - void deleteServer1() { - if (serverId > 0) { - client.deleteServer(serverId); - assert client.getServer(serverId) == null; - } - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") + public void testRebuildServer() throws Exception { + client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); + blockUntilServerActive(serverId); + // issue Web Hosting #119580 imageId comes back incorrect after rebuild + // assertEquals(new Integer(imageId), client.getServer(serverId).getImageId()); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = { "deleteServer1" }) - void testDeleteSharedIpGroup() { - if (sharedIpGroupId > 0) { - client.deleteSharedIpGroup(sharedIpGroupId); - assert client.getSharedIpGroup(sharedIpGroupId) == null; - } - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") + public void testRebootHard() throws Exception { + client.rebootServer(serverId, RebootType.HARD); + blockUntilServerActive(serverId); + } - @AfterTest - void deleteServersOnEnd() { - if (serverId > 0) { - client.deleteServer(serverId); - } - if (serverId2 > 0) { - client.deleteServer(serverId2); - } - if (sharedIpGroupId > 0) { - client.deleteSharedIpGroup(sharedIpGroupId); - } - } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard") + public void testRebootSoft() throws Exception { + client.rebootServer(serverId, RebootType.SOFT); + blockUntilServerActive(serverId); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + public void testRevertResize() throws Exception { + client.resizeServer(serverId, 2); + blockUntilServerVerifyResize(serverId); + client.revertResizeServer(serverId); + blockUntilServerActive(serverId); + assertEquals(new Integer(1), client.getServer(serverId).getFlavorId()); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + public void testConfirmResize() throws Exception { + client.resizeServer(serverId2, 2); + blockUntilServerVerifyResize(serverId2); + client.confirmResizeServer(serverId2); + blockUntilServerActive(serverId2); + assertEquals(new Integer(2), client.getServer(serverId2).getFlavorId()); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"testRebootSoft", "testRevertResize", + "testConfirmResize"}) + void deleteServer2() { + if (serverId2 > 0) { + client.deleteServer(serverId2); + assert client.getServer(serverId2) == null; + } + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2") + void testDeleteImage() { + if (imageId > 0) { + client.deleteImage(imageId); + assert client.getImage(imageId) == null; + } + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage") + void deleteServer1() { + if (serverId > 0) { + client.deleteServer(serverId); + assert client.getServer(serverId) == null; + } + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"deleteServer1"}) + void testDeleteSharedIpGroup() { + if (sharedIpGroupId > 0) { + client.deleteSharedIpGroup(sharedIpGroupId); + assert client.getSharedIpGroup(sharedIpGroupId) == null; + } + } + + @AfterTest + void deleteServersOnEnd() { + if (serverId > 0) { + client.deleteServer(serverId); + } + if (serverId2 > 0) { + client.deleteServer(serverId2); + } + if (sharedIpGroupId > 0) { + client.deleteSharedIpGroup(sharedIpGroupId); + } + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java index 88bc827faa..ded18d8dd6 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java @@ -18,71 +18,670 @@ */ package org.jclouds.openstack.nova.compute; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; - +import com.google.common.base.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.io.Files; +import com.google.inject.Guice; +import com.google.inject.Module; +import org.jclouds.Constants; +import org.jclouds.compute.*; +import org.jclouds.compute.domain.*; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaAsyncClient; import org.jclouds.openstack.nova.NovaClient; -import org.jclouds.compute.BaseComputeServiceLiveTest; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.domain.LocationScope; +import org.jclouds.predicates.RetryablePredicate; +import org.jclouds.predicates.SocketOpen; +import org.jclouds.rest.AuthorizationException; import org.jclouds.rest.RestContext; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.ssh.SshClient; +import org.jclouds.ssh.SshException; import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.and; +import static com.google.common.base.Predicates.not; +import static com.google.common.base.Throwables.getRootCause; +import static com.google.common.collect.Iterables.*; +import static com.google.common.collect.Maps.newLinkedHashMap; +import static com.google.common.collect.Maps.uniqueIndex; +import static com.google.common.collect.Sets.filter; +import static com.google.common.collect.Sets.newTreeSet; +import static org.jclouds.compute.ComputeTestUtils.buildScript; +import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; +import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; +import static org.jclouds.compute.predicates.NodePredicates.*; +import static org.jclouds.compute.predicates.NodePredicates.all; +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + /** - * * Generally disabled, as it incurs higher fees. - * + * * @author Adrian Cole */ -@Test(groups = "live", enabled = true, sequential = true) -public class NovaComputeServiceLiveTest extends BaseComputeServiceLiveTest { - public NovaComputeServiceLiveTest() { - provider = "nova"; - } +@Test(groups = "novalive", enabled = true, sequential = true) +public class NovaComputeServiceLiveTest { - @Override - protected JschSshClientModule getSshModule() { - return new JschSshClientModule(); - } + protected String group; - public void testAssignability() throws Exception { - @SuppressWarnings("unused") - RestContext tmContext = new ComputeServiceContextFactory() - .createContext(provider, identity, credential).getProviderSpecificContext(); - } + protected RetryablePredicate socketTester; + protected SortedSet nodes; + protected ComputeServiceContext context; + protected ComputeService client; - @Override - protected void checkNodes(Iterable nodes, String tag) throws IOException { - super.checkNodes(nodes, tag); - for (NodeMetadata node : nodes) { - assertEquals(node.getLocation().getScope(), LocationScope.HOST); - } - } + protected Template template; + protected Map keyPair; - @Test(enabled = true, dependsOnMethods = "testReboot", expectedExceptions = UnsupportedOperationException.class) - public void testSuspendResume() throws Exception { - super.testSuspendResume(); - } + protected String provider; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - @Override - public void testGetNodesWithDetails() throws Exception { - super.testGetNodesWithDetails(); - } + private Properties overrides; - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - @Override - public void testListNodes() throws Exception { - super.testListNodes(); - } + public NovaComputeServiceLiveTest() { + provider = "nova"; + } - @Test(enabled = true, dependsOnMethods = { "testListNodes", "testGetNodesWithDetails" }) - @Override - public void testDestroyNodes() { - super.testDestroyNodes(); - } + + private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); + } + + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } + + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } + + + protected Properties setupProperties() { + Properties overrides = new Properties(); + try { + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + } catch (IOException e) { + throw new RuntimeException("Can't load properties"); + } + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.public"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.private"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } + + protected Properties setupRestProperties() { + return RestContextFactory.getPropertiesFromResource("/rest.properties"); + } + + private void initializeContextAndClient(Properties properties) throws IOException { + if (context != null) + context.close(); + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( + new Log4JLoggingModule(), getSshModule()), properties); + client = context.getComputeService(); + } + + public static Map setupKeyPair(Properties properties) throws FileNotFoundException, IOException { + return ImmutableMap.of( + "private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8), + "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); + } + + + @BeforeGroups(groups = {"novalive"}) + public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException { + if (group == null) + group = checkNotNull(provider, "provider"); + if (group.indexOf('-') == -1) + group = group + "-"; + Properties properties = setupProperties(); + setupCredentials(properties); + updateProperties(properties); + overrides = properties; + keyPair = setupKeyPair(properties); + initializeContextAndClient(properties); + buildSocketTester(); + } + + protected void buildSocketTester() { + SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 60, 1, TimeUnit.SECONDS); + } + + + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + @Test + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext tmContext = new ComputeServiceContextFactory() + .createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides).getProviderSpecificContext(); + } + + + protected void checkNodes(Iterable nodes, String tag) throws IOException { + _checkNodes(nodes, tag); + for (NodeMetadata node : nodes) { + assertEquals(node.getLocation().getScope(), LocationScope.HOST); + } + } + + protected void _checkNodes(Iterable nodes, String group) throws IOException { + for (NodeMetadata node : nodes) { + assertNotNull(node.getProviderId()); + assertNotNull(node.getGroup()); + assertEquals(node.getGroup(), group); + assertEquals(node.getState(), NodeState.RUNNING); + Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); + assertEquals(fromStore, node.getCredentials()); + assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; + assertNotNull(node.getCredentials()); + if (node.getCredentials().identity != null) { + assertNotNull(node.getCredentials().identity); + assertNotNull(node.getCredentials().credential); + sshPing(node); + } + } + } + + + @Test(enabled = true, expectedExceptions = AuthorizationException.class) + public void testCorrectAuthException() throws Exception { + ComputeServiceContext context = null; + try { + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet + .of(new Log4JLoggingModule()), overrides); + context.getComputeService().listNodes(); + } catch (AuthorizationException e) { + throw e; + } catch (RuntimeException e) { + e.printStackTrace(); + throw e; + } finally { + if (context != null) + context.close(); + } + } + + @Test(enabled = true) + public void testImagesCache() throws Exception { + client.listImages(); + long time = System.currentTimeMillis(); + client.listImages(); + long duration = System.currentTimeMillis() - time; + assert duration < 1000 : String.format("%dms to get images", duration); + } + + @Test(enabled = true, expectedExceptions = NoSuchElementException.class) + public void testCorrectExceptionRunningNodesNotFound() throws Exception { + client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() + .family(OsFamily.UBUNTU).description("ffoo").build())); + } + + // since surefire and eclipse don't otherwise guarantee the order, we are + // starting this one alphabetically before create2nodes.. + @Test(enabled = true, dependsOnMethods = {"testCompareSizes"}) + public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { + String group = this.group + "r"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + + TemplateOptions options = client.templateOptions().blockOnPort(22, 120); + try { + Set nodes = client.createNodesInGroup(group, 1, options); + Credentials good = nodes.iterator().next().getCredentials(); + assert good.identity != null : nodes; + assert good.credential != null : nodes; + + OperatingSystem os = get(nodes, 0).getOperatingSystem(); + try { + Map responses = runScriptWithCreds(group, os, new Credentials( + good.identity, "romeo")); + assert false : "shouldn't pass with a bad password\n" + responses; + } catch (RunScriptOnNodesException e) { + assert getRootCause(e).getMessage().contains("Auth fail") : e; + } + + for (Map.Entry response : client.runScriptOnNodesMatching( + runningInGroup(group), Statements.exec("echo hello"), + overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) + assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + + response.getValue(); + + runScriptWithCreds(group, os, good); + + checkNodes(nodes, group); + + } finally { + client.destroyNodesMatching(inGroup(group)); + } + } + + @Test(enabled = true, dependsOnMethods = {"testImagesCache"}) + public void testTemplateMatch() throws Exception { + template = buildTemplate(client.templateBuilder()); + Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build(); + assertEquals(toMatch.getImage(), template.getImage()); + } + + protected void checkHttpGet(NodeMetadata node) { + ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); + } + + @Test(enabled = true, dependsOnMethods = "testCompareSizes") + public void testCreateTwoNodesWithRunScript() throws Exception { + try { + client.destroyNodesMatching(inGroup(group)); + } catch (NoSuchElementException e) { + + } + refreshTemplate(); + try { + nodes = newTreeSet(client.createNodesInGroup(group, 2, template)); + } catch (RunNodesException e) { + nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); + throw e; + } + assertEquals(nodes.size(), 2); + checkNodes(nodes, group); + NodeMetadata node1 = nodes.first(); + NodeMetadata node2 = nodes.last(); + // credentials aren't always the same + // assertEquals(node1.getCredentials(), node2.getCredentials()); + + assertLocationSameOrChild(node1.getLocation(), template.getLocation()); + assertLocationSameOrChild(node2.getLocation(), template.getLocation()); + checkImageIdMatchesTemplate(node1); + checkImageIdMatchesTemplate(node2); + checkOsMatchesTemplate(node1); + checkOsMatchesTemplate(node2); + } + + private void refreshTemplate() { + template = buildTemplate(client.templateBuilder()); + + template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) + .runScript(buildScript(template.getImage().getOperatingSystem())); + } + + protected void checkImageIdMatchesTemplate(NodeMetadata node) { + if (node.getImageId() != null) + assertEquals(node.getImageId(), template.getImage().getId()); + } + + protected void checkOsMatchesTemplate(NodeMetadata node) { + if (node.getOperatingSystem() != null) + assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String + .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node + .getOperatingSystem()); + } + + void assertLocationSameOrChild(Location test, Location expected) { + if (!test.equals(expected)) { + assertEquals(test.getParent().getId(), expected.getId()); + } else { + assertEquals(test, expected); + } + } + + @Test(enabled = true, dependsOnMethods = "testCreateTwoNodesWithRunScript") + public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { + initializeContextAndClient(overrides); + refreshTemplate(); + TreeSet nodes = newTreeSet(client.createNodesInGroup(group, 1, template)); + checkNodes(nodes, group); + NodeMetadata node = nodes.first(); + this.nodes.add(node); + assertEquals(nodes.size(), 1); + assertLocationSameOrChild(node.getLocation(), template.getLocation()); + checkOsMatchesTemplate(node); + } + + @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") + public void testCredentialsCache() throws Exception { + initializeContextAndClient(overrides); + for (NodeMetadata node : nodes) + assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); + } + + protected Map runScriptWithCreds(final String group, OperatingSystem os, + Credentials creds) throws RunScriptOnNodesException { + try { + return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + .nameTask("runScriptWithCreds")); + } catch (SshException e) { + throw e; + } + } + + + protected Template buildTemplate(TemplateBuilder templateBuilder) { + return templateBuilder.build(); + } + + @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") + public void testGet() throws Exception { + Map metadataMap = newLinkedHashMap(uniqueIndex(filter(client + .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), + new Function() { + + @Override + public String apply(NodeMetadata from) { + return from.getId(); + } + + })); + for (NodeMetadata node : nodes) { + metadataMap.remove(node.getId()); + NodeMetadata metadata = client.getNodeMetadata(node.getId()); + assertEquals(metadata.getProviderId(), node.getProviderId()); + assertEquals(metadata.getGroup(), node.getGroup()); + assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); + checkImageIdMatchesTemplate(metadata); + checkOsMatchesTemplate(metadata); + assert (metadata.getState() == NodeState.RUNNING) : metadata; + // due to DHCP the addresses can actually change in-between runs. + assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size()); + assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size()); + } + assertNodeZero(metadataMap.values()); + } + + protected void assertNodeZero(Collection metadataSet) { + assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", + metadataSet, nodes); + } + + @Test(enabled = true, dependsOnMethods = "testGet") + public void testReboot() throws Exception { + client.rebootNodesMatching(inGroup(group));// TODO test + // validation + testGet(); + } + + @Test(enabled = true, dependsOnMethods = "testReboot") + public void testSuspendResume() throws Exception { + client.suspendNodesMatching(inGroup(group)); + + Set stoppedNodes = refreshNodes(); + + assert Iterables.all(stoppedNodes, new Predicate() { + + @Override + public boolean apply(NodeMetadata input) { + boolean returnVal = input.getState() == NodeState.SUSPENDED; + if (!returnVal) + System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState()); + return returnVal; + } + + }) : stoppedNodes; + + client.resumeNodesMatching(inGroup(group)); + testGet(); + } + + @Test(enabled = true, dependsOnMethods = "testSuspendResume") + public void testListNodes() throws Exception { + for (ComputeMetadata node : client.listNodes()) { + assert node.getProviderId() != null; + assert node.getLocation() != null; + assertEquals(node.getType(), ComputeType.NODE); + } + } + + @Test(enabled = true, dependsOnMethods = "testSuspendResume") + public void testGetNodesWithDetails() throws Exception { + for (NodeMetadata node : client.listNodesDetailsMatching(all())) { + assert node.getProviderId() != null : node; + assert node.getLocation() != null : node; + assertEquals(node.getType(), ComputeType.NODE); + assert node instanceof NodeMetadata; + NodeMetadata nodeMetadata = (NodeMetadata) node; + assert nodeMetadata.getProviderId() != null : nodeMetadata; + // nullable + // assert nodeMetadata.getImage() != null : node; + // user specified name is not always supported + // assert nodeMetadata.getName() != null : nodeMetadata; + if (nodeMetadata.getState() == NodeState.RUNNING) { + assert nodeMetadata.getPublicAddresses() != null : nodeMetadata; + assert nodeMetadata.getPublicAddresses().size() > 0 || nodeMetadata.getPrivateAddresses().size() > 0 : nodeMetadata; + assertNotNull(nodeMetadata.getPrivateAddresses()); + } + } + } + + @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"}) + public void testDestroyNodes() { + int toDestroy = refreshNodes().size(); + Set destroyed = client.destroyNodesMatching(inGroup(group)); + assertEquals(toDestroy, destroyed.size()); + for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) { + assert node.getState() == NodeState.TERMINATED : node; + assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); + } + } + + private Set refreshNodes() { + return filter(client.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); + } + + @Test(enabled = true) + public void testCreateAndRunAService() throws Exception { + + String group = this.group + "s"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + + template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) + .build(); + + // note this is a dependency on the template resolution + template.getOptions().runScript( + RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() + .getOperatingSystem())); + try { + NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template)); + + checkHttpGet(node); + } finally { + client.destroyNodesMatching(inGroup(group)); + } + + } + + @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */) + public void testTemplateOptions() throws Exception { + TemplateOptions options = new TemplateOptions().withMetadata(); + Template t = client.templateBuilder().smallest().options(options).build(); + assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; + } + + public void testListImages() throws Exception { + for (Image image : client.listImages()) { + assert image.getProviderId() != null : image; + // image.getLocationId() can be null, if it is a location-free image + assertEquals(image.getType(), ComputeType.IMAGE); + } + } + + @Test(groups = {"integration", "live"}) + public void testGetAssignableLocations() throws Exception { + for (Location location : client.listAssignableLocations()) { + System.err.printf("location %s%n", location); + assert location.getId() != null : location; + assert location != location.getParent() : location; + assert location.getScope() != null : location; + switch (location.getScope()) { + case PROVIDER: + assertProvider(location); + break; + case REGION: + assertProvider(location.getParent()); + break; + case ZONE: + Location provider = location.getParent().getParent(); + // zone can be a direct descendant of provider + if (provider == null) + provider = location.getParent(); + assertProvider(provider); + break; + case HOST: + Location provider2 = location.getParent().getParent().getParent(); + // zone can be a direct descendant of provider + if (provider2 == null) + provider2 = location.getParent().getParent(); + assertProvider(provider2); + break; + } + } + } + + public void testOptionToNotBlock() throws Exception { + String group = this.group + "block"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + // no inbound ports + TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts(); + try { + long time = System.currentTimeMillis(); + Set nodes = client.createNodesInGroup(group, 1, options); + NodeMetadata node = getOnlyElement(nodes); + assert node.getState() != NodeState.RUNNING; + long duration = System.currentTimeMillis() - time; + assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; + } finally { + client.destroyNodesMatching(inGroup(group)); + } + } + + private void assertProvider(Location provider) { + assertEquals(provider.getScope(), LocationScope.PROVIDER); + assertEquals(provider.getParent(), null); + } + + public void testListSizes() throws Exception { + for (Hardware hardware : client.listHardwareProfiles()) { + assert hardware.getProviderId() != null; + assert getCores(hardware) > 0; + assert hardware.getVolumes().size() >= 0; + assert hardware.getRam() > 0; + assertEquals(hardware.getType(), ComputeType.HARDWARE); + } + } + + @Test(enabled = true) + public void testCompareSizes() throws Exception { + Hardware defaultSize = client.templateBuilder().build().getHardware(); + + Hardware smallest = client.templateBuilder().smallest().build().getHardware(); + Hardware fastest = client.templateBuilder().fastest().build().getHardware(); + Hardware biggest = client.templateBuilder().biggest().build().getHardware(); + + System.out.printf("smallest %s%n", smallest); + System.out.printf("fastest %s%n", fastest); + System.out.printf("biggest %s%n", biggest); + + assertEquals(defaultSize, smallest); + + assert getCores(smallest) <= getCores(fastest) : String.format("%d ! <= %d", smallest, fastest); + assert getCores(biggest) <= getCores(fastest) : String.format("%d ! <= %d", biggest, fastest); + + assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest); + assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest); + + assert getCores(fastest) >= getCores(biggest) : String.format("%d ! >= %d", fastest, biggest); + assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest); + } + + private void sshPing(NodeMetadata node) throws IOException { + for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate. + try { + doCheckJavaIsInstalledViaSsh(node); + return; + } catch (SshException e) { + try { + Thread.sleep(10 * 1000); + } catch (InterruptedException e1) { + } + continue; + } + } + } + + protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { + SshClient ssh = context.utils().sshForNode().apply(node); + try { + ssh.connect(); + ExecResponse hello = ssh.exec("echo hello"); + assertEquals(hello.getOutput().trim(), "hello"); + ExecResponse exec = ssh.exec("java -version"); + assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" + + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); + } finally { + if (ssh != null) + ssh.disconnect(); + } + } + + @AfterTest + protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException { + if (nodes != null) { + testDestroyNodes(); + } + context.close(); + } } diff --git a/sandbox-apis/nova/src/test/resources/test.properties.template b/sandbox-apis/nova/src/test/resources/test.properties.template new file mode 100644 index 0000000000..9b7f844768 --- /dev/null +++ b/sandbox-apis/nova/src/test/resources/test.properties.template @@ -0,0 +1,7 @@ +test.nova.endpoint=http://172.18.34.40:8774 +test.nova.apiversion=1.1 +test.nova.identity=admin +test.nova.credential=d744752f-20d3-4d75-979f-f62f16033b07 +test.initializer= +test.ssh.keyfile.private=f:/gigaspace/distr/gigaspaces.pem +test.ssh.keyfile.public=f:/gigaspace/distr/gigaspaces.pem \ No newline at end of file From f8afe3860be8a0e58b1e5281d3fc8ae58e4db3cb Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 8 Apr 2011 22:29:41 +0400 Subject: [PATCH 11/95] test json output --- .../jclouds/openstack/nova/_NovaClient.java | 12 +-- .../src/test/resources/test_list_images.json | 58 +++++++++++--- .../resources/test_list_images_detail.json | 80 ++++++++++++++----- 3 files changed, 112 insertions(+), 38 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index 23f86b6b35..d05515702a 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -36,12 +36,12 @@ public class _NovaClient { TemplateOptions options = new TemplateOptions(); //options.authorizePublicKey(""); - Template template = cs.templateBuilder().hardwareId("m1.small").imageId("13").options(options).build(); - /*try { - cs.runNodesWithTag("test", 1, template); - } catch (RunNodesException e) { - e.printStackTrace(); - }*/ + //Template template = cs.templateBuilder().hardwareId("m1.small").imageId("13").options(options).build(); + //try { + // cs.runNodesWithTag("test", 1, template); + //} catch (RunNodesException e) { + // e.printStackTrace(); + //} //System.out.println(cs.listNodes()); //System.out.println(cs.listImages()); diff --git a/sandbox-apis/nova/src/test/resources/test_list_images.json b/sandbox-apis/nova/src/test/resources/test_list_images.json index 0c5cb251ad..5584d7cf83 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images.json @@ -1,12 +1,46 @@ -{ - "images" : [ - { - "id" : 2, - "name" : "CentOS 5.2" - }, - { - "id" : 743, - "name" : "My Server Backup" - } - ] -} +{ + "images" : { + "values" : [ + { + "id" : 1, + "name" : "CentOS 5.2", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + }, + { + "id" : 743, + "name" : "My Server Backup", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/743" + } + ] + } + ] + } +} diff --git a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json index bdafc2ded3..722d1936d8 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json @@ -1,20 +1,60 @@ -{ - "images" : [ - { - "id" : 2, - "name" : "CentOS 5.2", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "status" : "ACTIVE" - }, - { - "id" : 743, - "name" : "My Server Backup", - "serverId" : 12, - "updated" : "2010-10-10T12:00:00Z", - "created" : "2009-07-07T09:56:16-05:00", - "status" : "SAVING", - "progress" : 80 - } - ] -} +{ + "images" : { + "values" : [ + { + "id" : 1, + "name" : "CentOS 5.2", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "ACTIVE", + "metadata" : { + "values" : { + "ImageType" : "Gold", + "ImageVersion" : "1.5" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + }, + { + "id" : 743, + "name" : "My Server Backup", + "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "SAVING", + "progress" : 80, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/743" + } + ] + } + ] + } +} From 1e204e55cb5022ffadf9d8e0b2e72c1bd92fdd93 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 8 Apr 2011 23:08:25 +0400 Subject: [PATCH 12/95] removed unnecessary artifacts --- sandbox-apis/nova/pom.xml | 321 +++++++++++++++++++------------------- 1 file changed, 158 insertions(+), 163 deletions(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 4c7d2d609f..49777e8314 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -1,163 +1,158 @@ - - - - - 4.0.0 - - org.jclouds - jclouds-project - 1.0-SNAPSHOT - ../../project/pom.xml - - org.jclouds.api - nova - jcloud nova api - jclouds components to access an implementation of OpenStack Nova - - - https://auth.api.rackspacecloud.com - 1.1 - FIXME - FIXME - - - - - org.jclouds.provider - aws-ec2 - ${project.version} - - - org.jclouds.common - openstack-common - ${project.version} - - - org.jclouds - jclouds-compute - ${project.version} - - - org.jclouds - jclouds-core - ${project.version} - test-jar - test - - - org.jclouds.common - openstack-common - ${project.version} - test-jar - test - - - org.jclouds - jclouds-compute - ${project.version} - test-jar - test - - - org.jclouds.driver - jclouds-jsch - ${project.version} - test - - - com.jcraft - jsch - test - - - org.jclouds.driver - jclouds-log4j - ${project.version} - test - - - log4j - log4j - 1.2.16 - test - - - - - - live - - - - org.apache.maven.plugins - maven-surefire-plugin - - - integration - integration-test - - test - - - - - test.nova.endpoint - ${test.nova.endpoint} - - - test.nova.apiversion - ${test.nova.apiversion} - - - test.nova.identity - ${test.nova.identity} - - - test.nova.credential - ${test.nova.credential} - - - test.nova.credential - ${test.ssh.keyfile.public} - - - test.nova.credential - ${test.ssh.keyfile.private} - - - test.initializer - ${test.initializer} - - - - - - - - - - - - - - + + + + + 4.0.0 + + org.jclouds + jclouds-project + 1.0-SNAPSHOT + ../../project/pom.xml + + org.jclouds.api + nova + jcloud nova api + jclouds components to access an implementation of OpenStack Nova + + + https://auth.api.rackspacecloud.com + 1.1 + FIXME + FIXME + + + + + org.jclouds.common + openstack-common + ${project.version} + + + org.jclouds + jclouds-compute + ${project.version} + + + org.jclouds + jclouds-core + ${project.version} + test-jar + test + + + org.jclouds.common + openstack-common + ${project.version} + test-jar + test + + + org.jclouds + jclouds-compute + ${project.version} + test-jar + test + + + org.jclouds.driver + jclouds-jsch + ${project.version} + test + + + com.jcraft + jsch + test + + + org.jclouds.driver + jclouds-log4j + ${project.version} + test + + + log4j + log4j + 1.2.16 + test + + + + + + live + + + + org.apache.maven.plugins + maven-surefire-plugin + + + integration + integration-test + + test + + + + + test.nova.endpoint + ${test.nova.endpoint} + + + test.nova.apiversion + ${test.nova.apiversion} + + + test.nova.identity + ${test.nova.identity} + + + test.nova.credential + ${test.nova.credential} + + + test.nova.credential + ${test.ssh.keyfile.public} + + + test.nova.credential + ${test.ssh.keyfile.private} + + + test.initializer + ${test.initializer} + + + + + + + + + + + + + + From e01910ffd8fc5b588c3f1454f210ce9180aac9c8 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Sat, 9 Apr 2011 16:21:24 +0400 Subject: [PATCH 13/95] Removed unusefull properties --- sandbox-apis/nova/pom.xml | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 49777e8314..361d72e383 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -35,13 +35,15 @@ jclouds components to access an implementation of OpenStack Nova - https://auth.api.rackspacecloud.com - 1.1 - FIXME - FIXME + + + org.jclouds.provider + aws-ec2 + ${project.version} + org.jclouds.common openstack-common @@ -132,11 +134,11 @@ ${test.nova.credential} - test.nova.credential + test.ssh.keyfile.public ${test.ssh.keyfile.public} - test.nova.credential + test.ssh.keyfile.private ${test.ssh.keyfile.private} From ca4b0fe61840320a0139585f8f7ad915814b7206 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Sat, 9 Apr 2011 16:22:14 +0400 Subject: [PATCH 14/95] Fixed expectations of createRequest tests --- .../openstack/nova/NovaAsyncClientTest.java | 1385 +++++++++-------- 1 file changed, 694 insertions(+), 691 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 26753f1571..07052ec444 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -18,35 +18,9 @@ */ package org.jclouds.openstack.nova; -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIpGroup; -import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; -import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URI; -import java.net.UnknownHostException; -import java.util.Date; -import java.util.Properties; - -import javax.ws.rs.core.MediaType; - -import org.jclouds.openstack.nova.config.NovaRestClientModule; -import org.jclouds.openstack.nova.domain.BackupSchedule; -import org.jclouds.openstack.nova.domain.DailyBackup; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.WeeklyBackup; -import org.jclouds.openstack.nova.options.CreateServerOptions; -import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; -import org.jclouds.openstack.nova.options.ListOptions; -import org.jclouds.openstack.nova.options.RebuildServerOptions; +import com.google.common.collect.ImmutableMap; +import com.google.inject.Module; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.http.functions.ReleasePayloadAndReturn; @@ -57,848 +31,877 @@ import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse; import org.jclouds.openstack.TestOpenStackAuthenticationModule; import org.jclouds.openstack.filters.AddTimestampQuery; import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.openstack.nova.config.NovaRestClientModule; +import org.jclouds.openstack.nova.domain.BackupSchedule; +import org.jclouds.openstack.nova.domain.DailyBackup; +import org.jclouds.openstack.nova.domain.RebootType; +import org.jclouds.openstack.nova.domain.WeeklyBackup; +import org.jclouds.openstack.nova.options.CreateServerOptions; +import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; +import org.jclouds.openstack.nova.options.ListOptions; +import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; -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; +import org.jclouds.rest.functions.*; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.net.UnknownHostException; +import java.util.Date; +import java.util.Properties; + +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.*; +import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code NovaAsyncClient} - * + * * @author Adrian Cole */ // NOTE:without testName, this will not call @Before* and fail w/NPE during surefire @Test(groups = "unit", testName = "NovaAsyncClientTest") public class NovaAsyncClientTest extends RestClientTest { - private static final Class listOptionsVarargsClass = new ListOptions[] {}.getClass(); - private static final Class createServerOptionsVarargsClass = new CreateServerOptions[] {} - .getClass(); - - public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - 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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - 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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor - .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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); + private static final Class listOptionsVarargsClass = new ListOptions[]{}.getClass(); + private static final Class createServerOptionsVarargsClass = new CreateServerOptions[]{} + .getClass(); + + @Test + public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", + "application/json", false); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + + } + + @Test + public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withSharedIpGroup(2)); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Test + public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor + .createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + + } + + @Test + public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, + withMetadata(ImmutableMap.of("foo", "bar"))); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); + + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + + } + + public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException, + UnknownHostException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, + withSharedIpGroup(2).withSharedIp("127.0.0.1")); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); - } - - public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, - withMetadata(ImmutableMap.of("foo", "bar"))); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - 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); + checkFilters(request); + } + + public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/images/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - } + checkFilters(request); + } - public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException, - UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, - withSharedIpGroup(2).withSharedIp("127.0.0.1")); + public void testListServers() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); + + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - 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); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + checkFilters(request); + } - checkFilters(request); - } + Date now = new Date(10000000l); - public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testListServersOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, "DELETE http://serverManagementUrl/images/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListServers() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + public void testListServersDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - Date now = new Date(10000000l); + public void testGetServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getServer", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListServersOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, - "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, ReturnNullOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListFlavors() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - public void testListServersDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListFlavorsOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - public void testGetServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getServer", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListFlavorsDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - public void testListFlavors() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListFlavorsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - public void testListFlavorsOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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); - assertRequestLineEquals(request, - "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, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testGetFlavor() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListFlavorsDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListImages() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - public void testListFlavorsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, - "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, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListImagesDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - public void testGetFlavor() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/flavors/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListImagesOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - public void testListImages() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/images?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListImagesDetailOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - public void testListImagesDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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); - assertRequestLineEquals(request, "GET http://serverManagementUrl/images/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testGetImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getImage", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListImagesOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, - "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, ReturnNullOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testDeleteServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListImagesDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, - "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, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { + Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class, + boolean.class); + HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false); - public void testGetImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getImage", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":false}}", + MediaType.APPLICATION_JSON, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/images/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + checkFilters(request); - checkFilters(request); - } + } - public void testDeleteServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { + Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class, + boolean.class); + HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, true); - assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":true}}", + MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); - } + checkFilters(request); - public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.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"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":false}}", - MediaType.APPLICATION_JSON, false); + public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, + UnknownHostException { + Method method = NovaAsyncClient.class.getMethod("unshareIp", String.class, int.class); + HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); - } + checkFilters(request); - public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.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); + public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("replaceBackupSchedule", int.class, BackupSchedule.class); + HttpRequest request = processor.createRequest(method, 2, new BackupSchedule(WeeklyBackup.MONDAY, + DailyBackup.H_0800_1000, true)); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/backup_schedule HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, + "{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}", + MediaType.APPLICATION_JSON, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOn404.class); - } + checkFilters(request); - public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, - UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("unshareIp", String.class, int.class); - HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false); + } - assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2/ips/public/127.0.0.1 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + public void testDeleteBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteBackupSchedule", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2/backup_schedule HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, MediaType.APPLICATION_JSON, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - } + checkFilters(request); - public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("replaceBackupSchedule", int.class, BackupSchedule.class); - HttpRequest request = processor.createRequest(method, 2, new BackupSchedule(WeeklyBackup.MONDAY, - 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); + public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); + HttpRequest request = processor.createRequest(method, 2, "foo"); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOn404.class); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - } + checkFilters(request); - public void testDeleteBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteBackupSchedule", int.class); - HttpRequest request = processor.createRequest(method, 2); + } - assertRequestLineEquals(request, "DELETE http://serverManagementUrl/servers/2/backup_schedule HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, MediaType.APPLICATION_JSON, false); + public void testChangeServerName() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class); + HttpRequest request = processor.createRequest(method, 2, "foo"); - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - } + checkFilters(request); - public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); - HttpRequest request = processor.createRequest(method, 2, "foo"); + } - assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); + public void testListSharedIpGroups() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - } + checkFilters(request); + } - public void testChangeServerName() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class); - HttpRequest request = processor.createRequest(method, 2, "foo"); + public void testListSharedIpGroupsOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, "PUT http://serverManagementUrl/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); + checkFilters(request); + } - } + public void testListSharedIpGroupsDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - public void testListSharedIpGroups() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testListSharedIpGroupsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - public void testListSharedIpGroupsOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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); - assertRequestLineEquals(request, - "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, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + public void testGetSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getSharedIpGroup", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListSharedIpGroupsDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + private static final Class createSharedIpGroupOptionsVarargsClass = new CreateSharedIpGroupOptions[]{} + .getClass(); - public void testListSharedIpGroupsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); + public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, + createSharedIpGroupOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie"); - assertRequestLineEquals(request, - "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); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/shared_ip_groups?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); - } + checkFilters(request); - public void testGetSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getSharedIpGroup", int.class); - HttpRequest request = processor.createRequest(method, 2); + } - assertRequestLineEquals(request, "GET http://serverManagementUrl/shared_ip_groups/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, + createSharedIpGroupOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", withServer(2)); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); - checkFilters(request); - } + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - private static final Class createSharedIpGroupOptionsVarargsClass = new CreateSharedIpGroupOptions[] {} - .getClass(); + checkFilters(request); + } - public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, - createSharedIpGroupOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie"); + public void testDeleteSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteSharedIpGroup", int.class); + HttpRequest request = processor.createRequest(method, 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\"}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/shared_ip_groups/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - checkFilters(request); + checkFilters(request); + } - } + public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, - createSharedIpGroupOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", withServer(2)); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - 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); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + checkFilters(request); + } - checkFilters(request); - } + public void testListPublicAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testDeleteSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteSharedIpGroup", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/public?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "DELETE http://serverManagementUrl/shared_ip_groups/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + @Test + public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/private?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + checkFilters(request); + } - checkFilters(request); - } + @Test + public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getBackupSchedule", int.class); + HttpRequest request = processor.createRequest(method, 2); - public void testListPublicAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/backup_schedule?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips/public?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); + } - checkFilters(request); - } + @Test + public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); + HttpRequest request = processor.createRequest(method, "ralphie", 2); - public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/images?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, + false); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/ips/private?format=json 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); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + checkFilters(request); - checkFilters(request); - } + } - public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getBackupSchedule", int.class); - HttpRequest request = processor.createRequest(method, 2); + private static final Class rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{} + .getClass(); - assertRequestLineEquals(request, "GET http://serverManagementUrl/servers/2/backup_schedule?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + @Test + public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, + rebuildServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, 3); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false); - checkFilters(request); - } + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); - HttpRequest request = processor.createRequest(method, "ralphie", 2); + checkFilters(request); + } - 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); + @Test + public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, + rebuildServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, 3, withImage(2)); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false); - checkFilters(request); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - } + checkFilters(request); + } - private static final Class rebuildServerOptionsVarargsClass = new RebuildServerOptions[] {} - .getClass(); + @Test + public void testReboot() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class); + HttpRequest request = processor.createRequest(method, 2, RebootType.HARD); - public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, - rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false); - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, - rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3, withImage(2)); - - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/3/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testReboot() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class); - HttpRequest request = processor.createRequest(method, 2, RebootType.HARD); - - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testResize() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class); - HttpRequest request = processor.createRequest(method, 2, 3); - - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testConfirmResize() throws IOException, IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testRevertResize() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "POST http://serverManagementUrl/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - @Override - protected TypeLiteral> createTypeLiteral() { - return new TypeLiteral>() { - }; - } - - @Override - protected void checkFilters(HttpRequest request) { - assertEquals(request.getFilters().size(), 2); - assertEquals(request.getFilters().get(0).getClass(), AuthenticateRequest.class); - assertEquals(request.getFilters().get(1).getClass(), AddTimestampQuery.class); - - } - - @Override - protected Module createModule() { - return new TestNovaRestClientModule(); - } - - @ConfiguresRestClient - @RequiresHttp - protected static class TestNovaRestClientModule extends NovaRestClientModule { - private TestNovaRestClientModule() { - super(new TestOpenStackAuthenticationModule()); - } - - @Override - protected URI provideServerUrl(AuthenticationResponse response) { - return URI.create("http://serverManagementUrl"); - } - - } - - protected String provider = "nova"; - - @Override - public RestContextSpec createContextSpec() { - return new RestContextFactory(getProperties()).createContextSpec(provider, "user", "password", new Properties()); - } - - @Override - protected Properties getProperties() { - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_REGIONS, "US"); - overrides.setProperty(PROPERTY_API_VERSION, "1"); - overrides.setProperty(provider + ".endpoint", "https://auth"); - overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); - return overrides; - } + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Test + public void testResize() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class); + HttpRequest request = processor.createRequest(method, 2, 3); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + + } + + public void testConfirmResize() throws IOException, IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class); + HttpRequest request = processor.createRequest(method, 2); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testRevertResize() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class); + HttpRequest request = processor.createRequest(method, 2); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + protected void checkFilters(HttpRequest request) { + assertEquals(request.getFilters().size(), 2); + assertEquals(request.getFilters().get(0).getClass(), AuthenticateRequest.class); + assertEquals(request.getFilters().get(1).getClass(), AddTimestampQuery.class); + + } + + @Override + protected Module createModule() { + return new TestNovaRestClientModule(); + } + + @ConfiguresRestClient + @RequiresHttp + protected static class TestNovaRestClientModule extends NovaRestClientModule { + private TestNovaRestClientModule() { + super(new TestOpenStackAuthenticationModule()); + } + + @Override + protected URI provideServerUrl(AuthenticationResponse response) { + return URI.create("http://endpoint"); + } + + } + + protected String provider = "nova"; + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory(getProperties()).createContextSpec(provider, "user", "password", new Properties()); + } + + @Override + protected Properties getProperties() { + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_REGIONS, "US"); + overrides.setProperty(PROPERTY_API_VERSION, "apiversion"); + overrides.setProperty(provider + ".endpoint", "http://endpoint"); + overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); + return overrides; + } } From d210baa9625fc5e732262486c8492acf3962950e Mon Sep 17 00:00:00 2001 From: vicglarson Date: Sat, 9 Apr 2011 16:35:24 +0400 Subject: [PATCH 15/95] Removed unneccessary artifact again --- sandbox-apis/nova/pom.xml | 5 ----- 1 file changed, 5 deletions(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 361d72e383..0ae2dce73f 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -39,11 +39,6 @@ - - org.jclouds.provider - aws-ec2 - ${project.version} - org.jclouds.common openstack-common From 1137e552aee9fbcb1a211cdf54668b3104fa48bf Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Sun, 10 Apr 2011 21:19:07 +0400 Subject: [PATCH 16/95] Shared IP groups is removed Backup management is removed --- .../openstack/nova/NovaAsyncClient.java | 91 ------ .../jclouds/openstack/nova/NovaClient.java | 96 ------ .../BindBackupScheduleToJsonPayload.java | 53 ---- .../openstack/nova/domain/BackupSchedule.java | 104 ------- .../openstack/nova/domain/DailyBackup.java | 37 --- .../openstack/nova/domain/ShareIp.java | 42 --- .../openstack/nova/domain/SharedIpGroup.java | 111 ------- .../openstack/nova/domain/Version.java | 59 ---- .../openstack/nova/domain/VersionStatus.java | 37 --- .../openstack/nova/domain/WeeklyBackup.java | 37 --- .../openstack/nova/NovaAsyncClientTest.java | 276 ------------------ .../openstack/nova/NovaClientLiveTest.java | 142 --------- ...rseBackupScheduleFromJsonResponseTest.java | 68 ----- ...arseSharedIpGroupFromJsonResponseTest.java | 61 ---- ...SharedIpGroupListFromJsonResponseTest.java | 83 ------ .../test_get_sharedipgroup_details.json | 7 - .../resources/test_list_backupschedule.json | 7 - .../resources/test_list_sharedipgroups.json | 12 - .../test_list_sharedipgroups_detail.json | 14 - 19 files changed, 1337 deletions(-) delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/binders/BindBackupScheduleToJsonPayload.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/BackupSchedule.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/DailyBackup.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ShareIp.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/SharedIpGroup.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Version.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/VersionStatus.java delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/WeeklyBackup.java delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseBackupScheduleFromJsonResponseTest.java delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupFromJsonResponseTest.java delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupListFromJsonResponseTest.java delete mode 100644 sandbox-apis/nova/src/test/resources/test_get_sharedipgroup_details.json delete mode 100644 sandbox-apis/nova/src/test/resources/test_list_backupschedule.json delete mode 100644 sandbox-apis/nova/src/test/resources/test_list_sharedipgroups.json delete mode 100644 sandbox-apis/nova/src/test/resources/test_list_sharedipgroups_detail.json diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java index 73bbab0d57..9dec5dfe32 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java @@ -31,14 +31,11 @@ import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import org.jclouds.openstack.nova.binders.BindBackupScheduleToJsonPayload; import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.BackupSchedule; import org.jclouds.openstack.nova.domain.Flavor; import org.jclouds.openstack.nova.domain.Image; import org.jclouds.openstack.nova.domain.RebootType; import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.SharedIpGroup; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; import org.jclouds.openstack.nova.options.ListOptions; @@ -170,25 +167,6 @@ public interface NovaAsyncClient { @MapBinder(RebuildServerOptions.class) ListenableFuture rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); - /** - * @see NovaClient#shareIp - */ - @PUT - @Path("/servers/{id}/ips/public/{address}") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"shareIp\":%7B\"sharedIpGroupId\":{sharedIpGroupId},\"configureServer\":{configureServer}%7D%7D") - ListenableFuture shareIp(@PathParam("address") String addressToShare, - @PathParam("id") int serverToTosignBindressTo, @PayloadParam("sharedIpGroupId") int sharedIpGroup, - @PayloadParam("configureServer") boolean configureServer); - - /** - * @see NovaClient#unshareIp - */ - @DELETE - @Path("/servers/{id}/ips/public/{address}") - @ExceptionParser(ReturnVoidOnNotFoundOr404.class) - ListenableFuture unshareIp(@PathParam("address") String addressToShare, - @PathParam("id") int serverToTosignBindressTo); /** * @see NovaClient#changeAdminPass @@ -273,75 +251,6 @@ public interface NovaAsyncClient { ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, @PayloadParam("serverId") int serverId); - /** - * @see NovaClient#listSharedIpGroups - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/shared_ip_groups") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listSharedIpGroups(ListOptions... options); - - /** - * @see NovaClient#getSharedIpGroup - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/shared_ip_groups/{id}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getSharedIpGroup(@PathParam("id") int id); - - /** - * @see NovaClient#createSharedIpGroup - */ - @POST - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/shared_ip_groups") - @MapBinder(CreateSharedIpGroupOptions.class) - ListenableFuture createSharedIpGroup(@PayloadParam("name") String name, - CreateSharedIpGroupOptions... options); - - /** - * @see NovaClient#deleteSharedIpGroup - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/shared_ip_groups/{id}") - ListenableFuture deleteSharedIpGroup(@PathParam("id") int id); - - /** - * @see NovaClient#listBackupSchedule - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/backup_schedule") - ListenableFuture getBackupSchedule(@PathParam("id") int serverId); - - /** - * @see NovaClient#deleteBackupSchedule - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/servers/{id}/backup_schedule") - ListenableFuture deleteBackupSchedule(@PathParam("id") int serverId); - - /** - * @see NovaClient#replaceBackupSchedule - */ - @POST - @ExceptionParser(ReturnFalseOn404.class) - @Path("/servers/{id}/backup_schedule") - ListenableFuture replaceBackupSchedule(@PathParam("id") int id, - @BinderParam(BindBackupScheduleToJsonPayload.class) BackupSchedule backupSchedule); - /** * @see NovaClient#listAddresses */ diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java index 22acaf2ce6..01e3f7a4a3 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java @@ -26,12 +26,10 @@ import javax.ws.rs.PathParam; import org.jclouds.concurrent.Timeout; import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.BackupSchedule; import org.jclouds.openstack.nova.domain.Flavor; import org.jclouds.openstack.nova.domain.Image; import org.jclouds.openstack.nova.domain.RebootType; import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.SharedIpGroup; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; import org.jclouds.openstack.nova.options.ListOptions; @@ -173,40 +171,6 @@ public interface NovaClient { */ void rebuildServer(int id, RebuildServerOptions... options); - /** - * /** This operation allows you share an IP address to the specified server - *

- * This operation shares an IP from an existing server in the specified shared IP group to - * another specified server in the same group. The operation modifies cloud network restrictions - * to allow IP traffic for the given IP to/from the server specified. - * - *

- * Status Transition: ACTIVE - SHARE_IP - ACTIVE (if configureServer is true) ACTIVE - - * SHARE_IP_NO_CONFIG - ACTIVE - * - * @param configureServer - *

- * if set to true, the server is configured with the new address, though the address is - * not enabled. Note that configuring the server does require a reboot. - *

- * If set to false, does not bind the IP to the server itself. A heartbeat facility - * (e.g. keepalived) can then be used within the servers to perform health checks and - * manage IP failover. - */ - void shareIp(String addressToShare, int serverToTosignBindressTo, int sharedIpGroup, - boolean configureServer); - - /** - * This operation removes a shared IP address from the specified server. - *

- * Status Transition: ACTIVE - DELETE_IP - ACTIVE - * - * @param addressToShare - * @param serverToTosignBindressTo - * @return - */ - void unshareIp(String addressToShare, int serverToTosignBindressTo); - /** * This operation allows you to change the administrative password. *

@@ -295,66 +259,6 @@ public interface NovaClient { */ Image createImageFromServer(String imageName, int serverId); - /** - * - * List shared IP groups (IDs and names only) - * - * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listSharedIpGroups(ListOptions... options); - - /** - * - * This operation returns details of the specified shared IP group. - * - * @return null, if the shared ip group is not found - * - * @see SharedIpGroup - */ - SharedIpGroup getSharedIpGroup(int id); - - /** - * This operation creates a new shared IP group. Please note, all responses to requests for - * shared_ip_groups return an array of servers. However, on a create request, the shared IP group - * can be created empty or can be initially populated with a single server. Use - * {@link CreateSharedIpGroupOptions} to specify an server. - */ - SharedIpGroup createSharedIpGroup(String name, CreateSharedIpGroupOptions... options); - - /** - * This operation deletes the specified shared IP group. This operation will ONLY succeed if 1) - * there are no active servers in the group (i.e. they have all been terminated) or 2) no servers - * in the group are actively sharing IPs. - * - * @return false if the shared ip group is not found - * @see SharedIpGroup - */ - boolean deleteSharedIpGroup(int id); - - /** - * List the backup schedule for the specified server - * - * @throws ResourceNotFoundException - * , if the server doesn't exist - */ - BackupSchedule getBackupSchedule(int serverId); - - /** - * Delete backup schedule for the specified server. - *

- * Web Hosting #119571 currently disables the schedule, not deletes it. - * - * @return false if the schedule is not found - */ - boolean deleteBackupSchedule(int serverId); - - /** - * Enable/update the backup schedule for the specified server - * - */ - void replaceBackupSchedule(int id, BackupSchedule backupSchedule); - /** * List all server addresses * diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/binders/BindBackupScheduleToJsonPayload.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/binders/BindBackupScheduleToJsonPayload.java deleted file mode 100644 index 30b2916f6e..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/binders/BindBackupScheduleToJsonPayload.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.binders; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.util.Map; - -import javax.inject.Singleton; - -import org.jclouds.http.HttpRequest; -import org.jclouds.openstack.nova.domain.BackupSchedule; -import org.jclouds.rest.binders.BindToJsonPayload; - -import com.google.common.collect.ImmutableMap; - -/** - * - * @author Adrian Cole - * - */ -@Singleton -public class BindBackupScheduleToJsonPayload extends BindToJsonPayload { - - @Override - public R bindToRequest(R request, Map postParams) { - throw new IllegalStateException( - "Replace Backup Schedule needs an BackupSchedule object, not a Map"); - } - - @Override - public R bindToRequest(R request, Object toBind) { - checkArgument(toBind instanceof BackupSchedule, - "this binder is only valid for BackupSchedules!"); - return super.bindToRequest(request, ImmutableMap.of("backupSchedule", toBind)); - } -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/BackupSchedule.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/BackupSchedule.java deleted file mode 100644 index 18087b0318..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/BackupSchedule.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -/** - * A backup schedule can be defined to create server images at regular intervals (daily and weekly). - * Backup schedules are configurable per server. - * - * @author Adrian Cole - */ -public class BackupSchedule { - protected DailyBackup daily = DailyBackup.DISABLED; - protected boolean enabled; - protected WeeklyBackup weekly = WeeklyBackup.DISABLED; - - public BackupSchedule() { - } - - public BackupSchedule(WeeklyBackup weekly, DailyBackup daily, boolean enabled) { - this.weekly = weekly; - this.daily = daily; - this.enabled = enabled; - } - - public DailyBackup getDaily() { - return daily; - } - - public void setDaily(DailyBackup value) { - this.daily = value; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean value) { - this.enabled = value; - } - - public WeeklyBackup getWeekly() { - return weekly; - } - - public void setWeekly(WeeklyBackup value) { - this.weekly = value; - } - - @Override - public String toString() { - return "[daily=" + daily + ", enabled=" + enabled + ", weekly=" + weekly + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((daily == null) ? 0 : daily.hashCode()); - result = prime * result + (enabled ? 1231 : 1237); - result = prime * result + ((weekly == null) ? 0 : weekly.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; - BackupSchedule other = (BackupSchedule) obj; - if (daily == null) { - if (other.daily != null) - return false; - } else if (!daily.equals(other.daily)) - return false; - if (enabled != other.enabled) - return false; - if (weekly == null) { - if (other.weekly != null) - return false; - } else if (!weekly.equals(other.weekly)) - return false; - return true; - } - -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/DailyBackup.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/DailyBackup.java deleted file mode 100644 index 6a6518bdc6..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/DailyBackup.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -public enum DailyBackup { - - DISABLED, H_0000_0200, H_0200_0400, H_0400_0600, H_0600_0800, H_0800_1000, H_1000_1200, H_1200_1400, H_1400_1600, H_1600_1800, H_1800_2000, H_2000_2200, H_2200_0000, UNRECOGNIZED; - - public String value() { - return name(); - } - - public static DailyBackup fromValue(String v) { - try { - return valueOf(v); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } - -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ShareIp.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ShareIp.java deleted file mode 100644 index d8284f6aad..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ShareIp.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -public class ShareIp { - - private boolean configureServer; - private int sharedIpGroupId; - - public void setConfigureServer(boolean configureServer) { - this.configureServer = configureServer; - } - - public boolean isConfigureServer() { - return configureServer; - } - - public void setSharedIpGroupId(int sharedIpGroupId) { - this.sharedIpGroupId = sharedIpGroupId; - } - - public int getSharedIpGroupId() { - return sharedIpGroupId; - } - -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/SharedIpGroup.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/SharedIpGroup.java deleted file mode 100644 index f46690013c..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/SharedIpGroup.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -import java.util.List; - -import com.google.common.collect.Lists; - -/** - * A shared IP group is a collection of servers that can share IPs with other members of the group. - * Any server in a group can share one or more public IPs with any other server in the group. With - * the exception of the first server in a shared IP group, servers must be launched into shared IP - * groups. A server may only be a member of one shared IP group. - * - * @author Adrian Cole - */ -public class SharedIpGroup { - - private int id; - private String name; - - private List servers = Lists.newArrayList(); - - public SharedIpGroup() { - } - - public SharedIpGroup(int id, String name) { - this.id = id; - this.name = name; - } - - public void setId(int id) { - this.id = id; - } - - public int getId() { - return id; - } - - public void setName(String name) { - this.name = name; - } - - public String getName() { - return name; - } - - public void setServers(List servers) { - this.servers = servers; - } - - public List getServers() { - return servers; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + id; - result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((servers == null) ? 0 : servers.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; - SharedIpGroup other = (SharedIpGroup) obj; - if (id != other.id) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - if (servers == null) { - if (other.servers != null) - return false; - } else if (!servers.equals(other.servers)) - return false; - return true; - } - - @Override - public String toString() { - return "SharedIpGroup [id=" + id + ", name=" + name + ", servers=" + servers + "]"; - } - -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Version.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Version.java deleted file mode 100644 index d2fa91f94d..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Version.java +++ /dev/null @@ -1,59 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -public class Version { - - private String docURL; - private String id = "v1.0"; - private VersionStatus status; - private String wadl; - - public void setDocURL(String docURL) { - this.docURL = docURL; - } - - public String getDocURL() { - return docURL; - } - - public void setId(String id) { - this.id = id; - } - - public String getId() { - return id; - } - - public void setStatus(VersionStatus status) { - this.status = status; - } - - public VersionStatus getStatus() { - return status; - } - - public void setWadl(String wadl) { - this.wadl = wadl; - } - - public String getWadl() { - return wadl; - } -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/VersionStatus.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/VersionStatus.java deleted file mode 100644 index f3270887dd..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/VersionStatus.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -public enum VersionStatus { - - BETA, CURRENT, DEPRECATED, UNRECOGNIZED; - - public String value() { - return name(); - } - - public static VersionStatus fromValue(String v) { - try { - return valueOf(v); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } - -} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/WeeklyBackup.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/WeeklyBackup.java deleted file mode 100644 index f637b366ac..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/WeeklyBackup.java +++ /dev/null @@ -1,37 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.domain; - -public enum WeeklyBackup { - - DISABLED, SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, UNRECOGNIZED; - - public String value() { - return name(); - } - - public static WeeklyBackup fromValue(String v) { - try { - return valueOf(v); - } catch (IllegalArgumentException e) { - return UNRECOGNIZED; - } - } - -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 07052ec444..2da320c57a 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -32,10 +32,7 @@ import org.jclouds.openstack.TestOpenStackAuthenticationModule; import org.jclouds.openstack.filters.AddTimestampQuery; import org.jclouds.openstack.filters.AuthenticateRequest; import org.jclouds.openstack.nova.config.NovaRestClientModule; -import org.jclouds.openstack.nova.domain.BackupSchedule; -import org.jclouds.openstack.nova.domain.DailyBackup; import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.WeeklyBackup; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; import org.jclouds.openstack.nova.options.ListOptions; @@ -96,25 +93,6 @@ public class NovaAsyncClientTest extends RestClientTest { } - @Test - public void testCreateServerWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withSharedIpGroup(2)); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - @Test public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, @@ -158,27 +136,6 @@ public class NovaAsyncClientTest extends RestClientTest { } - public void testCreateServerWithIpGroupAndSharedIp() throws IOException, SecurityException, NoSuchMethodException, - UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, - withSharedIpGroup(2).withSharedIp("127.0.0.1")); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); HttpRequest request = processor.createRequest(method, 2); @@ -426,94 +383,6 @@ public class NovaAsyncClientTest extends RestClientTest { checkFilters(request); } - public void testShareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class, - boolean.class); - HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false); - - assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":false}}", - MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testShareIpConfig() throws IOException, SecurityException, NoSuchMethodException, UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("shareIp", String.class, int.class, int.class, - boolean.class); - HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, true); - - assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"shareIp\":{\"sharedIpGroupId\":3,\"configureServer\":true}}", - MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testUnshareIpNoConfig() throws IOException, SecurityException, NoSuchMethodException, - UnknownHostException { - Method method = NovaAsyncClient.class.getMethod("unshareIp", String.class, int.class); - HttpRequest request = processor.createRequest(method, "127.0.0.1", 2, 3, false); - - assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2/ips/public/127.0.0.1 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnVoidOnNotFoundOr404.class); - - checkFilters(request); - - } - - public void testReplaceBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("replaceBackupSchedule", int.class, BackupSchedule.class); - HttpRequest request = processor.createRequest(method, 2, new BackupSchedule(WeeklyBackup.MONDAY, - DailyBackup.H_0800_1000, true)); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/backup_schedule HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, - "{\"backupSchedule\":{\"daily\":\"H_0800_1000\",\"enabled\":true,\"weekly\":\"MONDAY\"}}", - MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOn404.class); - - checkFilters(request); - - } - - public void testDeleteBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteBackupSchedule", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2/backup_schedule HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(request); - - } - public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); HttpRequest request = processor.createRequest(method, 2, "foo"); @@ -546,135 +415,6 @@ public class NovaAsyncClientTest extends RestClientTest { } - public void testListSharedIpGroups() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); - - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(request); - } - - public void testListSharedIpGroupsOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(request); - } - - public void testListSharedIpGroupsDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); - - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(request); - } - - public void testListSharedIpGroupsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listSharedIpGroups", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); - - checkFilters(request); - } - - public void testGetSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getSharedIpGroup", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/shared_ip_groups/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - - checkFilters(request); - } - - private static final Class createSharedIpGroupOptionsVarargsClass = new CreateSharedIpGroupOptions[]{} - .getClass(); - - public void testCreateSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, - createSharedIpGroupOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie"); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/shared_ip_groups?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"sharedIpGroup\":{\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testCreateSharedIpGroupWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createSharedIpGroup", String.class, - createSharedIpGroupOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", withServer(2)); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/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); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testDeleteSharedIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteSharedIpGroup", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/shared_ip_groups/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - - checkFilters(request); - } - public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); HttpRequest request = processor.createRequest(method, 2); @@ -721,22 +461,6 @@ public class NovaAsyncClientTest extends RestClientTest { checkFilters(request); } - @Test - public void testListBackupSchedule() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getBackupSchedule", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/backup_schedule?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); - - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, MapHttp4xxCodesToExceptions.class); - - checkFilters(request); - } - @Test public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index e23449bd10..47375f4e8e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -260,68 +260,6 @@ public class NovaClientLiveTest { assert client.getFlavor(12312987) == null; } - public void testListSharedIpGroups() throws Exception { - Set response = client.listSharedIpGroups(); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - assertTrue(sharedIpGroup.getId() >= 0); - assert null != sharedIpGroup.getName() : sharedIpGroup; - } - - } - - public void testListSharedIpGroupsDetail() throws Exception { - Set response = client.listSharedIpGroups(withDetails()); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - assertTrue(sharedIpGroup.getId() >= 1); - assert null != sharedIpGroup.getName() : sharedIpGroup; - assert null != sharedIpGroup.getServers() : sharedIpGroup; - } - } - - public void testGetSharedIpGroupsDetail() throws Exception { - Set response = client.listSharedIpGroups(withDetails()); - assert null != response; - long sharedIpGroupCount = response.size(); - assertTrue(sharedIpGroupCount >= 0); - for (SharedIpGroup sharedIpGroup : response) { - SharedIpGroup newDetails = client.getSharedIpGroup(sharedIpGroup.getId()); - assertEquals(sharedIpGroup, newDetails); - } - } - - @Test - public void testGetSharedIpGroupDetailsNotFound() throws Exception { - assert client.getSharedIpGroup(12312987) == null; - } - - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testCreateSharedIpGroup() throws Exception { - SharedIpGroup sharedIpGroup = null; - while (sharedIpGroup == null) { - String sharedIpGroupName = serverPrefix + "createSharedIpGroup" + new SecureRandom().nextInt(); - try { - sharedIpGroup = client.createSharedIpGroup(sharedIpGroupName, withServer(serverId)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } - assertNotNull(sharedIpGroup.getName()); - sharedIpGroupId = sharedIpGroup.getId(); - // Response doesn't include the server id Web Hosting #119311 - // assertEquals(sharedIpGroup.getServers(), ImmutableList.of(serverId)); - } - - private int sharedIpGroupId; - private String serverPrefix = System.getProperty("user.name") + ".cs"; private int serverId; private String adminPass; @@ -468,33 +406,6 @@ public class NovaClientLiveTest { this.adminPass = "elmo"; } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateSharedIpGroup") - public void testCreateServerIp() throws Exception { - int imageId = 14362; - int flavorId = 1; - Server server = null; - 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)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } - assertNotNull(server.getAdminPass()); - serverId2 = server.getId(); - adminPass2 = server.getAdminPass(); - blockUntilServerActive(serverId2); - assertIpConfigured(server, adminPass2); - 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"); @@ -507,15 +418,6 @@ public class NovaClientLiveTest { } } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateServerIp") - public void testUnshare() throws Exception { - client.unshareIp(ip, serverId2); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert !server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpNotConfigured(server, adminPass2); - } - private void assertIpNotConfigured(Server server, String password) { try { ExecResponse response = exec(server, password, "ifconfig -a"); @@ -528,39 +430,6 @@ public class NovaClientLiveTest { } } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testUnshare") - public void testShareConfig() throws Exception { - client.shareIp(ip, serverId2, sharedIpGroupId, true); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpConfigured(server, adminPass2); - testUnshare(); - } - - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareConfig") - public void testShareNoConfig() throws Exception { - client.shareIp(ip, serverId2, sharedIpGroupId, false); - blockUntilServerActive(serverId2); - Server server = client.getServer(serverId2); - assert server.getAddresses().getPublicAddresses().contains(ip) : server.getAddresses(); - assertIpNotConfigured(server, adminPass2); - testUnshare(); - } - - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testShareNoConfig") - public void testBackup() throws Exception { - assertEquals(new BackupSchedule(), client.getBackupSchedule(serverId)); - BackupSchedule dailyWeekly = new BackupSchedule(); - dailyWeekly.setEnabled(true); - dailyWeekly.setWeekly(WeeklyBackup.FRIDAY); - dailyWeekly.setDaily(DailyBackup.H_0400_0600); - client.replaceBackupSchedule(serverId, dailyWeekly); - client.deleteBackupSchedule(serverId); - // disables, doesn't delete: Web Hosting #119571 - assertEquals(client.getBackupSchedule(serverId).isEnabled(), false); - } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") public void testCreateImage() throws Exception { Image image = client.createImageFromServer("hoofie", serverId); @@ -633,14 +502,6 @@ public class NovaClientLiveTest { } } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"deleteServer1"}) - void testDeleteSharedIpGroup() { - if (sharedIpGroupId > 0) { - client.deleteSharedIpGroup(sharedIpGroupId); - assert client.getSharedIpGroup(sharedIpGroupId) == null; - } - } - @AfterTest void deleteServersOnEnd() { if (serverId > 0) { @@ -649,8 +510,5 @@ public class NovaClientLiveTest { if (serverId2 > 0) { client.deleteServer(serverId2); } - if (sharedIpGroupId > 0) { - client.deleteSharedIpGroup(sharedIpGroupId); - } } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseBackupScheduleFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseBackupScheduleFromJsonResponseTest.java deleted file mode 100644 index 868531c5e7..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseBackupScheduleFromJsonResponseTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; - -import org.jclouds.openstack.nova.domain.BackupSchedule; -import org.jclouds.openstack.nova.domain.DailyBackup; -import org.jclouds.openstack.nova.domain.WeeklyBackup; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseBackupScheduleFromJsonResponse} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ParseBackupScheduleFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); - - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_backupschedule.json"); - - UnwrapOnlyJsonValue parser = i.getInstance(Key - .get(new TypeLiteral>() { - })); - BackupSchedule response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(new BackupSchedule(WeeklyBackup.THURSDAY, DailyBackup.H_0400_0600, true), response); - } - - public void testNoSchedule() throws UnknownHostException { - - UnwrapOnlyJsonValue parser = i.getInstance(Key - .get(new TypeLiteral>() { - })); - BackupSchedule response = parser.apply(new HttpResponse(200, "ok", Payloads - .newStringPayload("{\"backupSchedule\":{\"enabled\" : false}}"))); - assertEquals(new BackupSchedule(), response); - } -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupFromJsonResponseTest.java deleted file mode 100644 index a1c3ad7c77..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupFromJsonResponseTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; - -import org.jclouds.openstack.nova.domain.SharedIpGroup; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseSharedIpGroupFromJsonResponse} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ParseSharedIpGroupFromJsonResponseTest { - - Injector i = Guice.createInjector(new GsonModule()); - - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_get_sharedipgroup_details.json"); - - UnwrapOnlyJsonValue parser = i.getInstance(Key - .get(new TypeLiteral>() { - })); - SharedIpGroup response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - - assertEquals(response.getId(), 1234); - assertEquals(response.getName(), "Shared IP Group 1"); - assertEquals(response.getServers(), ImmutableList.of(422)); - } -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupListFromJsonResponseTest.java deleted file mode 100644 index 3d92b1415c..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseSharedIpGroupListFromJsonResponseTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.functions; - -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.SharedIpGroup; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; - -/** - * Tests behavior of {@code ParseSharedIpGroupListFromJsonResponse} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class ParseSharedIpGroupListFromJsonResponseTest { - - Injector i = Guice.createInjector(new GsonModule()); - - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups.json"); - - List expects = ImmutableList.of(new SharedIpGroup(1234, "Shared IP Group 1"), new SharedIpGroup( - 5678, "Shared IP Group 2")); - - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - - assertEquals(response, expects); - - } - - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_sharedipgroups_detail.json"); - - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - - assertEquals(response.get(0).getId(), 1234); - assertEquals(response.get(0).getName(), "Shared IP Group 1"); - assertEquals(response.get(0).getServers(), ImmutableList.of(422, 3445)); - - assertEquals(response.get(1).getId(), 5678); - assertEquals(response.get(1).getName(), "Shared IP Group 2"); - assertEquals(response.get(1).getServers(), ImmutableList.of(23203, 2456, 9891)); - - } - -} diff --git a/sandbox-apis/nova/src/test/resources/test_get_sharedipgroup_details.json b/sandbox-apis/nova/src/test/resources/test_get_sharedipgroup_details.json deleted file mode 100644 index d10f33d656..0000000000 --- a/sandbox-apis/nova/src/test/resources/test_get_sharedipgroup_details.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "sharedIpGroup" : { - "id" : 1234, - "name" : "Shared IP Group 1", - "servers" : [422] - } -} \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/test_list_backupschedule.json b/sandbox-apis/nova/src/test/resources/test_list_backupschedule.json deleted file mode 100644 index c2f893a506..0000000000 --- a/sandbox-apis/nova/src/test/resources/test_list_backupschedule.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "backupSchedule" : { - "enabled" : true, - "weekly" : "THURSDAY", - "daily" : "H_0400_0600" - } -} \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups.json b/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups.json deleted file mode 100644 index 73717c4a76..0000000000 --- a/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "sharedIpGroups" : [ - { - "id" : 1234, - "name" : "Shared IP Group 1" - }, - { - "id" : 5678, - "name" : "Shared IP Group 2" - } - ] -} \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups_detail.json b/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups_detail.json deleted file mode 100644 index de6e37336b..0000000000 --- a/sandbox-apis/nova/src/test/resources/test_list_sharedipgroups_detail.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "sharedIpGroups" : [ - { - "id" : 1234, - "name" : "Shared IP Group 1", - "servers" : [422, 3445] - }, - { - "id" : 5678, - "name" : "Shared IP Group 2", - "servers" : [23203, 2456, 9891] - } - ] -} \ No newline at end of file From 95b060218a17813de36a86b318fde60f5e3a6a55 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Mon, 11 Apr 2011 03:15:13 +0400 Subject: [PATCH 17/95] API is updated to use URI references --- .../openstack/nova/NovaAsyncClient.java | 6 +- .../jclouds/openstack/nova/NovaClient.java | 4 +- .../compute/functions/FlavorToHardware.java | 11 +- .../compute/functions/NovaImageToImage.java | 4 + .../functions/ServerToNodeMetadata.java | 1 + ...ovaCreateNodeWithGroupEncodedIntoName.java | 4 +- .../jclouds/openstack/nova/domain/Flavor.java | 2 +- .../jclouds/openstack/nova/domain/Image.java | 29 ++++- .../openstack/nova/domain/Resource.java | 27 +++++ .../jclouds/openstack/nova/domain/Server.java | 20 +--- .../nova/options/CreateServerOptions.java | 17 +-- .../openstack/nova/NovaClientLiveTest.java | 7 +- .../jclouds/openstack/nova/_NovaClient.java | 108 +++++++++--------- 13 files changed, 147 insertions(+), 93 deletions(-) create mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java index 9dec5dfe32..cedc2c9ebb 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java @@ -18,6 +18,8 @@ */ package org.jclouds.openstack.nova; +import java.net.URI; +import java.net.URL; import java.util.Set; import java.util.concurrent.ExecutionException; @@ -155,8 +157,8 @@ public interface NovaAsyncClient { @QueryParams(keys = "format", values = "json") @Path("/servers") @MapBinder(CreateServerOptions.class) - ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageId") int imageId, - @PayloadParam("flavorId") int flavorId, CreateServerOptions... options); + ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, + @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); /** * @see NovaClient#rebuildServer diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java index 01e3f7a4a3..0c39883f1d 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java @@ -18,6 +18,8 @@ */ package org.jclouds.openstack.nova; +import java.net.URI; +import java.net.URL; import java.util.Set; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -152,7 +154,7 @@ public interface NovaClient { * @param options * - used to specify extra files, metadata, or ip parameters during server creation. */ - Server createServer(String name, int imageId, int flavorId, CreateServerOptions... options); + Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); /** * The rebuild function removes all data on the server and replaces it with the specified image. diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardware.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardware.java index 8f5064a61b..f166754303 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardware.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardware.java @@ -36,8 +36,13 @@ import com.google.common.collect.ImmutableList; @Singleton public class FlavorToHardware implements Function { public Hardware apply(Flavor from) { - return new HardwareBuilder().ids(from.getId() + "").name(from.getName()) - .processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))).ram(from.getRam()) - .volumes(ImmutableList. of(new VolumeImpl((float) from.getDisk(), true, true))).build(); + return new HardwareBuilder() + .ids(from.getId() + "") + .name(from.getName()) + .processors(ImmutableList.of(new Processor(from.getDisk() / 10.0, 1.0))) + .ram(from.getRam()) + .volumes(ImmutableList. of(new VolumeImpl((float) from.getDisk(), true, true))) + .uri(from.getURI()) + .build(); } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index 9822046e8d..6a880dd9fc 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -28,6 +28,9 @@ import org.jclouds.domain.Credentials; import com.google.common.base.Function; +import java.util.List; +import java.util.Map; + /** * * @author Adrian Cole @@ -49,6 +52,7 @@ public class NovaImageToImage implements Function { builder.publicAddresses(from.getAddresses().getPublicAddresses()); builder.privateAddresses(from.getAddresses().getPrivateAddresses()); builder.credentials(credentialStore.get("node#" + from.getId())); + builder.uri(from.getURI()); return builder.build(); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java index 71e37bbb16..5769efad8e 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java @@ -53,8 +53,8 @@ public class NovaCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGro @Override public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) { - Server from = client.createServer(name, Integer.parseInt(template.getImage().getProviderId()), Integer - .parseInt(template.getHardware().getProviderId())); + Server from = client.createServer(name, template.getImage().getUri().toString(), + template.getHardware().getUri().toString()); credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass())); return serverToNodeMetadata.apply(from); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Flavor.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Flavor.java index b0f9cb2b1b..94ab5c61cf 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Flavor.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Flavor.java @@ -25,7 +25,7 @@ package org.jclouds.openstack.nova.domain; * * @author Adrian Cole */ -public class Flavor { +public class Flavor extends Resource { public Flavor() { } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java index a98eeeecf9..115ce7640b 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java @@ -18,7 +18,20 @@ */ package org.jclouds.openstack.nova.domain; +import com.google.common.base.Objects; +import com.google.common.base.Predicate; +import com.google.common.collect.Collections2; +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; + +import javax.annotation.Nullable; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Collections; import java.util.Date; +import java.util.List; +import java.util.Map; /** * An image is a collection of files used to create or rebuild a server. Rackspace provides a number @@ -28,7 +41,7 @@ import java.util.Date; * * @author Adrian Cole */ -public class Image { +public class Image extends Resource { private Date created; private int id; @@ -37,6 +50,7 @@ public class Image { private Integer serverId; private ImageStatus status; private Date updated; + private Map metadata = Maps.newHashMap(); public Image() { } @@ -101,8 +115,17 @@ public class Image { public Date getUpdated() { return updated; } + + public Map getMetadata() { + return Collections.unmodifiableMap(metadata); + } + + public void setMetadata(Map metadata) { + this.metadata = Maps.newHashMap(metadata); + } + /** - * note that this ignores the create time + * note that this ignores some fields */ @Override public int hashCode() { @@ -115,7 +138,7 @@ public class Image { } /** - * note that this ignores the serverid and create time. + * note that this ignores some fields */ @Override public boolean equals(Object obj) { diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java new file mode 100644 index 0000000000..ea6b09d3fa --- /dev/null +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java @@ -0,0 +1,27 @@ +package org.jclouds.openstack.nova.domain; + +import com.google.common.collect.Lists; + +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; +import java.util.Map; + +/** + * @author Dmitri Babaev + */ +public class Resource { + private List> links = Lists.newArrayList(); + + public URI getURI() { + for (Map linkProperties : links) { + try { + return new URI(linkProperties.get("href")); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + throw new IllegalStateException("URI is not available"); + } +} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java index 1ef8e28bd7..9ebdba385f 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java @@ -28,7 +28,7 @@ import com.google.common.collect.Maps; * * @author Adrian Cole */ -public class Server { +public class Server extends Resource { private int id; private String name; @@ -39,7 +39,6 @@ public class Server { private Integer flavorId; private String hostId; private Integer imageId; - private Integer sharedIpGroupId; private Integer progress; private ServerStatus status; @@ -124,14 +123,6 @@ public class Server { return progress; } - public void setSharedIpGroupId(Integer sharedIpGroupId) { - this.sharedIpGroupId = sharedIpGroupId; - } - - public Integer getSharedIpGroupId() { - return sharedIpGroupId; - } - public void setStatus(ServerStatus status) { this.status = status; } @@ -156,7 +147,6 @@ public class Server { result = prime * result + ((imageId == null) ? 0 : imageId.hashCode()); result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((sharedIpGroupId == null) ? 0 : sharedIpGroupId.hashCode()); return result; } @@ -206,11 +196,6 @@ public class Server { return false; } else if (!name.equals(other.name)) return false; - if (sharedIpGroupId == null) { - if (other.sharedIpGroupId != null) - return false; - } else if (!sharedIpGroupId.equals(other.sharedIpGroupId)) - return false; return true; } @@ -222,8 +207,7 @@ public class Server { public String toString() { return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorId=" + flavorId + ", hostId=" + hostId + ", id=" + id + ", imageId=" + imageId - + ", metadata=" + metadata + ", name=" + name + ", sharedIpGroupId=" - + sharedIpGroupId + "]"; + + ", metadata=" + metadata + ", name=" + name + "]"; } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java index 14f4fb578f..0457299495 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java @@ -22,6 +22,7 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; +import java.net.URI; import java.util.List; import java.util.Map; import java.util.Map.Entry; @@ -70,17 +71,17 @@ public class CreateServerOptions extends BindToJsonPayload { @SuppressWarnings("unused") private class ServerRequest { final String name; - final int imageId; - final int flavorId; + final String imageRef; + final String flavorRef; Map metadata; List personality; Integer sharedIpGroupId; Addresses addresses; - private ServerRequest(String name, int imageId, int flavorId) { + private ServerRequest(String name, String imageRef, String flavorRef) { this.name = name; - this.imageId = imageId; - this.flavorId = flavorId; + this.imageRef = imageRef; + this.flavorRef = flavorRef; } } @@ -93,9 +94,9 @@ public class CreateServerOptions extends BindToJsonPayload { @Override public R bindToRequest(R request, Map postParams) { ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), - "name parameter not present"), Integer.parseInt(checkNotNull(postParams - .get("imageId"), "imageId parameter not present")), Integer.parseInt(checkNotNull( - postParams.get("flavorId"), "flavorId parameter not present"))); + "name parameter not present"), checkNotNull(postParams + .get("imageRef"), "imageRef parameter not present"), checkNotNull( + postParams.get("flavorRef"), "flavorRef parameter not present")); if (metadata.size() > 0) server.metadata = metadata; if (files.size() > 0) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 47375f4e8e..4b5202ed06 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -46,6 +46,7 @@ import org.testng.annotations.Test; import java.io.IOException; import java.lang.reflect.UndeclaredThrowableException; +import java.net.URI; import java.security.SecureRandom; import java.util.Map; import java.util.Properties; @@ -271,13 +272,13 @@ public class NovaClientLiveTest { @Test(enabled = true) public void testCreateServer() throws Exception { - int imageId = 14362; - int flavorId = 1; + String imageRef = "14362"; + String flavorRef = "1"; Server server = null; while (server == null) { String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); try { - server = client.createServer(serverName, imageId, flavorId, withFile("/etc/jclouds.txt", + server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata)); } catch (UndeclaredThrowableException e) { HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index d05515702a..4e16a9024f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,52 +1,56 @@ -package org.jclouds.openstack.nova; - -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.ssh.jsch.config.JschSshClientModule; - -import java.util.Collections; -import java.util.Properties; - -import static org.jclouds.Constants.PROPERTY_ENDPOINT; - -public class _NovaClient { - static public void main(String[] args) { - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ - //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json - - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; - String endpoint = "http://172.18.34.40:8774"; - - ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); - - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_ENDPOINT, endpoint); - ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, Collections.singleton(new JschSshClientModule()), overrides); - - ComputeService cs = context.getComputeService(); - - System.out.println(cs.listImages()); - //System.out.println(cs.listNodes()); - - TemplateOptions options = new TemplateOptions(); - //options.authorizePublicKey(""); - //Template template = cs.templateBuilder().hardwareId("m1.small").imageId("13").options(options).build(); - //try { - // cs.runNodesWithTag("test", 1, template); - //} catch (RunNodesException e) { - // e.printStackTrace(); - //} - - //System.out.println(cs.listNodes()); - //System.out.println(cs.listImages()); - //System.out.println(cs.listNodes()); - //System.out.println(cs.listAssignableLocations()); - //System.out.println(cs.listHardwareProfiles()); - } -} +package org.jclouds.openstack.nova; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.ssh.jsch.config.JschSshClientModule; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Properties; + +import static org.jclouds.Constants.PROPERTY_ENDPOINT; + +public class _NovaClient { + static public void main(String[] args) { + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json + + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + String endpoint = "http://dragon004.hw.griddynamics.net:8774"; + + ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); + + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_ENDPOINT, endpoint); + ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, + Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); + + ComputeService cs = context.getComputeService(); + + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + //System.out.println(cs.listNodes()); + + TemplateOptions options = new TemplateOptions(); + //options.authorizePublicKey(""); + Template template = cs.templateBuilder().imageId("13").options(options).build(); + try { + cs.runNodesWithTag("test", 1, template); + } catch (RunNodesException e) { + e.printStackTrace(); + } + + //System.out.println(cs.listNodes()); + //System.out.println(cs.listImages()); + //System.out.println(cs.listNodes()); + //System.out.println(cs.listAssignableLocations()); + //System.out.println(cs.listHardwareProfiles()); + } +} From f66e27c2ca9b93f4288d205f24caa8d7b23fe26d Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Mon, 11 Apr 2011 22:45:28 +0400 Subject: [PATCH 18/95] test tool --- .../jclouds/openstack/nova/_NovaClient.java | 115 +++++++++--------- 1 file changed, 59 insertions(+), 56 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index 4e16a9024f..a5c750d3d4 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,56 +1,59 @@ -package org.jclouds.openstack.nova; - -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; -import org.jclouds.ssh.jsch.config.JschSshClientModule; - -import java.util.Arrays; -import java.util.Collections; -import java.util.Properties; - -import static org.jclouds.Constants.PROPERTY_ENDPOINT; - -public class _NovaClient { - static public void main(String[] args) { - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ - //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json - - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; - String endpoint = "http://dragon004.hw.griddynamics.net:8774"; - - ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); - - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_ENDPOINT, endpoint); - ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, - Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); - - ComputeService cs = context.getComputeService(); - - System.out.println(cs.listImages()); - System.out.println(cs.listHardwareProfiles()); - //System.out.println(cs.listNodes()); - - TemplateOptions options = new TemplateOptions(); - //options.authorizePublicKey(""); - Template template = cs.templateBuilder().imageId("13").options(options).build(); - try { - cs.runNodesWithTag("test", 1, template); - } catch (RunNodesException e) { - e.printStackTrace(); - } - - //System.out.println(cs.listNodes()); - //System.out.println(cs.listImages()); - //System.out.println(cs.listNodes()); - //System.out.println(cs.listAssignableLocations()); - //System.out.println(cs.listHardwareProfiles()); - } -} +package org.jclouds.openstack.nova; + +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.ssh.jsch.config.JschSshClientModule; + +import java.util.Arrays; +import java.util.Collections; +import java.util.Properties; +import java.util.Set; + +import static org.jclouds.Constants.PROPERTY_ENDPOINT; + +public class _NovaClient { + static public void main(String[] args) { + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json + + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + String endpoint = "http://dragon004.hw.griddynamics.net:8774"; + + ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); + + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_ENDPOINT, endpoint); + ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, + Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); + + ComputeService cs = context.getComputeService(); + + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + //System.out.println(cs.listNodes()); + + TemplateOptions options = new TemplateOptions(); + //options.authorizePublicKey(""); + Template template = cs.templateBuilder().imageId("13").options(options).build(); + try { + Set metedata = cs.runNodesWithTag("test", 1, template); + System.out.println(metedata); + } catch (RunNodesException e) { + e.printStackTrace(); + } + + //System.out.println(cs.listNodes()); + //System.out.println(cs.listImages()); + //System.out.println(cs.listNodes()); + //System.out.println(cs.listAssignableLocations()); + //System.out.println(cs.listHardwareProfiles()); + } +} From 5e2bae24e868baa6cea7081ddc6509ccfe91accd Mon Sep 17 00:00:00 2001 From: vicglarson Date: Wed, 13 Apr 2011 16:56:03 +0400 Subject: [PATCH 19/95] Changed jsons to parser tests. Removed unnecessary catches. --- .../openstack/nova/NovaClientLiveTest.java | 55 ++---- .../functions/NovaImageToImageTest.java | 47 +++--- .../ParseAddressesFromJsonResponseTest.java | 50 +++--- .../ParseFlavorFromJsonResponseTest.java | 54 +++--- .../resources/test_get_flavor_details.json | 32 +++- .../resources/test_get_image_details.json | 42 +++-- .../resources/test_get_server_detail.json | 81 ++++++--- .../test/resources/test_list_addresses.json | 31 ++-- .../src/test/resources/test_list_flavors.json | 58 +++++-- .../resources/test_list_flavors_detail.json | 66 ++++++-- .../src/test/resources/test_list_images.json | 1 + .../src/test/resources/test_list_servers.json | 59 +++++-- .../resources/test_list_servers_detail.json | 156 +++++++++++++----- 13 files changed, 480 insertions(+), 252 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 4b5202ed06..07a07a0761 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -37,7 +37,6 @@ import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.SocketOpen; import org.jclouds.rest.RestContextFactory; import org.jclouds.ssh.SshClient; -import org.jclouds.ssh.SshException; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; @@ -45,8 +44,6 @@ import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import java.io.IOException; -import java.lang.reflect.UndeclaredThrowableException; -import java.net.URI; import java.security.SecureRandom; import java.util.Map; import java.util.Properties; @@ -55,7 +52,6 @@ import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; @@ -274,19 +270,10 @@ public class NovaClientLiveTest { public void testCreateServer() throws Exception { String imageRef = "14362"; String flavorRef = "1"; - Server server = null; - while (server == null) { - String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); - try { - server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", - "rackspace".getBytes()).withMetadata(metadata)); - } catch (UndeclaredThrowableException e) { - HttpResponseException htpe = (HttpResponseException) e.getCause().getCause(); - if (htpe.getResponse().getStatusCode() == 400) - continue; - throw e; - } - } + String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); + Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + assertNotNull(server.getAdminPass()); serverId = server.getId(); adminPass = server.getAdminPass(); @@ -296,7 +283,7 @@ public class NovaClientLiveTest { } private void blockUntilServerActive(int serverId) throws InterruptedException { - Server currentDetails = null; + Server currentDetails; for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client .getServer(serverId)) { System.out.printf("blocking on status active%n%s%n", currentDetails); @@ -305,7 +292,7 @@ public class NovaClientLiveTest { } private void blockUntilServerVerifyResize(int serverId) throws InterruptedException { - Server currentDetails = null; + Server currentDetails; for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client .getServer(serverId)) { System.out.printf("blocking on status verify resize%n%s%n", currentDetails); @@ -314,7 +301,7 @@ public class NovaClientLiveTest { } private void blockUntilImageActive(int imageId) throws InterruptedException { - Image currentDetails = null; + Image currentDetails; for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client .getImage(imageId)) { System.out.printf("blocking on status active%n%s%n", currentDetails); @@ -350,17 +337,10 @@ public class NovaClientLiveTest { */ private void checkPassOk(Server newDetails, String pass) throws IOException { - try { - doCheckPass(newDetails, pass); - } catch (SshException e) {// try twice in case there is a network timeout - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e1) { - } - doCheckPass(newDetails, pass); - } + doCheckPass(newDetails, pass); } + private void doCheckPass(Server newDetails, String pass) throws IOException { IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22); socketTester.apply(socket); @@ -419,18 +399,13 @@ public class NovaClientLiveTest { } } - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } + private void assertIpNotConfigured(Server server, String password) throws IOException { + 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); } + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") public void testCreateImage() throws Exception { Image image = client.createImageFromServer("hoofie", serverId); @@ -445,7 +420,7 @@ public class NovaClientLiveTest { client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); blockUntilServerActive(serverId); // issue Web Hosting #119580 imageId comes back incorrect after rebuild - // assertEquals(new Integer(imageId), client.getServer(serverId).getImageId()); + assertEquals(new Integer(imageId), client.getServer(serverId).getImageId()); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index 7e7045f474..e780ba0c2d 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -18,14 +18,11 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static org.testng.Assert.assertEquals; - -import java.net.UnknownHostException; - +import com.google.inject.Guice; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; -import org.jclouds.compute.domain.OperatingSystemBuilder; +import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; @@ -34,7 +31,9 @@ import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.testng.annotations.Test; -import com.google.inject.Guice; +import java.net.UnknownHostException; + +import static org.testng.Assert.assertEquals; /** * @author Adrian Cole @@ -42,25 +41,25 @@ import com.google.inject.Guice; @Test(groups = "unit") public class NovaImageToImageTest { - @Test - public void testApplyWhereImageNotFound() throws UnknownHostException { - assertEquals( - convertImage(), - new ImageBuilder() - .name("CentOS 5.2") - .operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) - .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("2").version("1286712000000").build()); - } + @Test + public void testApplyWhereImageNotFound() throws UnknownHostException { + assertEquals( + convertImage(), + new ImageBuilder() + .name("CentOS 5.2") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) + .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) + .ids("2").version("1286712000000").build()); + } - public static Image convertImage() { - org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); + public static Image convertImage() { + org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); - NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)))); + NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { + }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) + .getInstance(Json.class)))); - return parser.apply(image); - } + return parser.apply(image); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index 19724a6bd3..cc5af7dfe7 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -18,45 +18,45 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Addresses; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseAddressesFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseAddressesFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - List publicAddresses = ImmutableList.of("67.23.10.132", "67.23.10.131"); + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - List privateAddresses = ImmutableList.of("10.176.42.16"); + List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); - assertEquals(response.getPublicAddresses(), publicAddresses); - assertEquals(response.getPrivateAddresses(), privateAddresses); - } + List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); + + assertEquals(response.getPublicAddresses(), publicAddresses); + assertEquals(response.getPrivateAddresses(), privateAddresses); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java index ada42756c8..6a9dfc6a71 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java @@ -18,47 +18,51 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; - -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - import com.google.gson.Gson; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.util.Strings2; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.io.InputStream; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseFlavorFromJsonResponseTest { - public void test() { - Flavor response = parseFlavor(); + public void test() throws IOException { + Flavor response = parseFlavor(); - String json = new Gson().toJson(response); + String json = new Gson().toJson(response); - assertEquals(json, "{\"id\":1,\"name\":\"256 MB Server\",\"disk\":10,\"ram\":256}"); - } + String expectedJson = Strings2.toStringAndClose( + ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json")) + .replace("\n", "").replace("\t", "").replace("\r", "").replace(" ", ""); - public static Flavor parseFlavor() { - Injector i = Guice.createInjector(new GsonModule()); + assertEquals(json, expectedJson); + } - InputStream is = ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json"); + public static Flavor parseFlavor() { + Injector i = Guice.createInjector(new GsonModule()); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Flavor response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; - } + InputStream is = ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json"); + + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + return parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + } } diff --git a/sandbox-apis/nova/src/test/resources/test_get_flavor_details.json b/sandbox-apis/nova/src/test/resources/test_get_flavor_details.json index 28500d2d6b..bd3266c04e 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_flavor_details.json +++ b/sandbox-apis/nova/src/test/resources/test_get_flavor_details.json @@ -1,8 +1,24 @@ -{ - "flavor" : { - "id" : 1, - "name" : "256 MB Server", - "ram" : 256, - "disk" : 10 - } -} +{ + "flavor" : { + "id" : 1, + "name" : "256 MB Server", + "ram" : 256, + "disk" : 10, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.computev1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.computev1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + } + ] + } +} \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/test_get_image_details.json b/sandbox-apis/nova/src/test/resources/test_get_image_details.json index e73095bb77..07fdb578e4 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_image_details.json +++ b/sandbox-apis/nova/src/test/resources/test_get_image_details.json @@ -1,11 +1,33 @@ -{ - "image" : { - "id" : 2, - "name" : "CentOS 5.2", - "serverId" : 12, - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "status" : "SAVING", - "progress" : 80 - } +{ + "image" : { + "id" : 1, + "name" : "CentOS 5.2", + "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "SAVING", + "progress" : 80, + "metadata" : { + "values" : { + "ImageVersion" : "1.5", + "ImageType" : "Gold" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.computev1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.computev1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + } } \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json index c90bb0bc96..d5f49cdbbd 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json @@ -1,25 +1,56 @@ -{ - "server" : { - "id" : 1234, - "name" : "sample-server", - "imageId" : 2, - "flavorId" : 1, - "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", - "status" : "BUILD", - "progress" : 60, - "addresses" : { - "public" : [ - "67.23.10.132", - "67.23.10.131" - ], - "private" : [ - "10.176.42.16" - ] - }, - "metadata" : { - "Server Label" : "Web Head 1", - "Image Version" : "2.1" - } - } - -} +{ + "server" : { + "id" : 1234, + "name" : "sample-server", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", + "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", + "status" : "BUILD", + "progress" : 60, + "addresses" : { + "values" : [ + { + "id" : "public", + "values" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ] + }, + { + "id" : "private", + "values" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + } + ] + }, + "metadata" : { + "values" : { + "Server Label" : "Web Head 1", + "Image Version" : "2.1" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + } +} diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses.json b/sandbox-apis/nova/src/test/resources/test_list_addresses.json index 24441b8fac..9f3a235f81 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses.json @@ -1,12 +1,23 @@ -{ - "addresses" : { - "public" : [ - "67.23.10.132", - "67.23.10.131" - ], - "private" : [ - "10.176.42.16" - ] - } +{ + "addresses" : { + "values" : [ + { + "id" : "public", + "values" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ] + }, + { + "id" : "private", + "values" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + } + ] + } } diff --git a/sandbox-apis/nova/src/test/resources/test_list_flavors.json b/sandbox-apis/nova/src/test/resources/test_list_flavors.json index d1cc9bee93..c677ff3f5e 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_flavors.json +++ b/sandbox-apis/nova/src/test/resources/test_list_flavors.json @@ -1,12 +1,46 @@ -{ - "flavors" : [ - { - "id" : 1, - "name" : "256 MB Server" - }, - { - "id" : 2, - "name" : "512 MB Server" - } - ] -} +{ + "flavors" : { + "values" : [ + { + "id" : 1, + "name" : "256 MB Server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + } + ] + }, + { + "id" : 2, + "name" : "512 MB Server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + } + ] + } + ] + } +} diff --git a/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json b/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json index a274908f9b..36c6f6852d 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json @@ -1,16 +1,50 @@ -{ - "flavors" : [ - { - "id" : 1, - "name" : "256 MB Server", - "ram" : 256, - "disk" : 10 - }, - { - "id" : 2, - "name" : "512 MB Server", - "ram" : 512, - "disk" : 20 - } - ] -} +{ + "flavors" : { + "values" : [ + { + "id" : 1, + "name" : "256 MB Server", + "ram" : 256, + "disk" : 10, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + } + ] + }, + { + "id" : 2, + "name" : "512 MB Server", + "ram" : 512, + "disk" : 20, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + } + ] + } + ] + } +} diff --git a/sandbox-apis/nova/src/test/resources/test_list_images.json b/sandbox-apis/nova/src/test/resources/test_list_images.json index 5584d7cf83..50bfb5ac90 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images.json @@ -4,6 +4,7 @@ { "id" : 1, "name" : "CentOS 5.2", + }, "links": [ { "rel" : "self", diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers.json b/sandbox-apis/nova/src/test/resources/test_list_servers.json index 3be518e566..c3b22c9d74 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers.json @@ -1,12 +1,47 @@ -{ - "servers" : [ - { - "id" : 1234, - "name" : "sample-server" - }, - { - "id" : 5678, - "name" : "sample-server2" - } - ] -} +{ + "servers" : { + "values" : [ + { + "id" : 1234, + "name" : "sample-server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + }, + { + "id" : 5678, + "name" : "sample-server2", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + } + ] + } + ] + } +} + diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json index a9bc29aa1e..407669d561 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json @@ -1,45 +1,111 @@ -{ - "servers" : [ - { - "id" : 1234, - "name" : "sample-server", - "imageId" : 2, - "flavorId" : 1, - "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", - "status" : "BUILD", - "progress" : 60, - "addresses" : { - "public" : [ - "67.23.10.132", - "67.23.10.131" - ], - "private" : [ - "10.176.42.16" - ] - }, - "metadata" : { - "Server Label" : "Web Head 1", - "Image Version" : "2.1" - } - }, - { - "id" : 5678, - "name" : "sample-server2", - "imageId" : 2, - "flavorId" : 1, - "hostId" : "9e107d9d372bb6826bd81d3542a419d6", - "status" : "ACTIVE", - "addresses" : { - "public" : [ - "67.23.10.133" - ], - "private" : [ - "10.176.42.17" - ] - }, - "metadata" : { - "Server Label" : "DB 1" - } - } - ] -} +{ + "servers" : { + "values" : [ + { + "id" : 1234, + "name" : "sample-server", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", + "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", + "status" : "BUILD", + "progress" : 60, + "addresses" : { + "values" : [ + { + "id" : "public", + "values" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ] + }, + { + "id" : "private", + "values" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + } + ] + }, + "metadata" : { + "values" : { + "Server Label" : "Web Head 1", + "Image Version" : "2.1" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + }, + { + "id" : 5678, + "name" : "sample-server2", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "9e107d9d372bb6826bd81d3542a419d6", + "affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2", + "status" : "ACTIVE", + "addresses" : { + "values" : [ + { + "id" : "public", + "values" : [ + {"version" : 4, "addr" : "67.23.10.133"}, + {"version" : 6, "addr" : "::babe:67.23.10.133"} + ] + }, + { + "id" : "private", + "values" : [ + {"version" : 4, "addr" : "10.176.42.17"}, + {"version" : 6, "addr" : "::babe:10.176.42.17"} + ] + } + ] + }, + "metadata" : { + "values" : { + "Server Label" : "DB 1" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + } + ] + } + ] + } +} + From 8d2d3e80881a059b4ca0012a8465934fa27ce751 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Wed, 13 Apr 2011 18:58:03 +0400 Subject: [PATCH 20/95] Changed expectations for parser tests --- .../ParseAddressesFromJsonResponseTest.java | 1 + .../ParseFlavorFromJsonResponseTest.java | 9 +- .../ParseFlavorListFromJsonResponseTest.java | 79 +++++------ .../ParseImageFromJsonResponseTest.java | 97 +++++++------ .../ParseImageListFromJsonResponseTest.java | 111 ++++++++------- ...seInetAddressListFromJsonResponseTest.java | 59 ++++---- .../ParseServerFromJsonResponseTest.java | 87 ++++++------ .../ParseServerListFromJsonResponseTest.java | 132 ++++++++++-------- .../test_list_addresses_private.json | 17 ++- .../resources/test_list_addresses_public.json | 14 +- .../resources/test_list_images_detail.json | 32 ++++- .../resources/test_list_servers_detail.json | 2 +- 12 files changed, 351 insertions(+), 289 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index cc5af7dfe7..b9e7ab8c49 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -45,6 +45,7 @@ import static org.testng.Assert.assertEquals; public class ParseAddressesFromJsonResponseTest { Injector i = Guice.createInjector(new GsonModule()); + @Test public void testApplyInputStreamDetails() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java index 6a9dfc6a71..7669a50f8a 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java @@ -43,7 +43,9 @@ import static org.testng.Assert.assertEquals; */ @Test(groups = "unit") public class ParseFlavorFromJsonResponseTest { - public void test() throws IOException { + + @Test + public void testParseFlavorFromJsonResponseTest() throws IOException { Flavor response = parseFlavor(); String json = new Gson().toJson(response); @@ -52,6 +54,11 @@ public class ParseFlavorFromJsonResponseTest { ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json")) .replace("\n", "").replace("\t", "").replace("\r", "").replace(" ", ""); + assertEquals(response.getId(), 1); + assertEquals(response.getName(), "256 MB Server"); + assertEquals(response.getDisk().intValue(), 10); + assertEquals(response.getRam().intValue(), 256); + assertEquals(json, expectedJson); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java index f4d6b63bda..064cac1561 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java @@ -18,64 +18,65 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - import com.google.common.collect.ImmutableList; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Flavor; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseFlavorListFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseFlavorListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_flavors.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_flavors.json"); - List expects = ImmutableList.of(new Flavor(1, "256 MB Server"), new Flavor(2, "512 MB Server")); + List expects = ImmutableList.of(new Flavor(1, "256 MB Server"), new Flavor(2, "512 MB Server")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + assertEquals(response, expects); + } - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 1); - assertEquals(response.get(0).getName(), "256 MB Server"); - assertEquals(response.get(0).getDisk(), new Integer(10)); - assertEquals(response.get(0).getRam(), new Integer(256)); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + assertEquals(response.get(0).getId(), 1); + assertEquals(response.get(0).getName(), "256 MB Server"); + assertEquals(response.get(0).getDisk(), new Integer(10)); + assertEquals(response.get(0).getRam(), new Integer(256)); - assertEquals(response.get(1).getId(), 2); - assertEquals(response.get(1).getName(), "512 MB Server"); - assertEquals(response.get(1).getDisk(), new Integer(20)); - assertEquals(response.get(1).getRam(), new Integer(512)); + assertEquals(response.get(1).getId(), 2); + assertEquals(response.get(1).getName(), "512 MB Server"); + assertEquals(response.get(1).getDisk(), new Integer(20)); + assertEquals(response.get(1).getRam(), new Integer(512)); - } + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java index 9fe8962c80..92ab3919a2 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java @@ -18,13 +18,7 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; - -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.ImageStatus; +import com.google.inject.*; import org.jclouds.date.DateService; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; @@ -32,61 +26,66 @@ import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule.DateAdapter; import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.ImageStatus; import org.testng.annotations.Test; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.UnknownHostException; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseImageFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseImageFromJsonResponseTest { - Injector i = Guice.createInjector(new AbstractModule() { + Injector i = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } - - }, new GsonModule()); - - DateService dateService = i.getInstance(DateService.class); - - public void testApplyInputStreamDetails() throws UnknownHostException { - Image response = parseImage(); - - assertEquals(response.getId(), 2); - assertEquals(response.getName(), "CentOS 5.2"); - assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); - assertEquals(response.getProgress(), new Integer(80)); - assertEquals(response.getServerId(), new Integer(12)); - assertEquals(response.getStatus(), ImageStatus.SAVING); - assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z"))); - - } - - public static Image parseImage() { - Injector i = Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { + @Override + protected void configure() { bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } + } - }, new GsonModule()); + }, new GsonModule()); - InputStream is = ParseImageFromJsonResponseTest.class.getResourceAsStream("/test_get_image_details.json"); + DateService dateService = i.getInstance(DateService.class); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; - } + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + Image response = parseImage(); + + assertEquals(response.getId(), 2); + assertEquals(response.getName(), "CentOS 5.2"); + assertEquals(response.getServerId(), new Integer(12)); + assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); + assertEquals(response.getProgress(), new Integer(80)); + assertEquals(response.getStatus(), ImageStatus.SAVING); + assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z"))); + assertEquals(response.getServerId(), "http://servers.api.openstack.org/v1.1/1234/servers/12", "Change serverId to serverRefs"); + assertEquals(response.getMetadata().get("ImageVersion"), "1.5"); + assertEquals(response.getMetadata().get("ImageType"), "Gold"); + assertEquals(response.getMetadata().size(), 2); + } + + public static Image parseImage() { + Injector i = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } + + }, new GsonModule()); + + InputStream is = ParseImageFromJsonResponseTest.class.getResourceAsStream("/test_get_image_details.json"); + + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java index 48c56cfcef..34a5a97d35 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java @@ -18,14 +18,8 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.ImageStatus; +import com.google.common.collect.ImmutableList; +import com.google.inject.*; import org.jclouds.date.DateService; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; @@ -33,69 +27,80 @@ import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; import org.jclouds.json.config.GsonModule.DateAdapter; import org.jclouds.json.config.GsonModule.Iso8601DateAdapter; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.ImageStatus; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseImageListFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseImageListFromJsonResponseTest { - Injector i = Guice.createInjector(new AbstractModule() { + Injector i = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } - },new GsonModule()); - DateService dateService = i.getInstance(DateService.class); + }, new GsonModule()); + DateService dateService = i.getInstance(DateService.class); - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_images.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_images.json"); - List expects = ImmutableList.of(new Image(2, "CentOS 5.2"), new Image(743, "My Server Backup")); + List expects = ImmutableList.of(new Image(1, "CentOS 5.2"), new Image(743, "My Server Backup")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + assertEquals(response, expects); + } - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 2); - assertEquals(response.get(0).getName(), "CentOS 5.2"); - assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); - assertEquals(response.get(0).getProgress(), null); - assertEquals(response.get(0).getServerId(), null); - assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE); - assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); + assertEquals(response.get(0).getId(), 1); + assertEquals(response.get(0).getName(), "CentOS 5.2"); + assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); + assertEquals(response.get(0).getProgress(), null); + assertEquals(response.get(0).getServerId(), null); + assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE); + assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); + assertEquals(response.get(0).getMetadata().get("ImageType"), "Gold"); + assertEquals(response.get(0).getMetadata().get("ImageVersion"), "1.5"); + assertEquals(response.get(0).getMetadata().size(), 2); + assertEquals(response.get(0).getServerId(), null, "Change serverId to serverRef"); - assertEquals(response.get(1).getId(), 743); - assertEquals(response.get(1).getName(), "My Server Backup"); - assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16-05:00")); - ; - assertEquals(response.get(1).getProgress(), new Integer(80)); - assertEquals(response.get(1).getServerId(), new Integer(12)); - assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); - assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); - } + assertEquals(response.get(1).getId(), 743); + assertEquals(response.get(1).getName(), "My Server Backup"); + assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16Z")); + + assertEquals(response.get(1).getProgress(), new Integer(80)); + assertEquals(response.get(1).getServerId(), new Integer(12)); + assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); + assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); + assertEquals(response.get(1).getServerId(), "http://servers.api.openstack.org/v1.1/1234/servers/12", "Change serverId to serverRef"); + + //short form of reference + assertEquals(response.get(2).getServerId().intValue(), 12, "Change serverId to serverRef"); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java index 362f61e27a..090fb1639c 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java @@ -18,53 +18,54 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - +import com.google.common.collect.ImmutableList; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseInetAddressListFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseInetAddressListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - public void testPublic() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); + @Test + public void testPublic() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, ImmutableList.of("67.23.10.132", "67.23.10.131")); - } + assertEquals(response, ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")); + } - public void testPrivate() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); + @Test + public void testPrivate() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, ImmutableList.of("10.176.42.16")); - } + assertEquals(response, ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 86f376ee79..83e72fa642 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -18,65 +18,68 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - +import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseServerFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseServerFromJsonResponseTest { - public void testApplyInputStreamDetails() throws UnknownHostException { - Server response = parseServer(); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + Server response = parseServer(); - assertEquals(response.getId(), 1234); - assertEquals(response.getName(), "sample-server"); - assertEquals(response.getImageId(), new Integer(2)); - assertEquals(response.getFlavorId(), new Integer(1)); - assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(response.getStatus(), ServerStatus.BUILD); - assertEquals(response.getProgress(), new Integer(60)); - List publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131"); - List privateAddresses = Lists.newArrayList("10.176.42.16"); - Addresses addresses1 = new Addresses(); - addresses1.getPrivateAddresses().addAll(privateAddresses); - addresses1.getPublicAddresses().addAll(publicAddresses); - assertEquals(response.getAddresses(), addresses1); - assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.getId(), 1234); + assertEquals(response.getName(), "sample-server"); + assertEquals(response.getImageId().intValue(), 1234); + assertEquals(response.getFlavorId().intValue(), 1); + assertEquals(response.getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); + assertEquals(true, false, "Uncomment next line"); + //assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); + assertEquals(response.getStatus(), ServerStatus.BUILD); + assertEquals(response.getProgress(), new Integer(60)); - } + List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); + List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); + Addresses addresses1 = new Addresses(new HashSet(publicAddresses), new HashSet(privateAddresses)); + assertEquals(response.getAddresses(), addresses1); + assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + } - public static Server parseServer() { - Injector i = Guice.createInjector(new GsonModule()); + public static Server parseServer() { + Injector i = Guice.createInjector(new GsonModule()); - InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); + InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; - } + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index 8a61582da5..a9a470fb08 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -18,89 +18,97 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.List; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseServerListFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class ParseServerListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); - List expects = ImmutableList.of(new Server(1234, "sample-server"), new Server(5678, "sample-server2")); + List expects = ImmutableList.of(new Server(1234, "sample-server"), new Server(5678, "sample-server2")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + assertEquals(response, expects); + } - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 1234); - assertEquals(response.get(0).getName(), "sample-server"); - assertEquals(response.get(0).getImageId(), new Integer(2)); - assertEquals(response.get(0).getFlavorId(), new Integer(1)); - assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); - assertEquals(response.get(0).getProgress(), new Integer(60)); - List publicAddresses = Lists.newArrayList("67.23.10.132", "67.23.10.131"); - List privateAddresses = Lists.newArrayList("10.176.42.16"); - Addresses addresses1 = new Addresses(); - addresses1.getPrivateAddresses().addAll(privateAddresses); - addresses1.getPublicAddresses().addAll(publicAddresses); - assertEquals(response.get(0).getAddresses(), addresses1); - assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); - assertEquals(response.get(1).getId(), 5678); - assertEquals(response.get(1).getName(), "sample-server2"); - assertEquals(response.get(1).getImageId(), new Integer(2)); - assertEquals(response.get(1).getFlavorId(), new Integer(1)); - assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); - assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); - assertEquals(response.get(1).getProgress(), null); - List publicAddresses2 = Lists.newArrayList("67.23.10.133"); - List privateAddresses2 = Lists.newArrayList("10.176.42.17"); - Addresses addresses2 = new Addresses(); - addresses2.getPrivateAddresses().addAll(privateAddresses2); - addresses2.getPublicAddresses().addAll(publicAddresses2); - assertEquals(response.get(1).getAddresses(), addresses2); - assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); + assertEquals(response.get(0).getId(), 1234); + assertEquals(response.get(0).getName(), "sample-server"); + assertEquals(response.get(0).getImageId().intValue(), 1234); + assertEquals(response.get(0).getFlavorId().intValue(), 1); + assertEquals(response.get(0).getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.get(0).getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(true, false, "Uncomment next line"); + //assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); + assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); + assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); + assertEquals(response.get(0).getProgress(), new Integer(60)); - } + List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); + List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); + Addresses addresses1 = new Addresses(new HashSet(publicAddresses), new HashSet(privateAddresses)); + + assertEquals(response.get(0).getAddresses(), addresses1); + assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.get(1).getId(), 5678); + assertEquals(response.get(1).getName(), "sample-server2"); + assertEquals(response.get(0).getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1"); + assertEquals(response.get(0).getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(true, false, "Uncomment next line"); + //assertEquals(response.getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2"); + assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); + assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); + assertEquals(response.get(1).getProgress(), null); + + List publicAddresses2 = ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"); + List privateAddresses2 = ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"); + Addresses addresses2 = new Addresses(new HashSet(publicAddresses2), new HashSet(privateAddresses2)); + + assertEquals(response.get(1).getAddresses(), addresses2); + assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); + assertEquals(response.get(1).getURI(), "http://servers.api.openstack.org/1234/servers/56789"); + + } } diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json index 8c14cf3b93..44297c1ebf 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json @@ -1,8 +1,11 @@ -{ - - "private" : [ - "10.176.42.16" - ] - +{ + "network" { + "id" : "private", + "values" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ] + } } - diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json index 22982ccb40..81277bf69d 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json @@ -1,7 +1,11 @@ -{ - "public" : [ - "67.23.10.132", - "67.23.10.131" +{ + "network" { + "id" : "public", + "values" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} ] + } } - diff --git a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json index 722d1936d8..865cfdc082 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json @@ -35,7 +35,7 @@ "name" : "My Server Backup", "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", + "created" : "2009-07-07T09:56:16Z", "status" : "SAVING", "progress" : 80, "links": [ @@ -54,6 +54,36 @@ "href" : "http://servers.api.openstack.org/1234/images/743" } ] + }, + { + "id" : 5, + "name" : "CentOS 5.2", + "serverRef" : 12, + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "ACTIVE", + "metadata" : { + "values" : { + "ImageType" : "Gold", + "ImageVersion" : "1.5" + } + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] } ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json index 407669d561..219d501bca 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json @@ -101,7 +101,7 @@ { "rel" : "bookmark", "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/5678" + "href" : "http://servers.api.openstack.org/1234/servers/56789" } ] } From 39c642964ac6c8163d82251a2b43358104f28a1d Mon Sep 17 00:00:00 2001 From: vicglarson Date: Thu, 14 Apr 2011 17:32:15 +0400 Subject: [PATCH 21/95] Removed sharedIP. Renamed id to ref in tests. --- .../openstack/nova/NovaAsyncClient.java | 427 ++++++++---------- .../jclouds/openstack/nova/NovaClient.java | 423 ++++++++--------- .../nova/options/CreateServerOptions.java | 310 +++++-------- .../options/CreateSharedIpGroupOptions.java | 87 ---- .../openstack/nova/NovaAsyncClientTest.java | 19 +- .../openstack/nova/NovaClientLiveTest.java | 33 +- .../openstack/nova/PropertyHelper.java | 20 + .../jclouds/openstack/nova/_NovaClient.java | 64 ++- .../compute/NovaComputeServiceLiveTest.java | 15 +- .../ParseFaultFromJsonResponseTest.java | 150 ++++++ .../nova/options/CreateServerOptionsTest.java | 141 ++---- .../CreateSharedIpGroupOptionsTest.java | 79 ---- .../resources/test_fault_response413.json | 9 + 13 files changed, 799 insertions(+), 978 deletions(-) delete mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptions.java create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptionsTest.java create mode 100644 sandbox-apis/nova/src/test/resources/test_fault_response413.json diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java index cedc2c9ebb..d5f6c87e2e 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java @@ -18,49 +18,22 @@ */ package org.jclouds.openstack.nova; -import java.net.URI; -import java.net.URL; -import java.util.Set; -import java.util.concurrent.ExecutionException; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.options.CreateServerOptions; -import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; -import org.jclouds.openstack.nova.options.ListOptions; -import org.jclouds.openstack.nova.options.RebuildServerOptions; -import org.jclouds.http.functions.ReturnFalseOn404; +import com.google.common.util.concurrent.ListenableFuture; import org.jclouds.openstack.filters.AddTimestampQuery; import org.jclouds.openstack.filters.AuthenticateRequest; -import org.jclouds.rest.annotations.BinderParam; -import org.jclouds.rest.annotations.Endpoint; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.MapBinder; -import org.jclouds.rest.annotations.Payload; -import org.jclouds.rest.annotations.PayloadParam; -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.openstack.nova.domain.*; +import org.jclouds.openstack.nova.options.CreateServerOptions; +import org.jclouds.openstack.nova.options.ListOptions; +import org.jclouds.openstack.nova.options.RebuildServerOptions; +import org.jclouds.rest.annotations.*; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnVoidOnNotFoundOr404; -import com.google.common.util.concurrent.ListenableFuture; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Set; +import java.util.concurrent.ExecutionException; /** * Provides asynchronous access to OpenStack Nova via their REST API. @@ -68,221 +41,221 @@ import com.google.common.util.concurrent.ListenableFuture; * All commands return a ListenableFuture of the result from OpenStack Nova. Any exceptions incurred * during processing will be wrapped in an {@link ExecutionException} as documented in * {@link ListenableFuture#get()}. - * + * + * @author Adrian Cole * @see NovaClient * @see - * @author Adrian Cole */ -@SkipEncoding({ '/', '=' }) -@RequestFilters({ AuthenticateRequest.class, AddTimestampQuery.class }) +@SkipEncoding({'/', '='}) +@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class}) @Endpoint(ServerManagement.class) public interface NovaAsyncClient { - /** - * @see NovaClient#listServers - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listServers(ListOptions... options); + /** + * @see NovaClient#listServers + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listServers(ListOptions... options); - /** - * @see NovaClient#getServer - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/servers/{id}") - ListenableFuture getServer(@PathParam("id") int id); + /** + * @see NovaClient#getServer + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/servers/{id}") + ListenableFuture getServer(@PathParam("id") int id); - /** - * @see NovaClient#deleteServer - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/servers/{id}") - ListenableFuture deleteServer(@PathParam("id") int id); + /** + * @see NovaClient#deleteServer + */ + @DELETE + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + @Path("/servers/{id}") + ListenableFuture deleteServer(@PathParam("id") int id); - /** - * @see NovaClient#rebootServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D") - ListenableFuture rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType); + /** + * @see NovaClient#rebootServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D") + ListenableFuture rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType); - /** - * @see NovaClient#resizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D") - ListenableFuture resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId); + /** + * @see NovaClient#resizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D") + ListenableFuture resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId); - /** - * @see NovaClient#confirmResizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("{\"confirmResize\":null}") - ListenableFuture confirmResizeServer(@PathParam("id") int id); + /** + * @see NovaClient#confirmResizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("{\"confirmResize\":null}") + ListenableFuture confirmResizeServer(@PathParam("id") int id); - /** - * @see NovaClient#revertResizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("{\"revertResize\":null}") - ListenableFuture revertResizeServer(@PathParam("id") int id); + /** + * @see NovaClient#revertResizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("{\"revertResize\":null}") + ListenableFuture revertResizeServer(@PathParam("id") int id); - /** - * @see NovaClient#createServer - */ - @POST - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers") - @MapBinder(CreateServerOptions.class) - ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, - @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); + /** + * @see NovaClient#createServer + */ + @POST + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers") + @MapBinder(CreateServerOptions.class) + ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, + @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); - /** - * @see NovaClient#rebuildServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @MapBinder(RebuildServerOptions.class) - ListenableFuture rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); + /** + * @see NovaClient#rebuildServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @MapBinder(RebuildServerOptions.class) + ListenableFuture rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); - /** - * @see NovaClient#changeAdminPass - */ - @PUT - @Path("/servers/{id}") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") - ListenableFuture changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass); + /** + * @see NovaClient#changeAdminPass + */ + @PUT + @Path("/servers/{id}") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") + ListenableFuture changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass); - /** - * @see NovaClient#renameServer - */ - @PUT - @Path("/servers/{id}") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D") - ListenableFuture renameServer(@PathParam("id") int id, @PayloadParam("name") String newName); + /** + * @see NovaClient#renameServer + */ + @PUT + @Path("/servers/{id}") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D") + ListenableFuture renameServer(@PathParam("id") int id, @PayloadParam("name") String newName); - /** - * @see NovaClient#listFlavors - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/flavors") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFlavors(ListOptions... options); + /** + * @see NovaClient#listFlavors + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/flavors") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listFlavors(ListOptions... options); - /** - * @see NovaClient#getFlavor - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/flavors/{id}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getFlavor(@PathParam("id") int id); + /** + * @see NovaClient#getFlavor + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/flavors/{id}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getFlavor(@PathParam("id") int id); - /** - * @see NovaClient#listImages - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/images") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listImages(ListOptions... options); + /** + * @see NovaClient#listImages + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/images") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listImages(ListOptions... options); - /** - * @see NovaClient#getImage - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @QueryParams(keys = "format", values = "json") - @Path("/images/{id}") - ListenableFuture getImage(@PathParam("id") int id); + /** + * @see NovaClient#getImage + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @QueryParams(keys = "format", values = "json") + @Path("/images/{id}") + ListenableFuture getImage(@PathParam("id") int id); - /** - * @see NovaClient#deleteImage - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/images/{id}") - ListenableFuture deleteImage(@PathParam("id") int id); + /** + * @see NovaClient#deleteImage + */ + @DELETE + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + @Path("/images/{id}") + ListenableFuture deleteImage(@PathParam("id") int id); - /** - * @see NovaClient#createImageFromServer - */ - @POST - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/images") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D") - ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, - @PayloadParam("serverId") int serverId); + /** + * @see NovaClient#createImageFromServer + */ + @POST + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/images") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D") + ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, + @PayloadParam("serverId") int serverId); - /** - * @see NovaClient#listAddresses - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips") - ListenableFuture getAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#getAddresses(int) + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips") + ListenableFuture getAddresses(@PathParam("id") int serverId); - /** - * @see NovaClient#listPublicAddresses - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips/public") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listPublicAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#listPublicAddresses(int) + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips/public") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listPublicAddresses(@PathParam("id") int serverId); - /** - * @see NovaClient#listPrivateAddresses - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips/private") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listPrivateAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#listPrivateAddresses + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips/private") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listPrivateAddresses(@PathParam("id") int serverId); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java index 0c39883f1d..1e9c75fb93 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java @@ -18,27 +18,18 @@ */ package org.jclouds.openstack.nova; -import java.net.URI; -import java.net.URL; -import java.util.Set; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; - -import javax.ws.rs.PathParam; - import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.CreateServerOptions; -import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.rest.ResourceNotFoundException; +import javax.ws.rs.PathParam; +import java.util.Set; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; /** * Provides access to OpenStack Nova via their REST API. @@ -46,240 +37,224 @@ import java.util.concurrent.Future; * All commands return a Future of the result from OpenStack Nova. Any exceptions incurred * during processing will be wrapped in an {@link ExecutionException} as documented in * {@link Future#get()}. - * + * + * @author Adrian Cole * @see NovaAsyncClient * @see - * @author Adrian Cole */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface NovaClient { - /** - * - * List all servers (IDs and names only) - * - * This operation provides a list of servers associated with your identity. Servers that have been - * deleted are not included in this list. - *

- * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listServers(ListOptions... options); + /** + * List all servers (IDs and names only) + *

+ * This operation provides a list of servers associated with your identity. Servers that have been + * deleted are not included in this list. + *

+ * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listServers(ListOptions... options); - /** - * - * This operation returns details of the specified server. - * - * @return null, if the server is not found - * @see Server - */ - Server getServer(@PathParam("id") int id); + /** + * This operation returns details of the specified server. + * + * @return null, if the server is not found + * @see Server + */ + Server getServer(@PathParam("id") int id); - /** - * - * This operation deletes a cloud server instance from the system. - *

- * Note: When a server is deleted, all images created from that server are also removed. - * - * @return false if the server is not found - * @see Server - */ - boolean deleteServer(@PathParam("id") int id); + /** + * This operation deletes a cloud server instance from the system. + *

+ * Note: When a server is deleted, all images created from that server are also removed. + * + * @return false if the server is not found + * @see Server + */ + boolean deleteServer(@PathParam("id") int id); - /** - * The reboot function allows for either a soft or hard reboot of a server. - *

- * Status Transition: - *

- * ACTIVE - REBOOT - ACTIVE (soft reboot) - *

- * ACTIVE - HARD_REBOOT - ACTIVE (hard reboot) - * - * @param rebootType - * With a soft reboot, the operating system is signaled to restart, which allows for a - * graceful shutdown of all processes. A hard reboot is the equivalent of power cycling - * the server. - */ - void rebootServer(int id, RebootType rebootType); + /** + * The reboot function allows for either a soft or hard reboot of a server. + *

+ * Status Transition: + *

+ * ACTIVE - REBOOT - ACTIVE (soft reboot) + *

+ * ACTIVE - HARD_REBOOT - ACTIVE (hard reboot) + * + * @param rebootType With a soft reboot, the operating system is signaled to restart, which allows for a + * graceful shutdown of all processes. A hard reboot is the equivalent of power cycling + * the server. + */ + void rebootServer(int id, RebootType rebootType); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly confirmed, at which time the - * original server is removed. All resizes are automatically confirmed after 24 hours if they are - * not confirmed or reverted. - *

- * Status Transition: - *

- * ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE - *

- * ACTIVE - QUEUE_RESIZE - ACTIVE (on error) - */ - void resizeServer(int id, int flavorId); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly confirmed, at which time the + * original server is removed. All resizes are automatically confirmed after 24 hours if they are + * not confirmed or reverted. + *

+ * Status Transition: + *

+ * ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE + *

+ * ACTIVE - QUEUE_RESIZE - ACTIVE (on error) + */ + void resizeServer(int id, int flavorId); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly confirmed, at which time the - * original server is removed. All resizes are automatically confirmed after 24 hours if they are - * not confirmed or reverted. - *

- * Status Transition: - *

- * VERIFY_RESIZE - ACTIVE - */ - void confirmResizeServer(int id); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly confirmed, at which time the + * original server is removed. All resizes are automatically confirmed after 24 hours if they are + * not confirmed or reverted. + *

+ * Status Transition: + *

+ * VERIFY_RESIZE - ACTIVE + */ + void confirmResizeServer(int id); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly reverted, at which time the - * original server is removed. All resizes are automatically reverted after 24 hours if they are - * not reverted or reverted. - *

- * Status Transition: - *

- * VERIFY_RESIZE - ACTIVE - */ - void revertResizeServer(int id); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly reverted, at which time the + * original server is removed. All resizes are automatically reverted after 24 hours if they are + * not reverted or reverted. + *

+ * Status Transition: + *

+ * VERIFY_RESIZE - ACTIVE + */ + void revertResizeServer(int id); - /** - * This operation asynchronously provisions a new server. The progress of this operation depends - * on several factors including location of the requested image, network i/o, host load, and the - * selected flavor. The progress of the request can be checked by performing a GET on /server/id, - * which will return a progress attribute (0-100% completion). A password will be randomly - * generated for you and returned in the response object. For security reasons, it will not be - * returned in subsequent GET calls against a given server ID. - * - * @param options - * - used to specify extra files, metadata, or ip parameters during server creation. - */ - Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); + /** + * This operation asynchronously provisions a new server. The progress of this operation depends + * on several factors including location of the requested image, network i/o, host load, and the + * selected flavor. The progress of the request can be checked by performing a GET on /server/id, + * which will return a progress attribute (0-100% completion). A password will be randomly + * generated for you and returned in the response object. For security reasons, it will not be + * returned in subsequent GET calls against a given server ID. + * + * @param options - used to specify extra files, metadata, or ip parameters during server creation. + */ + Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); - /** - * The rebuild function removes all data on the server and replaces it with the specified image. - * Server ID and IP addresses remain the same. - *

- * Status Transition: - *

- * ACTIVE - REBUILD - ACTIVE - *

- * ACTIVE - REBUILD - ERROR (on error) - *

- * - * @param options - * - imageId is an optional argument. If it is not specified, the server is rebuilt - * with the original imageId. - */ - void rebuildServer(int id, RebuildServerOptions... options); + /** + * The rebuild function removes all data on the server and replaces it with the specified image. + * Server ID and IP addresses remain the same. + *

+ * Status Transition: + *

+ * ACTIVE - REBUILD - ACTIVE + *

+ * ACTIVE - REBUILD - ERROR (on error) + *

+ * + * @param options - imageId is an optional argument. If it is not specified, the server is rebuilt + * with the original imageId. + */ + void rebuildServer(int id, RebuildServerOptions... options); - /** - * This operation allows you to change the administrative password. - *

- * Status Transition: ACTIVE - PASSWORD - ACTIVE - * - */ - void changeAdminPass(int id, String adminPass); + /** + * This operation allows you to change the administrative password. + *

+ * Status Transition: ACTIVE - PASSWORD - ACTIVE + */ + void changeAdminPass(int id, String adminPass); - /** - * This operation allows you to update the name of the server. This operation changes the name of - * the server in the OpenStack Nova system and does not change the server host name itself. - *

- * Status Transition: ACTIVE - PASSWORD - ACTIVE - * - */ - void renameServer(int id, String newName); + /** + * This operation allows you to update the name of the server. This operation changes the name of + * the server in the OpenStack Nova system and does not change the server host name itself. + *

+ * Status Transition: ACTIVE - PASSWORD - ACTIVE + */ + void renameServer(int id, String newName); - /** - * - * List available flavors (IDs and names only) - * - * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listFlavors(ListOptions... options); + /** + * List available flavors (IDs and names only) + *

+ * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listFlavors(ListOptions... options); - /** - * - * This operation returns details of the specified flavor. - * - * @return null, if the flavor is not found - * @see Flavor - */ - Flavor getFlavor(int id); + /** + * This operation returns details of the specified flavor. + * + * @return null, if the flavor is not found + * @see Flavor + */ + Flavor getFlavor(int id); - /** - * - * List available images (IDs and names only) - * - * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listImages(ListOptions... options); + /** + * List available images (IDs and names only) + *

+ * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listImages(ListOptions... options); - /** - * - * This operation returns details of the specified image. - * - * @return null, if the image is not found - * - * @see Image - */ - Image getImage(int id); + /** + * This operation returns details of the specified image. + * + * @return null, if the image is not found + * @see Image + */ + Image getImage(int id); - /** - * - * This operation deletes an image from the system. - *

- * Note: Images are immediately removed. Currently, there are no state transitions to track the - * delete operation. - * - * @return false if the image is not found - * @see Image - */ - boolean deleteImage(int id); + /** + * This operation deletes an image from the system. + *

+ * Note: Images are immediately removed. Currently, there are no state transitions to track the + * delete operation. + * + * @return false if the image is not found + * @see Image + */ + boolean deleteImage(int id); - /** - * - * This operation creates a new image for the given server ID. Once complete, a new image will be - * available that can be used to rebuild or create servers. Specifying the same image name as an - * existing custom image replaces the image. The image creation status can be queried by - * performing a GET on /images/id and examining the status and progress attributes. - * - * Status Transition: - *

- * QUEUED - PREPARING - SAVING - ACTIVE - *

- * QUEUED - PREPARING - SAVING - FAILED (on error) - *

- * Note: At present, image creation is an asynchronous operation, so coordinating the creation - * with data quiescence, etc. is currently not possible. - * - * @throws ResourceNotFoundException - * if the server is not found - * @see Image - */ - Image createImageFromServer(String imageName, int serverId); + /** + * This operation creates a new image for the given server ID. Once complete, a new image will be + * available that can be used to rebuild or create servers. Specifying the same image name as an + * existing custom image replaces the image. The image creation status can be queried by + * performing a GET on /images/id and examining the status and progress attributes. + *

+ * Status Transition: + *

+ * QUEUED - PREPARING - SAVING - ACTIVE + *

+ * QUEUED - PREPARING - SAVING - FAILED (on error) + *

+ * Note: At present, image creation is an asynchronous operation, so coordinating the creation + * with data quiescence, etc. is currently not possible. + * + * @throws ResourceNotFoundException if the server is not found + * @see Image + */ + Image createImageFromServer(String imageName, int serverId); - /** - * List all server addresses - * - * returns empty set if the server doesn't exist - */ - Addresses getAddresses(int serverId); + /** + * List all server addresses + *

+ * returns empty set if the server doesn't exist + */ + Addresses getAddresses(int serverId); - /** - * List all public server addresses - * - * returns empty set if the server doesn't exist - */ - Set listPublicAddresses(int serverId); + /** + * List all public server addresses + *

+ * returns empty set if the server doesn't exist + */ + Set listPublicAddresses(int serverId); - /** - * List all private server addresses - * - * returns empty set if the server doesn't exist - */ - Set listPrivateAddresses(int serverId); + /** + * List all private server addresses + *

+ * returns empty set if the server doesn't exist + */ + Set listPrivateAddresses(int serverId); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java index 0457299495..be8607a17d 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java @@ -18,224 +18,154 @@ */ package org.jclouds.openstack.nova.options; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Preconditions.checkState; - -import java.net.URI; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; import org.jclouds.encryption.internal.Base64; import org.jclouds.http.HttpRequest; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.rest.binders.BindToJsonPayload; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import static com.google.common.base.Preconditions.*; /** - * * @author Adrian Cole - * */ public class CreateServerOptions extends BindToJsonPayload { - static class File { - private final String path; - private final String contents; + static class File { + private final String path; + private final String contents; - public File(String path, byte[] contents) { - this.path = checkNotNull(path, "path"); - this.contents = Base64.encodeBytes(checkNotNull(contents, "contents")); - checkArgument(path.getBytes().length < 255, String.format( - "maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path - .getBytes().length)); - checkArgument(contents.length < 10 * 1024, String.format( - "maximum size of the file is 10KB. Contents specified is %d bytes", - contents.length)); - } + public File(String path, byte[] contents) { + this.path = checkNotNull(path, "path"); + this.contents = Base64.encodeBytes(checkNotNull(contents, "contents")); + checkArgument(path.getBytes().length < 255, String.format( + "maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path + .getBytes().length)); + checkArgument(contents.length < 10 * 1024, String.format( + "maximum size of the file is 10KB. Contents specified is %d bytes", + contents.length)); + } - public String getContents() { - return contents; - } + public String getContents() { + return contents; + } - public String getPath() { - return path; - } + public String getPath() { + return path; + } - } + } - @SuppressWarnings("unused") - private class ServerRequest { - final String name; - final String imageRef; - final String flavorRef; - Map metadata; - List personality; - Integer sharedIpGroupId; - Addresses addresses; + @SuppressWarnings("unused") + private class ServerRequest { + final String name; + final String imageRef; + final String flavorRef; + Map metadata; + List personality; + Addresses addresses; - private ServerRequest(String name, String imageRef, String flavorRef) { - this.name = name; - this.imageRef = imageRef; - this.flavorRef = flavorRef; - } + private ServerRequest(String name, String imageRef, String flavorRef) { + this.name = name; + this.imageRef = imageRef; + this.flavorRef = flavorRef; + } - } + } - private Map metadata = Maps.newHashMap(); - private List files = Lists.newArrayList(); - private Integer sharedIpGroupId; - private String publicIp; + private Map metadata = Maps.newHashMap(); + private List files = Lists.newArrayList(); + private String publicIp; - @Override - public R bindToRequest(R request, Map postParams) { - ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), - "name parameter not present"), checkNotNull(postParams - .get("imageRef"), "imageRef parameter not present"), checkNotNull( - postParams.get("flavorRef"), "flavorRef parameter not present")); - if (metadata.size() > 0) - server.metadata = metadata; - if (files.size() > 0) - server.personality = files; - if (sharedIpGroupId != null) - server.sharedIpGroupId = this.sharedIpGroupId; - if (publicIp != null) { - server.addresses = new Addresses(); - server.addresses.getPublicAddresses().add(publicIp); - server.addresses.setPrivateAddresses(null); - } - return bindToRequest(request, ImmutableMap.of("server", server)); - } + @Override + public R bindToRequest(R request, Map postParams) { + ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), + "name parameter not present"), checkNotNull(postParams + .get("imageRef"), "imageRef parameter not present"), checkNotNull( + postParams.get("flavorRef"), "flavorRef parameter not present")); + if (metadata.size() > 0) + server.metadata = metadata; + if (files.size() > 0) + server.personality = files; + if (publicIp != null) { + server.addresses = new Addresses(); + server.addresses.getPublicAddresses().add(publicIp); + server.addresses.setPrivateAddresses(null); + } + return bindToRequest(request, ImmutableMap.of("server", server)); + } - /** - * You may further customize a cloud server by injecting data into the file system of the cloud - * server itself. This is useful, for example, for inserting ssh keys, setting configuration - * files, or storing data that you want to retrieve from within the instance itself. It is - * intended to provide a minimal amount of launch-time personalization. If significant - * customization is required, a custom image should be created. The max size of the file path - * data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents - * should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the - * decoded data not the number of characters in the encoded data. The maximum number of file - * path/content pairs that can be supplied is 5. Any existing files that match the specified file - * will be renamed to include the extension bak followed by a time stamp. For example, the file - * /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and - * the root group as owner and group owner, respectively and will allow user and group read - * access only (-r--r-----). - */ - public CreateServerOptions withFile(String path, byte[] contents) { - checkState(files.size() < 5, "maximum number of files allowed is 5"); - files.add(new File(path, contents)); - return this; - } + /** + * You may further customize a cloud server by injecting data into the file system of the cloud + * server itself. This is useful, for example, for inserting ssh keys, setting configuration + * files, or storing data that you want to retrieve from within the instance itself. It is + * intended to provide a minimal amount of launch-time personalization. If significant + * customization is required, a custom image should be created. The max size of the file path + * data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents + * should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the + * decoded data not the number of characters in the encoded data. The maximum number of file + * path/content pairs that can be supplied is 5. Any existing files that match the specified file + * will be renamed to include the extension bak followed by a time stamp. For example, the file + * /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and + * the root group as owner and group owner, respectively and will allow user and group read + * access only (-r--r-----). + */ + public CreateServerOptions withFile(String path, byte[] contents) { + checkState(files.size() < 5, "maximum number of files allowed is 5"); + files.add(new File(path, contents)); + return this; + } - /** - * A shared IP group is a collection of servers that can share IPs with other members of the - * group. Any server in a group can share one or more public IPs with any other server in the - * group. With the exception of the first server in a shared IP group, servers must be launched - * into shared IP groups. A server may only be a member of one shared IP group. - * - *

- * Servers in the same shared IP group can share public IPs for various high availability and - * load balancing configurations. To launch an HA server, include the optional sharedIpGroupId - * element and the server will be launched into that shared IP group. - *

- * - * Note: sharedIpGroupId is an optional parameter and for optimal performance, should ONLY be - * specified when intending to share IPs between servers. - * - * @see #withSharedIp(String) - */ - public CreateServerOptions withSharedIpGroup(int id) { - checkArgument(id > 0, "id must be positive or zero. was: " + id); - this.sharedIpGroupId = id; - return this; - } - - /** - * Custom cloud server metadata can also be supplied at launch time. This metadata is stored in - * the API system where it is retrievable by querying the API for server status. The maximum size - * of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that - * can be supplied per server is 5. - */ - public CreateServerOptions withMetadata(Map metadata) { - checkNotNull(metadata, "metadata"); - checkArgument(metadata.size() <= 5, - "you cannot have more then 5 metadata values. You specified: " + metadata.size()); - for (Entry entry : metadata.entrySet()) { - checkArgument(entry.getKey().getBytes().length < 255, String.format( - "maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", - entry.getKey(), entry.getKey().getBytes().length)); - checkArgument( - entry.getKey().getBytes().length < 255, - String - .format( + /** + * Custom cloud server metadata can also be supplied at launch time. This metadata is stored in + * the API system where it is retrievable by querying the API for server status. The maximum size + * of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that + * can be supplied per server is 5. + */ + public CreateServerOptions withMetadata(Map metadata) { + checkNotNull(metadata, "metadata"); + checkArgument(metadata.size() <= 5, + "you cannot have more then 5 metadata values. You specified: " + metadata.size()); + for (Entry entry : metadata.entrySet()) { + checkArgument(entry.getKey().getBytes().length < 255, String.format( + "maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", + entry.getKey(), entry.getKey().getBytes().length)); + checkArgument( + entry.getKey().getBytes().length < 255, + String + .format( "maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length)); - } - this.metadata = metadata; - return this; - } + } + this.metadata = metadata; + return this; + } - /** - * Public IP addresses can be shared across multiple servers for use in various high availability - * scenarios. When an IP address is shared to another server, the cloud network restrictions are - * modified to allow each server to listen to and respond on that IP address (you may optionally - * specify that the target server network configuration be modified). Shared IP addresses can be - * used with many standard heartbeat facilities (e.g. keepalived) that monitor for failure and - * manage IP failover. - * - *

- * If you intend to use a shared IP on the server being created and have no need for a separate - * public IP address, you may launch the server into a shared IP group and specify an IP address - * from that shared IP group to be used as its public IP. You can accomplish this by specifying - * the public shared IP address in your request. This is optional and is only valid if - * sharedIpGroupId is also supplied. - */ - public CreateServerOptions withSharedIp(String publicIp) { - checkState(sharedIpGroupId != null, - "sharedIp is invalid unless a shared ip group is specified."); - this.publicIp = checkNotNull(publicIp, "ip"); - return this; - } - public static class Builder { + public static class Builder { - /** - * @see CreateServerOptions#withFile(String,byte []) - */ - public static CreateServerOptions withFile(String path, byte[] contents) { - CreateServerOptions options = new CreateServerOptions(); - return options.withFile(path, contents); - } + /** + * @see CreateServerOptions#withFile(String, byte[]) + */ + public static CreateServerOptions withFile(String path, byte[] contents) { + CreateServerOptions options = new CreateServerOptions(); + return options.withFile(path, contents); + } - /** - * @see CreateServerOptions#withSharedIpGroup(int) - */ - public static CreateServerOptions withSharedIpGroup(int id) { - CreateServerOptions options = new CreateServerOptions(); - return options.withSharedIpGroup(id); - } + /** + * @see CreateServerOptions#withMetadata(Map) + */ + public static CreateServerOptions withMetadata(Map metadata) { + CreateServerOptions options = new CreateServerOptions(); + return options.withMetadata(metadata); + } - /** - * @see CreateServerOptions#withMetadata(Map) - */ - public static CreateServerOptions withMetadata(Map metadata) { - CreateServerOptions options = new CreateServerOptions(); - return options.withMetadata(metadata); - } - - /** - * @see CreateServerOptions#withSharedIp(String) - */ - public static CreateServerOptions withSharedIp(String publicIp) { - CreateServerOptions options = new CreateServerOptions(); - return options.withSharedIp(publicIp); - } - - } + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptions.java deleted file mode 100644 index f84984a0f1..0000000000 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptions.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.options; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Map; - -import javax.annotation.Nullable; - -import org.jclouds.http.HttpRequest; -import org.jclouds.rest.binders.BindToJsonPayload; - -import com.google.common.collect.ImmutableMap; - -/** - * - * - * @author Adrian Cole - * - */ -public class CreateSharedIpGroupOptions extends BindToJsonPayload { - Integer serverId; - - @SuppressWarnings("unused") - private static class SharedIpGroupRequest { - final String name; - Integer server; - - private SharedIpGroupRequest(String name, @Nullable Integer serverId) { - this.name = name; - this.server = serverId; - } - - } - - @Override - public R bindToRequest(R request, Map postParams) { - SharedIpGroupRequest createRequest = new SharedIpGroupRequest(checkNotNull(postParams - .get("name")), serverId); - return super.bindToRequest(request, ImmutableMap.of("sharedIpGroup", createRequest)); - } - - @Override - public R bindToRequest(R request, Object toBind) { - throw new IllegalStateException("CreateSharedIpGroup is a POST operation"); - } - - /** - * - * @param id - * of the server to include with this request. - */ - public CreateSharedIpGroupOptions withServer(int id) { - checkArgument(id > 0, "server id must be a positive number"); - this.serverId = id; - return this; - } - - public static class Builder { - - /** - * @see CreateSharedIpGroupOptions#withServer(int) - */ - public static CreateSharedIpGroupOptions withServer(int id) { - CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions(); - return options.withServer(id); - } - } -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 2da320c57a..e015fca319 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -24,7 +24,6 @@ import com.google.inject.TypeLiteral; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.http.functions.ReleasePayloadAndReturn; -import org.jclouds.http.functions.ReturnFalseOn404; import org.jclouds.http.functions.ReturnTrueIf2xx; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.openstack.OpenStackAuthAsyncClient.AuthenticationResponse; @@ -34,14 +33,15 @@ import org.jclouds.openstack.filters.AuthenticateRequest; import org.jclouds.openstack.nova.config.NovaRestClientModule; import org.jclouds.openstack.nova.domain.RebootType; import org.jclouds.openstack.nova.options.CreateServerOptions; -import org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions; import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; -import org.jclouds.rest.functions.*; +import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -49,14 +49,13 @@ import javax.ws.rs.core.MediaType; import java.io.IOException; import java.lang.reflect.Method; import java.net.URI; -import java.net.UnknownHostException; import java.util.Date; import java.util.Properties; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.*; -import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; @@ -82,7 +81,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -104,7 +103,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals( request, - "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -125,7 +124,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals(request, - "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -507,7 +506,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false); + assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 07a07a0761..95eedde364 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -51,6 +51,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; @@ -73,11 +74,20 @@ public class NovaClientLiveTest { protected String endpoint; protected String apiversion; - private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { - if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) - properties.setProperty(propertyName, System.getProperty(propertyName)); - } + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } protected void setupCredentials(Properties properties) { identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); @@ -96,19 +106,6 @@ public class NovaClientLiveTest { properties.setProperty(provider + ".apiversion", apiversion); } - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; - } @BeforeGroups(groups = {"live"}) public void setupClient() throws IOException { @@ -268,7 +265,7 @@ public class NovaClientLiveTest { @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = "14362"; + String imageRef = "3"; String flavorRef = "1"; String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java new file mode 100644 index 0000000000..f91d323ceb --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java @@ -0,0 +1,20 @@ +package org.jclouds.openstack.nova; + +import java.util.Properties; + +/** + * Created by IntelliJ IDEA. + * User: VGalkin + * Date: 4/14/11 + * Time: 4:32 PM + * To change this template use File | Settings | File Templates. + */ +public class PropertyHelper { + + public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); + } + + +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index a5c750d3d4..3b0bf50534 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,59 +1,57 @@ package org.jclouds.openstack.nova; import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.RunNodesException; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; import java.util.Arrays; -import java.util.Collections; import java.util.Properties; import java.util.Set; import static org.jclouds.Constants.PROPERTY_ENDPOINT; public class _NovaClient { - static public void main(String[] args) { - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ - //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://172.18.34.40:8774/v1.0/images/detail?format=json + static public void main(String[] args) { + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ + //curl -v -H "X-Auth-Token: 00cf93fd62df48f9fdc35fa16a7662447e48c513" http://dragon004.hw.griddynamics.net:8774/v1.1/images/detail?format=json - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; - String endpoint = "http://dragon004.hw.griddynamics.net:8774"; + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + String endpoint = "http://dragon004.hw.griddynamics.net:8774"; - ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); + ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_ENDPOINT, endpoint); - ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, - Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_ENDPOINT, endpoint); + ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, + Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); - ComputeService cs = context.getComputeService(); + ComputeService cs = context.getComputeService(); - System.out.println(cs.listImages()); - System.out.println(cs.listHardwareProfiles()); - //System.out.println(cs.listNodes()); + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + //System.out.println(cs.listNodes()); - TemplateOptions options = new TemplateOptions(); - //options.authorizePublicKey(""); - Template template = cs.templateBuilder().imageId("13").options(options).build(); - try { - Set metedata = cs.runNodesWithTag("test", 1, template); - System.out.println(metedata); - } catch (RunNodesException e) { - e.printStackTrace(); - } + TemplateOptions options = new TemplateOptions(); + //options.authorizePublicKey(""); + Template template = cs.templateBuilder().imageId("3").options(options).build(); + try { + Set metedata = cs.runNodesWithTag("test", 1, template); + System.out.println(metedata); + } catch (RunNodesException e) { + e.printStackTrace(); + } - //System.out.println(cs.listNodes()); - //System.out.println(cs.listImages()); - //System.out.println(cs.listNodes()); - //System.out.println(cs.listAssignableLocations()); - //System.out.println(cs.listHardwareProfiles()); - } + //System.out.println(cs.listNodes()); + //System.out.println(cs.listImages()); + //System.out.println(cs.listNodes()); + //System.out.println(cs.listAssignableLocations()); + //System.out.println(cs.listHardwareProfiles()); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java index ded18d8dd6..3cd440e25b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java @@ -74,6 +74,7 @@ import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCreden import static org.jclouds.compute.predicates.NodePredicates.*; import static org.jclouds.compute.predicates.NodePredicates.all; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -108,11 +109,6 @@ public class NovaComputeServiceLiveTest { } - private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { - if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) - properties.setProperty(propertyName, System.getProperty(propertyName)); - } - protected void setupCredentials(Properties properties) { identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider @@ -131,13 +127,10 @@ public class NovaComputeServiceLiveTest { } - protected Properties setupProperties() { + protected Properties setupProperties() throws IOException { Properties overrides = new Properties(); - try { - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - } catch (IOException e) { - throw new RuntimeException("Can't load properties"); - } + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java new file mode 100644 index 0000000000..781e62e2db --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java @@ -0,0 +1,150 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova.functions; + +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpCommand; +import org.jclouds.http.HttpRequest; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.handlers.ParseNovaErrorFromHttpResponse; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + +/** + * Tests behavior of {@code ParseServerListFromJsonResponse} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ParseFaultFromJsonResponseTest { + + Injector i = Guice.createInjector(new GsonModule()); + + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); + + + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + //List response = parser.apply(new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); + new ParseNovaErrorFromHttpResponse().handleError(createHttpCommand(), new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); + + //assertEquals(response, expects); + } + + @Test + public void testHandler() { + //InputStream is = getClass().getResourceAsStream("/test_error_handler.json"); + +// +// +// NovaErrorHandler handler = Guice.createInjector(new GsonModule()).getInstance(GoGridErrorHandler.class); +// +// HttpCommand command = createHttpCommand(); +// handler.handleError(command, new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); +// +// Exception createdException = command.getException(); +// +// assertNotNull(createdException, "There should've been an exception generated"); +// String message = createdException.getMessage(); +// assertTrue(message.contains("No object found that matches your input criteria."), +// "Didn't find the expected error cause in the exception message"); +// assertTrue(message.contains("IllegalArgumentException"), +// "Didn't find the expected error code in the exception message"); +// +// // make sure the InputStream is closed +// try { +// is.available(); +// throw new TestException("Stream wasn't closed by the GoGridErrorHandler when it should've"); +// } catch (IOException e) { +// // this is the excepted output +// } + } + + HttpCommand createHttpCommand() { + return new HttpCommand() { + private Exception exception; + + @Override + public int incrementRedirectCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getRedirectCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean isReplayable() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int incrementFailureCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getFailureCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public HttpRequest getCurrentRequest() { + try { + return new HttpRequest("method", new URI("http://endpoint")); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + @Override + public void setCurrentRequest(HttpRequest request) { + //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public void setException(Exception exception) { + this.exception = exception; + } + + @Override + public Exception getException() { + return exception; + } + }; + } + + +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java index c01d973e7d..c3783bf992 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java @@ -18,123 +18,66 @@ */ package org.jclouds.openstack.nova.options; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIp; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withSharedIpGroup; -import static org.testng.Assert.assertEquals; - -import java.net.URI; - -import javax.ws.rs.HttpMethod; - +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; import org.jclouds.http.HttpRequest; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Guice; -import com.google.inject.Injector; +import javax.ws.rs.HttpMethod; +import java.net.URI; + +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class CreateServerOptionsTest { - Injector injector = Guice.createInjector(new GsonModule()); + Injector injector = Guice.createInjector(new GsonModule()); - @Test - public void testAddPayloadToRequestMapOfStringStringHttpRequest() { - CreateServerOptions options = new CreateServerOptions(); - HttpRequest request = buildRequest(options); - assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent()); - } + @Test + public void testAddPayloadToRequestMapOfStringStringHttpRequest() { + CreateServerOptions options = new CreateServerOptions(); + HttpRequest request = buildRequest(options); + assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2}}", request.getPayload().getRawContent()); + } - private HttpRequest buildRequest(CreateServerOptions options) { - injector.injectMembers(options); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", "2")); - return request; - } + private HttpRequest buildRequest(CreateServerOptions options) { + injector.injectMembers(options); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2")); + return request; + } - @Test - public void testWithFile() { - CreateServerOptions options = new CreateServerOptions(); - options.withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFile() { + CreateServerOptions options = new CreateServerOptions(); + options.withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - @Test - public void testWithFileStatic() { - CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFileStatic() { + CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - private void assertFile(HttpRequest request) { - assertEquals( - "{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}", - request.getPayload().getRawContent()); - } + private void assertFile(HttpRequest request) { + assertEquals(request.getPayload().getRawContent(), + "{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); + } - @Test - public void testWithSharedIpGroup() { - CreateServerOptions options = new CreateServerOptions(); - options.withSharedIpGroup(3); - HttpRequest request = buildRequest(options); - assertSharedIpGroup(request); - } + @Test + public void testWithMetadata() { + } - @Test - public void testWithSharedIpGroupStatic() { - CreateServerOptions options = withSharedIpGroup(3); - HttpRequest request = buildRequest(options); - assertSharedIpGroup(request); - } - private void assertSharedIpGroup(HttpRequest request) { - assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3}}", request - .getPayload().getRawContent()); - } - - @Test - public void testWithMetadata() { - } - - @Test - public void testWithSharedIp() { - CreateServerOptions options = new CreateServerOptions(); - options.withSharedIpGroup(3).withSharedIp("127.0.0.1"); - HttpRequest request = buildRequest(options); - assertSharedIp(request); - } - - @Test - public void testWithSharedIpStatic() { - CreateServerOptions options = withSharedIpGroup(3).withSharedIp("127.0.0.1"); - HttpRequest request = buildRequest(options); - assertSharedIp(request); - } - - private void assertSharedIp(HttpRequest request) { - assertEquals( - "{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"sharedIpGroupId\":3,\"addresses\":{\"public\":[\"127.0.0.1\"]}}}", - request.getPayload().getRawContent()); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testWithSharedIpNoGroup() { - CreateServerOptions options = new CreateServerOptions(); - options.withSharedIp("127.0.0.1"); - buildRequest(options); - } - - @Test(expectedExceptions = IllegalStateException.class) - public void testWithSharedIpNoGroupStatic() { - CreateServerOptions options = withSharedIp("127.0.0.1"); - buildRequest(options); - } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptionsTest.java deleted file mode 100644 index bb1df92fd8..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateSharedIpGroupOptionsTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.options; - -import static org.jclouds.openstack.nova.options.CreateSharedIpGroupOptions.Builder.withServer; -import static org.testng.Assert.assertEquals; - -import java.net.URI; - -import javax.ws.rs.HttpMethod; - -import org.jclouds.http.HttpRequest; -import org.jclouds.json.config.GsonModule; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.Guice; -import com.google.inject.Injector; - -/** - * Tests behavior of {@code ParseFlavorFromJsonResponse} - * - * @author Adrian Cole - */ -@Test(groups = "unit") -public class CreateSharedIpGroupOptionsTest { - - Injector injector = Guice.createInjector(new GsonModule()); - - @Test - public void testAddPayloadToRequestMapOfStringStringHttpRequest() { - CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions(); - HttpRequest request = buildRequest(options); - assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\"}}", request.getPayload().getRawContent()); - } - - private HttpRequest buildRequest(CreateSharedIpGroupOptions options) { - injector.injectMembers(options); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - options.bindToRequest(request, ImmutableMap.of("name", "foo")); - return request; - } - - @Test - public void testWithServer() { - CreateSharedIpGroupOptions options = new CreateSharedIpGroupOptions(); - options.withServer(3); - HttpRequest request = buildRequest(options); - assertSharedIpGroup(request); - } - - @Test - public void testWithServerStatic() { - CreateSharedIpGroupOptions options = withServer(3); - HttpRequest request = buildRequest(options); - assertSharedIpGroup(request); - } - - private void assertSharedIpGroup(HttpRequest request) { - assertEquals("{\"sharedIpGroup\":{\"name\":\"foo\",\"server\":3}}", request.getPayload().getRawContent()); - } - -} diff --git a/sandbox-apis/nova/src/test/resources/test_fault_response413.json b/sandbox-apis/nova/src/test/resources/test_fault_response413.json new file mode 100644 index 0000000000..093cb11ded --- /dev/null +++ b/sandbox-apis/nova/src/test/resources/test_fault_response413.json @@ -0,0 +1,9 @@ +{ + "overLimit" : { + "code" : 413, + "message" : "OverLimit Retry...", + "details" : "Error Details...", + "retryAt" : "2010-08-01T00:00:00Z" + } +} + From eb4dedca622099db18d4a4c961b0853e4ae34e54 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Thu, 14 Apr 2011 23:48:29 +0400 Subject: [PATCH 22/95] slf4j + logback is used for logging in tests numeric IDs instead of URIs in requests --- sandbox-apis/nova/pom.xml | 23 ++- ...ovaCreateNodeWithGroupEncodedIntoName.java | 3 +- .../openstack/nova/NovaClientLiveTest.java | 37 ++-- .../jclouds/openstack/nova/_NovaClient.java | 62 +++--- .../compute/NovaComputeServiceLiveTest.java | 21 +- .../nova/src/test/resources/log4j.xml | 185 ------------------ .../nova/src/test/resources/logback.xml | 15 ++ 7 files changed, 95 insertions(+), 251 deletions(-) delete mode 100755 sandbox-apis/nova/src/test/resources/log4j.xml create mode 100644 sandbox-apis/nova/src/test/resources/logback.xml diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 0ae2dce73f..87277cdb65 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -79,18 +79,25 @@ com.jcraft jsch - test - - - org.jclouds.driver - jclouds-log4j ${project.version} test - log4j - log4j - 1.2.16 + org.jclouds.driver + jclouds-slf4j + ${project.version} + test + + + slf4j-api + org.slf4j + 1.6.1 + test + + + ch.qos.logback + logback-classic + 0.9.28 test diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java index 5769efad8e..5cb3b1fa5a 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/strategy/NovaCreateNodeWithGroupEncodedIntoName.java @@ -53,8 +53,7 @@ public class NovaCreateNodeWithGroupEncodedIntoName implements CreateNodeWithGro @Override public NodeMetadata createNodeWithGroupEncodedIntoName(String group, String name, Template template) { - Server from = client.createServer(name, template.getImage().getUri().toString(), - template.getHardware().getUri().toString()); + Server from = client.createServer(name, template.getImage().getId(), template.getHardware().getId()); credentialStore.put("node#" + from.getId(), new Credentials("root", from.getAdminPass())); return serverToNodeMetadata.apply(from); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 95eedde364..d6dc8eaf9e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -29,7 +29,7 @@ import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.RebuildServerOptions; @@ -51,7 +51,6 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; @@ -74,21 +73,12 @@ public class NovaClientLiveTest { protected String endpoint; protected String apiversion; - - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; + private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); } + protected void setupCredentials(Properties properties) { identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider @@ -106,6 +96,19 @@ public class NovaClientLiveTest { properties.setProperty(provider + ".apiversion", apiversion); } + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } @BeforeGroups(groups = {"live"}) public void setupClient() throws IOException { @@ -119,7 +122,7 @@ public class NovaClientLiveTest { // ComputeServiceContext context = contextFactory.createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides); Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, - ImmutableSet.of(new Log4JLoggingModule(), new JschSshClientModule()), overrides) + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) .buildInjector(); client = injector.getInstance(NovaClient.class); @@ -265,7 +268,7 @@ public class NovaClientLiveTest { @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = "3"; + String imageRef = "14362"; String flavorRef = "1"; String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index 3b0bf50534..f2c06719a2 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,57 +1,55 @@ package org.jclouds.openstack.nova; import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.RunNodesException; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; import java.util.Arrays; +import java.util.Collections; import java.util.Properties; import java.util.Set; import static org.jclouds.Constants.PROPERTY_ENDPOINT; public class _NovaClient { - static public void main(String[] args) { - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://172.18.34.40:8774/v1.0/ - //curl -v -H "X-Auth-Token: 00cf93fd62df48f9fdc35fa16a7662447e48c513" http://dragon004.hw.griddynamics.net:8774/v1.1/images/detail?format=json + static public void main(String[] args) { + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; - String endpoint = "http://dragon004.hw.griddynamics.net:8774"; + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + String endpoint = "http://dragon004.hw.griddynamics.net:8774"; - ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); + ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_ENDPOINT, endpoint); - ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, - Arrays.asList(new JschSshClientModule(), new Log4JLoggingModule()), overrides); + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_ENDPOINT, endpoint); + ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, + Arrays.asList(new JschSshClientModule(), new SLF4JLoggingModule()), overrides); - ComputeService cs = context.getComputeService(); + ComputeService cs = context.getComputeService(); - System.out.println(cs.listImages()); - System.out.println(cs.listHardwareProfiles()); - //System.out.println(cs.listNodes()); + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + System.out.println(cs.listAssignableLocations()); + System.out.println(cs.listNodes()); - TemplateOptions options = new TemplateOptions(); - //options.authorizePublicKey(""); - Template template = cs.templateBuilder().imageId("3").options(options).build(); - try { - Set metedata = cs.runNodesWithTag("test", 1, template); - System.out.println(metedata); - } catch (RunNodesException e) { - e.printStackTrace(); - } + TemplateOptions options = new TemplateOptions(); + Template template = cs.templateBuilder().imageId("13").options(options).build(); + try { + Set metedata = cs.runNodesWithTag("test", 1, template); + System.out.println(metedata); + } catch (RunNodesException e) { + e.printStackTrace(); + } - //System.out.println(cs.listNodes()); - //System.out.println(cs.listImages()); - //System.out.println(cs.listNodes()); - //System.out.println(cs.listAssignableLocations()); - //System.out.println(cs.listHardwareProfiles()); - } + context.close(); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java index 3cd440e25b..cdec9d9a68 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java @@ -34,7 +34,7 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; -import org.jclouds.logging.log4j.config.Log4JLoggingModule; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaAsyncClient; import org.jclouds.openstack.nova.NovaClient; @@ -74,7 +74,6 @@ import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCreden import static org.jclouds.compute.predicates.NodePredicates.*; import static org.jclouds.compute.predicates.NodePredicates.all; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -109,6 +108,11 @@ public class NovaComputeServiceLiveTest { } + private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); + } + protected void setupCredentials(Properties properties) { identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider @@ -127,10 +131,13 @@ public class NovaComputeServiceLiveTest { } - protected Properties setupProperties() throws IOException { + protected Properties setupProperties() { Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - + try { + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + } catch (IOException e) { + throw new RuntimeException("Can't load properties"); + } overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); @@ -152,7 +159,7 @@ public class NovaComputeServiceLiveTest { if (context != null) context.close(); context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( - new Log4JLoggingModule(), getSshModule()), properties); + new SLF4JLoggingModule(), getSshModule()), properties); client = context.getComputeService(); } @@ -227,7 +234,7 @@ public class NovaComputeServiceLiveTest { ComputeServiceContext context = null; try { context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet - .of(new Log4JLoggingModule()), overrides); + .of(new SLF4JLoggingModule()), overrides); context.getComputeService().listNodes(); } catch (AuthorizationException e) { throw e; diff --git a/sandbox-apis/nova/src/test/resources/log4j.xml b/sandbox-apis/nova/src/test/resources/log4j.xml deleted file mode 100755 index 5b548a0f48..0000000000 --- a/sandbox-apis/nova/src/test/resources/log4j.xml +++ /dev/null @@ -1,185 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/sandbox-apis/nova/src/test/resources/logback.xml b/sandbox-apis/nova/src/test/resources/logback.xml new file mode 100644 index 0000000000..5c9c501b0c --- /dev/null +++ b/sandbox-apis/nova/src/test/resources/logback.xml @@ -0,0 +1,15 @@ + + + + + %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n + + + + + + + + + + \ No newline at end of file From b17b860279d11aedecf2d0883b55869e3c9937af Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 15 Apr 2011 16:30:13 +0400 Subject: [PATCH 23/95] Changed Addresses and Server domain objects do deserialize current nova response. Updated tests. --- .../functions/ServerToNodeMetadata.java | 187 +++++----- .../openstack/nova/domain/Addresses.java | 146 ++++---- .../jclouds/openstack/nova/domain/Server.java | 319 ++++++++++-------- .../openstack/nova/NovaClientLiveTest.java | 31 +- .../functions/ServerToNodeMetadataTest.java | 185 +++++----- .../ParseServerFromJsonResponseTest.java | 20 +- .../ParseServerListFromJsonResponseTest.java | 10 +- 7 files changed, 460 insertions(+), 438 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java index 2a574e7a40..8d16f9e6ad 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java @@ -18,126 +18,119 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; - -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; import org.jclouds.collect.Memoized; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.*; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.logging.Logger; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; /** * @author Adrian Cole */ @Singleton public class ServerToNodeMetadata implements Function { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - protected final Supplier location; - protected final Map credentialStore; - protected final Map serverToNodeState; - protected final Supplier> images; - protected final Supplier> hardwares; + protected final Supplier location; + protected final Map credentialStore; + protected final Map serverToNodeState; + protected final Supplier> images; + protected final Supplier> hardwares; - private static class FindImageForServer implements Predicate { - private final Server instance; + private static class FindImageForServer implements Predicate { + private final Server instance; - private FindImageForServer(Server instance) { - this.instance = instance; - } + private FindImageForServer(Server instance) { + this.instance = instance; + } - @Override - public boolean apply(Image input) { - return input.getProviderId().equals(instance.getImageId() + ""); - } - } + @Override + public boolean apply(Image input) { + return input.getProviderId().equals(instance.getImageRef() + ""); + } + } - private static class FindHardwareForServer implements Predicate { - private final Server instance; + private static class FindHardwareForServer implements Predicate { + private final Server instance; - private FindHardwareForServer(Server instance) { - this.instance = instance; - } + private FindHardwareForServer(Server instance) { + this.instance = instance; + } - @Override - public boolean apply(Hardware input) { - return input.getProviderId().equals(instance.getFlavorId() + ""); - } - } + @Override + public boolean apply(Hardware input) { + return input.getProviderId().equals(instance.getFlavorRef() + ""); + } + } - @Inject - ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, - @Memoized Supplier> images, Supplier location, - @Memoized Supplier> hardwares) { - this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); - this.images = checkNotNull(images, "images"); - this.location = checkNotNull(location, "location"); - this.hardwares = checkNotNull(hardwares, "hardwares"); - } + @Inject + ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, + @Memoized Supplier> images, Supplier location, + @Memoized Supplier> hardwares) { + this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); + this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + this.images = checkNotNull(images, "images"); + this.location = checkNotNull(location, "location"); + this.hardwares = checkNotNull(hardwares, "hardwares"); + } - @Override - public NodeMetadata apply(Server from) { - NodeMetadataBuilder builder = new NodeMetadataBuilder(); - builder.ids(from.getId() + ""); - builder.name(from.getName()); - builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description( - from.getHostId()).parent(location.get()).build()); - builder.userMetadata(from.getMetadata()); - builder.group(parseGroupFromName(from.getName())); - builder.imageId(from.getImageId() + ""); - builder.operatingSystem(parseOperatingSystem(from)); - builder.hardware(parseHardware(from)); - builder.state(serverToNodeState.get(from.getStatus())); - builder.publicAddresses(from.getAddresses().getPublicAddresses()); - builder.privateAddresses(from.getAddresses().getPrivateAddresses()); - builder.credentials(credentialStore.get("node#" + from.getId())); - builder.uri(from.getURI()); - return builder.build(); - } + @Override + public NodeMetadata apply(Server from) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + builder.ids(from.getId() + ""); + builder.name(from.getName()); + builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description( + from.getHostId()).parent(location.get()).build()); + builder.userMetadata(from.getMetadata()); + builder.group(parseGroupFromName(from.getName())); + builder.imageId(from.getImageRef() + ""); + builder.operatingSystem(parseOperatingSystem(from)); + builder.hardware(parseHardware(from)); + builder.state(serverToNodeState.get(from.getStatus())); + builder.publicAddresses(from.getAddresses().getPublicAddresses()); + builder.privateAddresses(from.getAddresses().getPrivateAddresses()); + builder.credentials(credentialStore.get("node#" + from.getId())); + builder.uri(from.getURI()); + return builder.build(); + } - protected Hardware parseHardware(Server from) { - try { - return Iterables.find(hardwares.get(), new FindHardwareForServer(from)); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching hardware for server %s", from); - } - return null; - } + protected Hardware parseHardware(Server from) { + try { + return Iterables.find(hardwares.get(), new FindHardwareForServer(from)); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching hardware for server %s", from); + } + return null; + } - protected OperatingSystem parseOperatingSystem(Server from) { - try { - return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching image for server %s in location %s", from, location); - } - return null; - } + protected OperatingSystem parseOperatingSystem(Server from) { + try { + return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching image for server %s in location %s", from, location); + } + return null; + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java index 02cdc9f6e0..cd93bdc272 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java @@ -18,81 +18,113 @@ */ package org.jclouds.openstack.nova.domain; -import java.util.Set; - import com.google.common.collect.Sets; import com.google.gson.annotations.SerializedName; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + /** - * * @author Adrian Cole */ public class Addresses { - @SerializedName("public") - private Set publicAddresses = Sets.newLinkedHashSet(); - @SerializedName("private") - private Set privateAddresses = Sets.newLinkedHashSet(); + @SerializedName("public") + private Set> publicAddresses = Sets.newHashSet(); + @SerializedName("private") + private Set> privateAddresses = Sets.newHashSet(); - public Addresses() { - } + public Addresses() { + } - public Addresses(Set publicAddresses, Set privateAddresses) { - this.publicAddresses = publicAddresses; - this.privateAddresses = privateAddresses; - } +// public Addresses(Set> publicAddresses, Set> privateAddresses) { +// this.publicAddresses = publicAddresses; +// this.privateAddresses = privateAddresses; +// } - public void setPublicAddresses(Set publicAddresses) { - this.publicAddresses = publicAddresses; - } + public Addresses(Set publicAddresses, Set privateAddresses) { + this.publicAddresses.clear(); + this.privateAddresses.clear(); + for (String address : publicAddresses) { + HashMap addressMap = new HashMap(); + addressMap.put("version", "4"); + addressMap.put("addr", "address"); + this.publicAddresses.add(addressMap); + } + for (String address : privateAddresses) { + HashMap addressMap = new HashMap(); + addressMap.put("version", "4"); + addressMap.put("addr", "address"); + this.privateAddresses.add(addressMap); + } - public Set getPublicAddresses() { - return publicAddresses; - } + } - public void setPrivateAddresses(Set privateAddresses) { - this.privateAddresses = privateAddresses; - } + public void setPublicAddresses(Set> publicAddresses) { + this.publicAddresses = publicAddresses; + } - public Set getPrivateAddresses() { - return privateAddresses; - } + public Set getPublicAddresses() { + HashSet addresses = new HashSet(); + for (Map address : publicAddresses) { + if (address.containsKey("addr")) { + addresses.add(address.get("addr")); + } + } + return addresses; + } - @Override - public String toString() { - return "Addresses [privateAddresses=" + privateAddresses + ", publicAddresses=" - + publicAddresses + "]"; - } + public void setPrivateAddresses(Set> privateAddresses) { + this.privateAddresses = privateAddresses; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode()); - result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode()); - return result; - } + public Set getPrivateAddresses() { + HashSet addresses = new HashSet(); + for (Map address : privateAddresses) { + if (address.containsKey("addr")) { + addresses.add(address.get("addr")); + } + } + return addresses; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Addresses other = (Addresses) obj; - if (privateAddresses == null) { - if (other.privateAddresses != null) + @Override + public String toString() { + return "Addresses [privateAddresses=" + privateAddresses + ", publicAddresses=" + + publicAddresses + "]"; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode()); + result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) return false; - } else if (!privateAddresses.equals(other.privateAddresses)) - return false; - if (publicAddresses == null) { - if (other.publicAddresses != null) + if (getClass() != obj.getClass()) return false; - } else if (!publicAddresses.equals(other.publicAddresses)) - return false; - return true; - } + Addresses other = (Addresses) obj; + if (privateAddresses == null) { + if (other.privateAddresses != null) + return false; + } else if (!privateAddresses.equals(other.privateAddresses)) + return false; + if (publicAddresses == null) { + if (other.publicAddresses != null) + return false; + } else if (!publicAddresses.equals(other.publicAddresses)) + return false; + return true; + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java index 9ebdba385f..ca1d902f3f 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java @@ -18,196 +18,217 @@ */ package org.jclouds.openstack.nova.domain; -import java.util.Map; - import com.google.common.collect.Maps; +import java.util.Map; + /** * A server is a virtual machine instance in the OpenStack Nova system. Flavor and image are * requisite elements when creating a server. - * + * * @author Adrian Cole */ public class Server extends Resource { - private int id; - private String name; + private int id; + private String name; - private Map metadata = Maps.newHashMap(); +// private Map> metadata = Maps.newHashMap(); - private Addresses addresses; - private String adminPass; - private Integer flavorId; - private String hostId; - private Integer imageId; + public Map getMetadata() { + return metadata; + } - private Integer progress; - private ServerStatus status; + public void setMetadata(Map metadata) { + this.metadata = metadata; + } - public Server() { - } + private Map metadata = Maps.newHashMap(); - public Server(int id, String name) { - this.id = id; - this.name = name; - } + private Addresses addresses; - public void setMetadata(Map metadata) { - this.metadata = metadata; - } + private String adminPass; + private String flavorRef; + private String hostId; + private String imageRef; - public Map getMetadata() { - return metadata; - } + public String getAffinityId() { + return affinityId; + } - public void setAddresses(Addresses addresses) { - this.addresses = addresses; - } + public void setAffinityId(String affinityId) { + this.affinityId = affinityId; + } - public Addresses getAddresses() { - return addresses; - } + private String affinityId; - public void setAdminPass(String adminPass) { - this.adminPass = adminPass; - } + private Integer progress; + private ServerStatus status; - public String getAdminPass() { - return adminPass; - } + public Server() { + } - public void setFlavorId(Integer flavorId) { - this.flavorId = flavorId; - } + public Server(int id, String name) { + this.id = id; + this.name = name; + } - public Integer getFlavorId() { - return flavorId; - } +// public void setMetadata(Map metadata) { +// this.metadata.put("values", metadata); +// } - public void setHostId(String hostId) { - this.hostId = hostId; - } +// public Map getMetadata() { +// return metadata.get("values"); +// } - /** - * The OpenStack Nova provisioning algorithm has an anti-affinity property that attempts to spread - * out customer VMs across hosts. Under certain situations, VMs from the same customer may be - * placed on the same host. hostId represents the host your cloud server runs on and can be used - * to determine this scenario if it's relevant to your application. - *

- * Note: hostId is unique PER ACCOUNT and is not globally unique. - */ - public String getHostId() { - return hostId; - } + public void setAddresses(Addresses addresses) { + this.addresses = addresses; + } - public int getId() { - return id; - } + public Addresses getAddresses() { + return addresses; + } - public void setImageId(Integer imageId) { - this.imageId = imageId; - } + public void setAdminPass(String adminPass) { + this.adminPass = adminPass; + } - public Integer getImageId() { - return imageId; - } + public String getAdminPass() { + return adminPass; + } - public String getName() { - return name; - } + public void setFlavorRef(String flavorRef) { + this.flavorRef = flavorRef; + } - public void setProgress(Integer progress) { - this.progress = progress; - } + public String getFlavorRef() { + return flavorRef; + } - public Integer getProgress() { - return progress; - } + public void setHostId(String hostId) { + this.hostId = hostId; + } - public void setStatus(ServerStatus status) { - this.status = status; - } + /** + * The OpenStack Nova provisioning algorithm has an anti-affinity property that attempts to spread + * out customer VMs across hosts. Under certain situations, VMs from the same customer may be + * placed on the same host. hostId represents the host your cloud server runs on and can be used + * to determine this scenario if it's relevant to your application. + *

+ * Note: hostId is unique PER ACCOUNT and is not globally unique. + */ + public String getHostId() { + return hostId; + } - /** - * Servers contain a status attribute that can be used as an indication of the current server - * state. Servers with an ACTIVE status are available for use. - */ - public ServerStatus getStatus() { - return status; - } + public int getId() { + return id; + } - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((addresses == null) ? 0 : addresses.hashCode()); - result = prime * result + ((adminPass == null) ? 0 : adminPass.hashCode()); - result = prime * result + ((flavorId == null) ? 0 : flavorId.hashCode()); - result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); - result = prime * result + id; - result = prime * result + ((imageId == null) ? 0 : imageId.hashCode()); - result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } + public void getImageRef(String imageRef) { + this.imageRef = imageRef; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Server other = (Server) obj; - if (addresses == null) { - if (other.addresses != null) + public String getImageRef() { + return imageRef; + } + + public String getName() { + return name; + } + + public void setProgress(Integer progress) { + this.progress = progress; + } + + public Integer getProgress() { + return progress; + } + + public void setStatus(ServerStatus status) { + this.status = status; + } + + /** + * Servers contain a status attribute that can be used as an indication of the current server + * state. Servers with an ACTIVE status are available for use. + */ + public ServerStatus getStatus() { + return status; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((addresses == null) ? 0 : addresses.hashCode()); + result = prime * result + ((adminPass == null) ? 0 : adminPass.hashCode()); + result = prime * result + ((flavorRef == null) ? 0 : flavorRef.hashCode()); + result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); + result = prime * result + id; + result = prime * result + ((imageRef == null) ? 0 : imageRef.hashCode()); + result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) return false; - } else if (!addresses.equals(other.addresses)) - return false; - if (adminPass == null) { - if (other.adminPass != null) + if (getClass() != obj.getClass()) return false; - } else if (!adminPass.equals(other.adminPass)) - return false; - if (flavorId == null) { - if (other.flavorId != null) + Server other = (Server) obj; + if (addresses == null) { + if (other.addresses != null) + return false; + } else if (!addresses.equals(other.addresses)) return false; - } else if (!flavorId.equals(other.flavorId)) - return false; - if (hostId == null) { - if (other.hostId != null) + if (adminPass == null) { + if (other.adminPass != null) + return false; + } else if (!adminPass.equals(other.adminPass)) return false; - } else if (!hostId.equals(other.hostId)) - return false; - if (id != other.id) - return false; - if (imageId == null) { - if (other.imageId != null) + if (flavorRef == null) { + if (other.flavorRef != null) + return false; + } else if (!flavorRef.equals(other.flavorRef)) return false; - } else if (!imageId.equals(other.imageId)) - return false; - if (metadata == null) { - if (other.metadata != null) + if (hostId == null) { + if (other.hostId != null) + return false; + } else if (!hostId.equals(other.hostId)) return false; - } else if (!metadata.equals(other.metadata)) - return false; - if (name == null) { - if (other.name != null) + if (id != other.id) return false; - } else if (!name.equals(other.name)) - return false; - return true; - } + if (imageRef == null) { + if (other.imageRef != null) + return false; + } else if (!imageRef.equals(other.imageRef)) + return false; + if (metadata == null) { + if (other.metadata != null) + return false; + } else if (!metadata.equals(other.metadata)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + return true; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Override - public String toString() { - return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorId=" - + flavorId + ", hostId=" + hostId + ", id=" + id + ", imageId=" + imageId - + ", metadata=" + metadata + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorRef=" + + flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef + + ", metadata=" + metadata + ", name=" + name + "]"; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index d6dc8eaf9e..ba1d6b4777 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -275,11 +275,11 @@ public class NovaClientLiveTest { "rackspace".getBytes()).withMetadata(metadata)); assertNotNull(server.getAdminPass()); + assertEquals(server.getStatus(), ServerStatus.BUILD); serverId = server.getId(); adminPass = server.getAdminPass(); - ip = server.getAddresses().getPublicAddresses().iterator().next(); - assertEquals(server.getStatus(), ServerStatus.BUILD); blockUntilServerActive(serverId); + ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next(); } private void blockUntilServerActive(int serverId) throws InterruptedException { @@ -316,8 +316,8 @@ public class NovaClientLiveTest { assertNotNull(server.getHostId()); assertEquals(server.getStatus(), ServerStatus.ACTIVE); assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals(new Integer(14362), server.getImageId()); - assertEquals(new Integer(1), server.getFlavorId()); + assertEquals("14362", server.getImageRef()); + assertEquals("1", server.getFlavorRef()); assertNotNull(server.getAddresses()); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); @@ -328,21 +328,12 @@ public class NovaClientLiveTest { // check metadata assertEquals(server.getMetadata(), metadata); - - checkPassOk(server, adminPass); - } - - /** - * this tests "personality" as the file looked up was sent during server creation - */ - - private void checkPassOk(Server newDetails, String pass) throws IOException { - doCheckPass(newDetails, pass); + assertPassword(server, adminPass); } - private void doCheckPass(Server newDetails, String pass) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0), 22); + private void assertPassword(Server server, String pass) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0), 22); socketTester.apply(socket); SshClient client = sshFactory.create(socket, new Credentials("root", pass)); @@ -383,7 +374,7 @@ public class NovaClientLiveTest { public void testChangePassword() throws Exception { client.changeAdminPass(serverId, "elmo"); blockUntilServerActive(serverId); - checkPassOk(client.getServer(serverId), "elmo"); + assertPassword(client.getServer(serverId), "elmo"); this.adminPass = "elmo"; } @@ -420,7 +411,7 @@ public class NovaClientLiveTest { client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); blockUntilServerActive(serverId); // issue Web Hosting #119580 imageId comes back incorrect after rebuild - assertEquals(new Integer(imageId), client.getServer(serverId).getImageId()); + assertEquals(imageId, client.getServer(serverId).getImageRef()); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") @@ -441,7 +432,7 @@ public class NovaClientLiveTest { blockUntilServerVerifyResize(serverId); client.revertResizeServer(serverId); blockUntilServerActive(serverId); - assertEquals(new Integer(1), client.getServer(serverId).getFlavorId()); + assertEquals(new Integer(1), client.getServer(serverId).getFlavorRef()); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") @@ -450,7 +441,7 @@ public class NovaClientLiveTest { blockUntilServerVerifyResize(serverId2); client.confirmResizeServer(serverId2); blockUntilServerActive(serverId2); - assertEquals(new Integer(2), client.getServer(serverId2).getFlavorId()); + assertEquals(new Integer(2), client.getServer(serverId2).getFlavorRef()); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"testRebootSoft", "testRevertResize", diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index 65e6ff33f5..8ae3a15b54 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -18,139 +18,128 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static org.testng.Assert.assertEquals; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import org.jclouds.compute.domain.*; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationBuilder; +import org.jclouds.domain.LocationScope; +import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; +import org.testng.annotations.Test; import java.net.UnknownHostException; import java.util.Map; import java.util.Set; -import org.jclouds.openstack.nova.compute.config.NovaComputeServiceDependenciesModule; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystemBuilder; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.VolumeBuilder; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationBuilder; -import org.jclouds.domain.LocationScope; -import org.testng.annotations.Test; - -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; +import static org.testng.Assert.assertEquals; /** * @author Adrian Cole */ @Test(groups = "unit") public class ServerToNodeMetadataTest { - Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); + Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); - @Test - public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException { - Credentials creds = new Credentials("root", "abdce"); + @Test + public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Credentials creds = new Credentials("root", "abdce"); - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - . of("node#1234", creds), Suppliers.> ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of("node#1234", creds), Suppliers.>ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + } - @Test - public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - . of(), Suppliers.> ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").location( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").id("1234").providerId("1234").name("sample-server").location( new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + } - @Test - public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); - Set images = ImmutableSet.of(jcImage); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); + Set images = ImmutableSet.of(jcImage); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - . of(), Suppliers.> ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").operatingSystem( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").operatingSystem( new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( + .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + } - @Test - public void testApplyWhereImageAndHardwareFound() throws UnknownHostException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); - Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); + Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - . of(), Suppliers.> ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.> ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").hardware( + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").hardware( new HardwareBuilder().ids("1").name("256 MB Server").processors( - ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) - .bootDevice(true).build())).build()).operatingSystem( + ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( + ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) + .bootDevice(true).build())).build()).operatingSystem( new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( + .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 83e72fa642..317a957594 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -49,37 +49,35 @@ import static org.testng.Assert.assertEquals; public class ParseServerFromJsonResponseTest { @Test - public void testApplyInputStreamDetails() throws UnknownHostException { + public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { Server response = parseServer(); assertEquals(response.getId(), 1234); assertEquals(response.getName(), "sample-server"); - assertEquals(response.getImageId().intValue(), 1234); - assertEquals(response.getFlavorId().intValue(), 1); - assertEquals(response.getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(true, false, "Uncomment next line"); - //assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); + assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); assertEquals(response.getStatus(), ServerStatus.BUILD); assertEquals(response.getProgress(), new Integer(60)); List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); Addresses addresses1 = new Addresses(new HashSet(publicAddresses), new HashSet(privateAddresses)); - assertEquals(response.getAddresses(), addresses1); assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.getAddresses(), addresses1); } - public static Server parseServer() { + public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { Injector i = Guice.createInjector(new GsonModule()); InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { })); - Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; + + //Function parser = i.getInstance(getParserOrThrowException(NovaClient.class.getMethod("getServer", int.class))); + return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index a9a470fb08..cdaf97e7b2 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -75,10 +75,8 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(0).getId(), 1234); assertEquals(response.get(0).getName(), "sample-server"); - assertEquals(response.get(0).getImageId().intValue(), 1234); - assertEquals(response.get(0).getFlavorId().intValue(), 1); - assertEquals(response.get(0).getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.get(0).getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); assertEquals(true, false, "Uncomment next line"); //assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); @@ -93,8 +91,8 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); assertEquals(response.get(1).getId(), 5678); assertEquals(response.get(1).getName(), "sample-server2"); - assertEquals(response.get(0).getImageId(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1"); - assertEquals(response.get(0).getFlavorId(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1"); + assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); assertEquals(true, false, "Uncomment next line"); //assertEquals(response.getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2"); assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); From 518177cff0264ce7e5d3de403c025627e5d7d41d Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 15 Apr 2011 16:31:43 +0400 Subject: [PATCH 24/95] Committed log4j.xml to win --- .../src/test/resources/log4j.xml | 175 +++++++++++++----- 1 file changed, 124 insertions(+), 51 deletions(-) diff --git a/skeletons/standalone-compute/src/test/resources/log4j.xml b/skeletons/standalone-compute/src/test/resources/log4j.xml index f7337defb9..b068c21071 100755 --- a/skeletons/standalone-compute/src/test/resources/log4j.xml +++ b/skeletons/standalone-compute/src/test/resources/log4j.xml @@ -1,45 +1,68 @@ - + 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. + ==================================================================== +--> - + + debug="false"> - - - - + + + + - + - + - + + + + + + + + + + + + + + + + + + + + - - + + - + - + - + + + + + + + + + + + + - - + + - + - + - + + + + + + + + + + + + + + + + + + + - - + + - - - - - - + + + + + + + + + + + + + + - - + + - + + \ No newline at end of file From 82e3c4ddf73c18530cd0061defb0b884b5e0c2c1 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 15 Apr 2011 17:10:20 +0400 Subject: [PATCH 25/95] Repair after merge --- sandbox-apis/nova/pom.xml | 1 - .../test/java/org/jclouds/openstack/nova/_NovaClient.java | 6 ++---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 87277cdb65..d08309712c 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -159,4 +159,3 @@ - diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index f2c06719a2..c3996e600f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,18 +1,16 @@ package org.jclouds.openstack.nova; import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; import org.jclouds.compute.RunNodesException; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; import java.util.Arrays; -import java.util.Collections; import java.util.Properties; import java.util.Set; @@ -52,4 +50,4 @@ public class _NovaClient { context.close(); } -} +} \ No newline at end of file From a131e2a34b1c3b7d281accea5e517e3dd30579c4 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 15 Apr 2011 19:30:12 +0400 Subject: [PATCH 26/95] Domain model is fixed to match the API v1.1 remaining parts of shared ip functionality is removed --- .../openstack/nova/NovaAsyncClient.java | 419 ++++++++--------- .../jclouds/openstack/nova/NovaClient.java | 420 +++++++++--------- .../functions/ServerToNodeMetadata.java | 188 ++++---- .../openstack/nova/domain/Address.java | 79 ++++ .../openstack/nova/domain/Addresses.java | 146 +++--- .../jclouds/openstack/nova/domain/Server.java | 319 +++++++------ .../nova/options/CreateServerOptions.java | 233 +++++----- .../openstack/nova/NovaAsyncClientTest.java | 15 +- .../openstack/nova/NovaClientLiveTest.java | 29 +- .../jclouds/openstack/nova/_NovaClient.java | 6 +- .../ParseServerFromJsonResponseTest.java | 20 +- .../ParseServerListFromJsonResponseTest.java | 16 +- .../nova/options/CreateServerOptionsTest.java | 89 ++-- .../resources/test_get_server_detail.json | 102 ++--- 14 files changed, 1080 insertions(+), 1001 deletions(-) create mode 100644 sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java index d5f6c87e2e..f21a5d1e0d 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java @@ -18,22 +18,43 @@ */ package org.jclouds.openstack.nova; -import com.google.common.util.concurrent.ListenableFuture; -import org.jclouds.openstack.filters.AddTimestampQuery; -import org.jclouds.openstack.filters.AuthenticateRequest; -import org.jclouds.openstack.nova.domain.*; +import java.util.Set; +import java.util.concurrent.ExecutionException; + +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.core.MediaType; + +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.RebootType; +import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; -import org.jclouds.rest.annotations.*; +import org.jclouds.openstack.filters.AddTimestampQuery; +import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.rest.annotations.Endpoint; +import org.jclouds.rest.annotations.ExceptionParser; +import org.jclouds.rest.annotations.MapBinder; +import org.jclouds.rest.annotations.Payload; +import org.jclouds.rest.annotations.PayloadParam; +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 javax.ws.rs.*; -import javax.ws.rs.core.MediaType; -import java.util.Set; -import java.util.concurrent.ExecutionException; +import com.google.common.util.concurrent.ListenableFuture; /** * Provides asynchronous access to OpenStack Nova via their REST API. @@ -41,221 +62,221 @@ import java.util.concurrent.ExecutionException; * All commands return a ListenableFuture of the result from OpenStack Nova. Any exceptions incurred * during processing will be wrapped in an {@link ExecutionException} as documented in * {@link ListenableFuture#get()}. - * - * @author Adrian Cole + * * @see NovaClient * @see + * @author Adrian Cole */ -@SkipEncoding({'/', '='}) -@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class}) +@SkipEncoding({ '/', '=' }) +@RequestFilters({ AuthenticateRequest.class, AddTimestampQuery.class }) @Endpoint(ServerManagement.class) public interface NovaAsyncClient { - /** - * @see NovaClient#listServers - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listServers(ListOptions... options); + /** + * @see NovaClient#listServers + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listServers(ListOptions... options); - /** - * @see NovaClient#getServer - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @Path("/servers/{id}") - ListenableFuture getServer(@PathParam("id") int id); + /** + * @see NovaClient#getServer + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @Path("/servers/{id}") + ListenableFuture getServer(@PathParam("id") int id); - /** - * @see NovaClient#deleteServer - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/servers/{id}") - ListenableFuture deleteServer(@PathParam("id") int id); + /** + * @see NovaClient#deleteServer + */ + @DELETE + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + @Path("/servers/{id}") + ListenableFuture deleteServer(@PathParam("id") int id); - /** - * @see NovaClient#rebootServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D") - ListenableFuture rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType); + /** + * @see NovaClient#rebootServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"reboot\":%7B\"type\":\"{type}\"%7D%7D") + ListenableFuture rebootServer(@PathParam("id") int id, @PayloadParam("type") RebootType rebootType); - /** - * @see NovaClient#resizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D") - ListenableFuture resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId); + /** + * @see NovaClient#resizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"resize\":%7B\"flavorId\":{flavorId}%7D%7D") + ListenableFuture resizeServer(@PathParam("id") int id, @PayloadParam("flavorId") int flavorId); - /** - * @see NovaClient#confirmResizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("{\"confirmResize\":null}") - ListenableFuture confirmResizeServer(@PathParam("id") int id); + /** + * @see NovaClient#confirmResizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("{\"confirmResize\":null}") + ListenableFuture confirmResizeServer(@PathParam("id") int id); - /** - * @see NovaClient#revertResizeServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @Produces(MediaType.APPLICATION_JSON) - @Payload("{\"revertResize\":null}") - ListenableFuture revertResizeServer(@PathParam("id") int id); + /** + * @see NovaClient#revertResizeServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @Produces(MediaType.APPLICATION_JSON) + @Payload("{\"revertResize\":null}") + ListenableFuture revertResizeServer(@PathParam("id") int id); - /** - * @see NovaClient#createServer - */ - @POST - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers") - @MapBinder(CreateServerOptions.class) - ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, - @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); + /** + * @see NovaClient#createServer + */ + @POST + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers") + @MapBinder(CreateServerOptions.class) + ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, + @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); - /** - * @see NovaClient#rebuildServer - */ - @POST - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/action") - @MapBinder(RebuildServerOptions.class) - ListenableFuture rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); + /** + * @see NovaClient#rebuildServer + */ + @POST + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/action") + @MapBinder(RebuildServerOptions.class) + ListenableFuture rebuildServer(@PathParam("id") int id, RebuildServerOptions... options); - /** - * @see NovaClient#changeAdminPass - */ - @PUT - @Path("/servers/{id}") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") - ListenableFuture changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass); + /** + * @see NovaClient#changeAdminPass + */ + @PUT + @Path("/servers/{id}") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") + ListenableFuture changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass); - /** - * @see NovaClient#renameServer - */ - @PUT - @Path("/servers/{id}") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D") - ListenableFuture renameServer(@PathParam("id") int id, @PayloadParam("name") String newName); + /** + * @see NovaClient#renameServer + */ + @PUT + @Path("/servers/{id}") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"server\":%7B\"name\":\"{name}\"%7D%7D") + ListenableFuture renameServer(@PathParam("id") int id, @PayloadParam("name") String newName); - /** - * @see NovaClient#listFlavors - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/flavors") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listFlavors(ListOptions... options); + /** + * @see NovaClient#listFlavors + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/flavors") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listFlavors(ListOptions... options); - /** - * @see NovaClient#getFlavor - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/flavors/{id}") - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - ListenableFuture getFlavor(@PathParam("id") int id); + /** + * @see NovaClient#getFlavor + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/flavors/{id}") + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + ListenableFuture getFlavor(@PathParam("id") int id); - /** - * @see NovaClient#listImages - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/images") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listImages(ListOptions... options); + /** + * @see NovaClient#listImages + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/images") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listImages(ListOptions... options); - /** - * @see NovaClient#getImage - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @ExceptionParser(ReturnNullOnNotFoundOr404.class) - @QueryParams(keys = "format", values = "json") - @Path("/images/{id}") - ListenableFuture getImage(@PathParam("id") int id); + /** + * @see NovaClient#getImage + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @ExceptionParser(ReturnNullOnNotFoundOr404.class) + @QueryParams(keys = "format", values = "json") + @Path("/images/{id}") + ListenableFuture getImage(@PathParam("id") int id); - /** - * @see NovaClient#deleteImage - */ - @DELETE - @ExceptionParser(ReturnFalseOnNotFoundOr404.class) - @Path("/images/{id}") - ListenableFuture deleteImage(@PathParam("id") int id); + /** + * @see NovaClient#deleteImage + */ + @DELETE + @ExceptionParser(ReturnFalseOnNotFoundOr404.class) + @Path("/images/{id}") + ListenableFuture deleteImage(@PathParam("id") int id); - /** - * @see NovaClient#createImageFromServer - */ - @POST - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/images") - @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D") - ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, - @PayloadParam("serverId") int serverId); + /** + * @see NovaClient#createImageFromServer + */ + @POST + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/images") + @Produces(MediaType.APPLICATION_JSON) + @Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D") + ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, + @PayloadParam("serverId") int serverId); - /** - * @see NovaClient#getAddresses(int) - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips") - ListenableFuture getAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#listAddresses + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips") + ListenableFuture getAddresses(@PathParam("id") int serverId); - /** - * @see NovaClient#listPublicAddresses(int) - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips/public") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listPublicAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#listPublicAddresses + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips/public") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listPublicAddresses(@PathParam("id") int serverId); - /** - * @see NovaClient#listPrivateAddresses - */ - @GET - @Unwrap - @Consumes(MediaType.APPLICATION_JSON) - @QueryParams(keys = "format", values = "json") - @Path("/servers/{id}/ips/private") - @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) - ListenableFuture> listPrivateAddresses(@PathParam("id") int serverId); + /** + * @see NovaClient#listPrivateAddresses + */ + @GET + @Unwrap + @Consumes(MediaType.APPLICATION_JSON) + @QueryParams(keys = "format", values = "json") + @Path("/servers/{id}/ips/private") + @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) + ListenableFuture> listPrivateAddresses(@PathParam("id") int serverId); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java index 1e9c75fb93..3ed6f04e50 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaClient.java @@ -18,18 +18,24 @@ */ package org.jclouds.openstack.nova; +import java.util.Set; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; + +import javax.ws.rs.PathParam; + import org.jclouds.concurrent.Timeout; -import org.jclouds.openstack.nova.domain.*; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.RebootType; +import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.rest.ResourceNotFoundException; -import javax.ws.rs.PathParam; -import java.util.Set; -import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; /** * Provides access to OpenStack Nova via their REST API. @@ -37,224 +43,240 @@ import java.util.concurrent.TimeUnit; * All commands return a Future of the result from OpenStack Nova. Any exceptions incurred * during processing will be wrapped in an {@link ExecutionException} as documented in * {@link Future#get()}. - * - * @author Adrian Cole + * * @see NovaAsyncClient * @see + * @author Adrian Cole */ @Timeout(duration = 60, timeUnit = TimeUnit.SECONDS) public interface NovaClient { - /** - * List all servers (IDs and names only) - *

- * This operation provides a list of servers associated with your identity. Servers that have been - * deleted are not included in this list. - *

- * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listServers(ListOptions... options); + /** + * + * List all servers (IDs and names only) + * + * This operation provides a list of servers associated with your identity. Servers that have been + * deleted are not included in this list. + *

+ * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listServers(ListOptions... options); - /** - * This operation returns details of the specified server. - * - * @return null, if the server is not found - * @see Server - */ - Server getServer(@PathParam("id") int id); + /** + * + * This operation returns details of the specified server. + * + * @return null, if the server is not found + * @see Server + */ + Server getServer(@PathParam("id") int id); - /** - * This operation deletes a cloud server instance from the system. - *

- * Note: When a server is deleted, all images created from that server are also removed. - * - * @return false if the server is not found - * @see Server - */ - boolean deleteServer(@PathParam("id") int id); + /** + * + * This operation deletes a cloud server instance from the system. + *

+ * Note: When a server is deleted, all images created from that server are also removed. + * + * @return false if the server is not found + * @see Server + */ + boolean deleteServer(@PathParam("id") int id); - /** - * The reboot function allows for either a soft or hard reboot of a server. - *

- * Status Transition: - *

- * ACTIVE - REBOOT - ACTIVE (soft reboot) - *

- * ACTIVE - HARD_REBOOT - ACTIVE (hard reboot) - * - * @param rebootType With a soft reboot, the operating system is signaled to restart, which allows for a - * graceful shutdown of all processes. A hard reboot is the equivalent of power cycling - * the server. - */ - void rebootServer(int id, RebootType rebootType); + /** + * The reboot function allows for either a soft or hard reboot of a server. + *

+ * Status Transition: + *

+ * ACTIVE - REBOOT - ACTIVE (soft reboot) + *

+ * ACTIVE - HARD_REBOOT - ACTIVE (hard reboot) + * + * @param rebootType + * With a soft reboot, the operating system is signaled to restart, which allows for a + * graceful shutdown of all processes. A hard reboot is the equivalent of power cycling + * the server. + */ + void rebootServer(int id, RebootType rebootType); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly confirmed, at which time the - * original server is removed. All resizes are automatically confirmed after 24 hours if they are - * not confirmed or reverted. - *

- * Status Transition: - *

- * ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE - *

- * ACTIVE - QUEUE_RESIZE - ACTIVE (on error) - */ - void resizeServer(int id, int flavorId); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly confirmed, at which time the + * original server is removed. All resizes are automatically confirmed after 24 hours if they are + * not confirmed or reverted. + *

+ * Status Transition: + *

+ * ACTIVE - QUEUE_RESIZE - PREP_RESIZE - VERIFY_RESIZE + *

+ * ACTIVE - QUEUE_RESIZE - ACTIVE (on error) + */ + void resizeServer(int id, int flavorId); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly confirmed, at which time the - * original server is removed. All resizes are automatically confirmed after 24 hours if they are - * not confirmed or reverted. - *

- * Status Transition: - *

- * VERIFY_RESIZE - ACTIVE - */ - void confirmResizeServer(int id); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly confirmed, at which time the + * original server is removed. All resizes are automatically confirmed after 24 hours if they are + * not confirmed or reverted. + *

+ * Status Transition: + *

+ * VERIFY_RESIZE - ACTIVE + */ + void confirmResizeServer(int id); - /** - * The resize function converts an existing server to a different flavor, in essence, scaling the - * server up or down. The original server is saved for a period of time to allow rollback if - * there is a problem. All resizes should be tested and explicitly reverted, at which time the - * original server is removed. All resizes are automatically reverted after 24 hours if they are - * not reverted or reverted. - *

- * Status Transition: - *

- * VERIFY_RESIZE - ACTIVE - */ - void revertResizeServer(int id); + /** + * The resize function converts an existing server to a different flavor, in essence, scaling the + * server up or down. The original server is saved for a period of time to allow rollback if + * there is a problem. All resizes should be tested and explicitly reverted, at which time the + * original server is removed. All resizes are automatically reverted after 24 hours if they are + * not reverted or reverted. + *

+ * Status Transition: + *

+ * VERIFY_RESIZE - ACTIVE + */ + void revertResizeServer(int id); - /** - * This operation asynchronously provisions a new server. The progress of this operation depends - * on several factors including location of the requested image, network i/o, host load, and the - * selected flavor. The progress of the request can be checked by performing a GET on /server/id, - * which will return a progress attribute (0-100% completion). A password will be randomly - * generated for you and returned in the response object. For security reasons, it will not be - * returned in subsequent GET calls against a given server ID. - * - * @param options - used to specify extra files, metadata, or ip parameters during server creation. - */ - Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); + /** + * This operation asynchronously provisions a new server. The progress of this operation depends + * on several factors including location of the requested image, network i/o, host load, and the + * selected flavor. The progress of the request can be checked by performing a GET on /server/id, + * which will return a progress attribute (0-100% completion). A password will be randomly + * generated for you and returned in the response object. For security reasons, it will not be + * returned in subsequent GET calls against a given server ID. + * + * @param options + * - used to specify extra files, metadata, or ip parameters during server creation. + */ + Server createServer(String name, String imageRef, String flavorRef, CreateServerOptions... options); - /** - * The rebuild function removes all data on the server and replaces it with the specified image. - * Server ID and IP addresses remain the same. - *

- * Status Transition: - *

- * ACTIVE - REBUILD - ACTIVE - *

- * ACTIVE - REBUILD - ERROR (on error) - *

- * - * @param options - imageId is an optional argument. If it is not specified, the server is rebuilt - * with the original imageId. - */ - void rebuildServer(int id, RebuildServerOptions... options); + /** + * The rebuild function removes all data on the server and replaces it with the specified image. + * Server ID and IP addresses remain the same. + *

+ * Status Transition: + *

+ * ACTIVE - REBUILD - ACTIVE + *

+ * ACTIVE - REBUILD - ERROR (on error) + *

+ * + * @param options + * - imageId is an optional argument. If it is not specified, the server is rebuilt + * with the original imageId. + */ + void rebuildServer(int id, RebuildServerOptions... options); - /** - * This operation allows you to change the administrative password. - *

- * Status Transition: ACTIVE - PASSWORD - ACTIVE - */ - void changeAdminPass(int id, String adminPass); + /** + * This operation allows you to change the administrative password. + *

+ * Status Transition: ACTIVE - PASSWORD - ACTIVE + * + */ + void changeAdminPass(int id, String adminPass); - /** - * This operation allows you to update the name of the server. This operation changes the name of - * the server in the OpenStack Nova system and does not change the server host name itself. - *

- * Status Transition: ACTIVE - PASSWORD - ACTIVE - */ - void renameServer(int id, String newName); + /** + * This operation allows you to update the name of the server. This operation changes the name of + * the server in the OpenStack Nova system and does not change the server host name itself. + *

+ * Status Transition: ACTIVE - PASSWORD - ACTIVE + * + */ + void renameServer(int id, String newName); - /** - * List available flavors (IDs and names only) - *

- * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listFlavors(ListOptions... options); + /** + * + * List available flavors (IDs and names only) + * + * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listFlavors(ListOptions... options); - /** - * This operation returns details of the specified flavor. - * - * @return null, if the flavor is not found - * @see Flavor - */ - Flavor getFlavor(int id); + /** + * + * This operation returns details of the specified flavor. + * + * @return null, if the flavor is not found + * @see Flavor + */ + Flavor getFlavor(int id); - /** - * List available images (IDs and names only) - *

- * in order to retrieve all details, pass the option {@link ListOptions#withDetails() - * withDetails()} - */ - Set listImages(ListOptions... options); + /** + * + * List available images (IDs and names only) + * + * in order to retrieve all details, pass the option {@link ListOptions#withDetails() + * withDetails()} + */ + Set listImages(ListOptions... options); - /** - * This operation returns details of the specified image. - * - * @return null, if the image is not found - * @see Image - */ - Image getImage(int id); + /** + * + * This operation returns details of the specified image. + * + * @return null, if the image is not found + * + * @see Image + */ + Image getImage(int id); - /** - * This operation deletes an image from the system. - *

- * Note: Images are immediately removed. Currently, there are no state transitions to track the - * delete operation. - * - * @return false if the image is not found - * @see Image - */ - boolean deleteImage(int id); + /** + * + * This operation deletes an image from the system. + *

+ * Note: Images are immediately removed. Currently, there are no state transitions to track the + * delete operation. + * + * @return false if the image is not found + * @see Image + */ + boolean deleteImage(int id); - /** - * This operation creates a new image for the given server ID. Once complete, a new image will be - * available that can be used to rebuild or create servers. Specifying the same image name as an - * existing custom image replaces the image. The image creation status can be queried by - * performing a GET on /images/id and examining the status and progress attributes. - *

- * Status Transition: - *

- * QUEUED - PREPARING - SAVING - ACTIVE - *

- * QUEUED - PREPARING - SAVING - FAILED (on error) - *

- * Note: At present, image creation is an asynchronous operation, so coordinating the creation - * with data quiescence, etc. is currently not possible. - * - * @throws ResourceNotFoundException if the server is not found - * @see Image - */ - Image createImageFromServer(String imageName, int serverId); + /** + * + * This operation creates a new image for the given server ID. Once complete, a new image will be + * available that can be used to rebuild or create servers. Specifying the same image name as an + * existing custom image replaces the image. The image creation status can be queried by + * performing a GET on /images/id and examining the status and progress attributes. + * + * Status Transition: + *

+ * QUEUED - PREPARING - SAVING - ACTIVE + *

+ * QUEUED - PREPARING - SAVING - FAILED (on error) + *

+ * Note: At present, image creation is an asynchronous operation, so coordinating the creation + * with data quiescence, etc. is currently not possible. + * + * @throws ResourceNotFoundException + * if the server is not found + * @see Image + */ + Image createImageFromServer(String imageName, int serverId); - /** - * List all server addresses - *

- * returns empty set if the server doesn't exist - */ - Addresses getAddresses(int serverId); + /** + * List all server addresses + * + * returns empty set if the server doesn't exist + */ + Addresses getAddresses(int serverId); - /** - * List all public server addresses - *

- * returns empty set if the server doesn't exist - */ - Set listPublicAddresses(int serverId); + /** + * List all public server addresses + * + * returns empty set if the server doesn't exist + */ + Set listPublicAddresses(int serverId); - /** - * List all private server addresses - *

- * returns empty set if the server doesn't exist - */ - Set listPrivateAddresses(int serverId); + /** + * List all private server addresses + * + * returns empty set if the server doesn't exist + */ + Set listPrivateAddresses(int serverId); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java index 8d16f9e6ad..3b03764e46 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java @@ -18,119 +18,127 @@ */ package org.jclouds.openstack.nova.compute.functions; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; + +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.collect.Memoized; -import org.jclouds.compute.domain.*; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.logging.Logger; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; /** * @author Adrian Cole */ @Singleton public class ServerToNodeMetadata implements Function { - @Resource - @Named(ComputeServiceConstants.COMPUTE_LOGGER) - protected Logger logger = Logger.NULL; + @Resource + @Named(ComputeServiceConstants.COMPUTE_LOGGER) + protected Logger logger = Logger.NULL; - protected final Supplier location; - protected final Map credentialStore; - protected final Map serverToNodeState; - protected final Supplier> images; - protected final Supplier> hardwares; + protected final Supplier location; + protected final Map credentialStore; + protected final Map serverToNodeState; + protected final Supplier> images; + protected final Supplier> hardwares; - private static class FindImageForServer implements Predicate { - private final Server instance; + private static class FindImageForServer implements Predicate { + private final Server instance; - private FindImageForServer(Server instance) { - this.instance = instance; - } + private FindImageForServer(Server instance) { + this.instance = instance; + } - @Override - public boolean apply(Image input) { - return input.getProviderId().equals(instance.getImageRef() + ""); - } - } + @Override + public boolean apply(Image input) { + return input.getProviderId().equals(instance.getImageRef() + ""); + } + } - private static class FindHardwareForServer implements Predicate { - private final Server instance; + private static class FindHardwareForServer implements Predicate { + private final Server instance; - private FindHardwareForServer(Server instance) { - this.instance = instance; - } + private FindHardwareForServer(Server instance) { + this.instance = instance; + } - @Override - public boolean apply(Hardware input) { - return input.getProviderId().equals(instance.getFlavorRef() + ""); - } - } + @Override + public boolean apply(Hardware input) { + return input.getProviderId().equals(instance.getFlavorRef() + ""); + } + } - @Inject - ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, - @Memoized Supplier> images, Supplier location, - @Memoized Supplier> hardwares) { - this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); - this.credentialStore = checkNotNull(credentialStore, "credentialStore"); - this.images = checkNotNull(images, "images"); - this.location = checkNotNull(location, "location"); - this.hardwares = checkNotNull(hardwares, "hardwares"); - } + @Inject + ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, + @Memoized Supplier> images, Supplier location, + @Memoized Supplier> hardwares) { + this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); + this.credentialStore = checkNotNull(credentialStore, "credentialStore"); + this.images = checkNotNull(images, "images"); + this.location = checkNotNull(location, "location"); + this.hardwares = checkNotNull(hardwares, "hardwares"); + } - @Override - public NodeMetadata apply(Server from) { - NodeMetadataBuilder builder = new NodeMetadataBuilder(); - builder.ids(from.getId() + ""); - builder.name(from.getName()); - builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description( - from.getHostId()).parent(location.get()).build()); - builder.userMetadata(from.getMetadata()); - builder.group(parseGroupFromName(from.getName())); - builder.imageId(from.getImageRef() + ""); - builder.operatingSystem(parseOperatingSystem(from)); - builder.hardware(parseHardware(from)); - builder.state(serverToNodeState.get(from.getStatus())); - builder.publicAddresses(from.getAddresses().getPublicAddresses()); - builder.privateAddresses(from.getAddresses().getPrivateAddresses()); - builder.credentials(credentialStore.get("node#" + from.getId())); - builder.uri(from.getURI()); - return builder.build(); - } + @Override + public NodeMetadata apply(Server from) { + NodeMetadataBuilder builder = new NodeMetadataBuilder(); + builder.ids(from.getId() + ""); + builder.name(from.getName()); + builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description( + from.getHostId()).parent(location.get()).build()); + builder.userMetadata(from.getMetadata()); + builder.group(parseGroupFromName(from.getName())); + builder.imageId(from.getImageRef() + ""); + builder.operatingSystem(parseOperatingSystem(from)); + builder.hardware(parseHardware(from)); + builder.state(serverToNodeState.get(from.getStatus())); + builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction())); + builder.privateAddresses(Iterables.transform(from.getAddresses().getPrivateAddresses(), Address.newAddress2StringFunction())); + builder.credentials(credentialStore.get("node#" + from.getId())); + builder.uri(from.getURI()); + return builder.build(); + } - protected Hardware parseHardware(Server from) { - try { - return Iterables.find(hardwares.get(), new FindHardwareForServer(from)); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching hardware for server %s", from); - } - return null; - } + protected Hardware parseHardware(Server from) { + try { + return Iterables.find(hardwares.get(), new FindHardwareForServer(from)); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching hardware for server %s", from); + } + return null; + } - protected OperatingSystem parseOperatingSystem(Server from) { - try { - return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); - } catch (NoSuchElementException e) { - logger.warn("could not find a matching image for server %s in location %s", from, location); - } - return null; - } + protected OperatingSystem parseOperatingSystem(Server from) { + try { + return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); + } catch (NoSuchElementException e) { + logger.warn("could not find a matching image for server %s in location %s", from, location); + } + return null; + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java new file mode 100644 index 0000000000..8ef964acb9 --- /dev/null +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java @@ -0,0 +1,79 @@ +package org.jclouds.openstack.nova.domain; + +import com.google.common.base.Function; +import com.google.gson.annotations.SerializedName; + +import javax.annotation.Nullable; + +/** + * @author Dmitri Babaev + */ +public class Address { + @SerializedName("addr") + private String address; + private int version; + + //for de-serialization + private Address() { + } + + public Address(String address, int version) { + this.address = address; + this.version = version; + } + + public String getAddress() { + return address; + } + + public int getVersion() { + return version; + } + + @Override + public String toString() { + return address; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + Address address1 = (Address) o; + + if (version != address1.version) return false; + if (address != null ? !address.equals(address1.address) : address1.address != null) return false; + + return true; + } + + @Override + public int hashCode() { + int result = address != null ? address.hashCode() : 0; + result = 31 * result + version; + return result; + } + + public static Function newAddress2StringFunction() { + return new Function() { + @Override + public String apply(@Nullable Address input) { + return input.getAddress(); + } + }; + } + + public static Address valueOf(String address) { + return new Address(address, address.startsWith("::") ? 6 : 4); + } + + public static Function newString2AddressFunction() { + return new Function() { + @Override + public Address apply(@Nullable String input) { + return valueOf(input); + } + }; + } +} diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java index cd93bdc272..478808f156 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Addresses.java @@ -18,113 +18,81 @@ */ package org.jclouds.openstack.nova.domain; +import java.util.Set; + import com.google.common.collect.Sets; import com.google.gson.annotations.SerializedName; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - /** + * * @author Adrian Cole */ public class Addresses { - @SerializedName("public") - private Set> publicAddresses = Sets.newHashSet(); - @SerializedName("private") - private Set> privateAddresses = Sets.newHashSet(); + @SerializedName("public") + private Set

publicAddresses = Sets.newLinkedHashSet(); + @SerializedName("private") + private Set
privateAddresses = Sets.newLinkedHashSet(); - public Addresses() { - } + public Addresses() { + } -// public Addresses(Set> publicAddresses, Set> privateAddresses) { -// this.publicAddresses = publicAddresses; -// this.privateAddresses = privateAddresses; -// } + public Addresses(Set
publicAddresses, Set
privateAddresses) { + this.publicAddresses = publicAddresses; + this.privateAddresses = privateAddresses; + } - public Addresses(Set publicAddresses, Set privateAddresses) { - this.publicAddresses.clear(); - this.privateAddresses.clear(); - for (String address : publicAddresses) { - HashMap addressMap = new HashMap(); - addressMap.put("version", "4"); - addressMap.put("addr", "address"); - this.publicAddresses.add(addressMap); - } - for (String address : privateAddresses) { - HashMap addressMap = new HashMap(); - addressMap.put("version", "4"); - addressMap.put("addr", "address"); - this.privateAddresses.add(addressMap); - } + public void setPublicAddresses(Set
publicAddresses) { + this.publicAddresses = publicAddresses; + } - } + public Set
getPublicAddresses() { + return publicAddresses; + } - public void setPublicAddresses(Set> publicAddresses) { - this.publicAddresses = publicAddresses; - } + public void setPrivateAddresses(Set
privateAddresses) { + this.privateAddresses = privateAddresses; + } - public Set getPublicAddresses() { - HashSet addresses = new HashSet(); - for (Map address : publicAddresses) { - if (address.containsKey("addr")) { - addresses.add(address.get("addr")); - } - } - return addresses; - } + public Set
getPrivateAddresses() { + return privateAddresses; + } - public void setPrivateAddresses(Set> privateAddresses) { - this.privateAddresses = privateAddresses; - } + @Override + public String toString() { + return "Addresses [privateAddresses=" + privateAddresses + ", publicAddresses=" + + publicAddresses + "]"; + } - public Set getPrivateAddresses() { - HashSet addresses = new HashSet(); - for (Map address : privateAddresses) { - if (address.containsKey("addr")) { - addresses.add(address.get("addr")); - } - } - return addresses; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode()); + result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode()); + return result; + } - @Override - public String toString() { - return "Addresses [privateAddresses=" + privateAddresses + ", publicAddresses=" - + publicAddresses + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((privateAddresses == null) ? 0 : privateAddresses.hashCode()); - result = prime * result + ((publicAddresses == null) ? 0 : publicAddresses.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Addresses other = (Addresses) obj; + if (privateAddresses == null) { + if (other.privateAddresses != null) return false; - if (getClass() != obj.getClass()) + } else if (!privateAddresses.equals(other.privateAddresses)) + return false; + if (publicAddresses == null) { + if (other.publicAddresses != null) return false; - Addresses other = (Addresses) obj; - if (privateAddresses == null) { - if (other.privateAddresses != null) - return false; - } else if (!privateAddresses.equals(other.privateAddresses)) - return false; - if (publicAddresses == null) { - if (other.publicAddresses != null) - return false; - } else if (!publicAddresses.equals(other.publicAddresses)) - return false; - return true; - } + } else if (!publicAddresses.equals(other.publicAddresses)) + return false; + return true; + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java index ca1d902f3f..69c3d841f5 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java @@ -18,217 +18,196 @@ */ package org.jclouds.openstack.nova.domain; -import com.google.common.collect.Maps; - import java.util.Map; +import com.google.common.collect.Maps; + /** * A server is a virtual machine instance in the OpenStack Nova system. Flavor and image are * requisite elements when creating a server. - * + * * @author Adrian Cole */ public class Server extends Resource { - private int id; - private String name; + private int id; + private String name; -// private Map> metadata = Maps.newHashMap(); + private Map metadata = Maps.newHashMap(); - public Map getMetadata() { - return metadata; - } + private Addresses addresses; + private String adminPass; + private String flavorRef; + private String hostId; + private String imageRef; - public void setMetadata(Map metadata) { - this.metadata = metadata; - } + private Integer progress; + private ServerStatus status; - private Map metadata = Maps.newHashMap(); + public Server() { + } - private Addresses addresses; + public Server(int id, String name) { + this.id = id; + this.name = name; + } - private String adminPass; - private String flavorRef; - private String hostId; - private String imageRef; + public void setMetadata(Map metadata) { + this.metadata = metadata; + } - public String getAffinityId() { - return affinityId; - } + public Map getMetadata() { + return metadata; + } - public void setAffinityId(String affinityId) { - this.affinityId = affinityId; - } + public void setAddresses(Addresses addresses) { + this.addresses = addresses; + } - private String affinityId; + public Addresses getAddresses() { + return addresses; + } - private Integer progress; - private ServerStatus status; + public void setAdminPass(String adminPass) { + this.adminPass = adminPass; + } - public Server() { - } + public String getAdminPass() { + return adminPass; + } - public Server(int id, String name) { - this.id = id; - this.name = name; - } + public void setFlavorRef(String flavorRef) { + this.flavorRef = flavorRef; + } -// public void setMetadata(Map metadata) { -// this.metadata.put("values", metadata); -// } + public String getFlavorRef() { + return flavorRef; + } -// public Map getMetadata() { -// return metadata.get("values"); -// } + public void setHostId(String hostId) { + this.hostId = hostId; + } - public void setAddresses(Addresses addresses) { - this.addresses = addresses; - } + /** + * The OpenStack Nova provisioning algorithm has an anti-affinity property that attempts to spread + * out customer VMs across hosts. Under certain situations, VMs from the same customer may be + * placed on the same host. hostId represents the host your cloud server runs on and can be used + * to determine this scenario if it's relevant to your application. + *

+ * Note: hostId is unique PER ACCOUNT and is not globally unique. + */ + public String getHostId() { + return hostId; + } - public Addresses getAddresses() { - return addresses; - } + public int getId() { + return id; + } - public void setAdminPass(String adminPass) { - this.adminPass = adminPass; - } + public void setImageRef(String imageRef) { + this.imageRef = imageRef; + } - public String getAdminPass() { - return adminPass; - } + public String getImageRef() { + return imageRef; + } - public void setFlavorRef(String flavorRef) { - this.flavorRef = flavorRef; - } + public String getName() { + return name; + } - public String getFlavorRef() { - return flavorRef; - } + public void setProgress(Integer progress) { + this.progress = progress; + } - public void setHostId(String hostId) { - this.hostId = hostId; - } + public Integer getProgress() { + return progress; + } - /** - * The OpenStack Nova provisioning algorithm has an anti-affinity property that attempts to spread - * out customer VMs across hosts. Under certain situations, VMs from the same customer may be - * placed on the same host. hostId represents the host your cloud server runs on and can be used - * to determine this scenario if it's relevant to your application. - *

- * Note: hostId is unique PER ACCOUNT and is not globally unique. - */ - public String getHostId() { - return hostId; - } + public void setStatus(ServerStatus status) { + this.status = status; + } - public int getId() { - return id; - } + /** + * Servers contain a status attribute that can be used as an indication of the current server + * state. Servers with an ACTIVE status are available for use. + */ + public ServerStatus getStatus() { + return status; + } - public void getImageRef(String imageRef) { - this.imageRef = imageRef; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((addresses == null) ? 0 : addresses.hashCode()); + result = prime * result + ((adminPass == null) ? 0 : adminPass.hashCode()); + result = prime * result + ((flavorRef == null) ? 0 : flavorRef.hashCode()); + result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); + result = prime * result + id; + result = prime * result + ((imageRef == null) ? 0 : imageRef.hashCode()); + result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + return result; + } - public String getImageRef() { - return imageRef; - } - - public String getName() { - return name; - } - - public void setProgress(Integer progress) { - this.progress = progress; - } - - public Integer getProgress() { - return progress; - } - - public void setStatus(ServerStatus status) { - this.status = status; - } - - /** - * Servers contain a status attribute that can be used as an indication of the current server - * state. Servers with an ACTIVE status are available for use. - */ - public ServerStatus getStatus() { - return status; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((addresses == null) ? 0 : addresses.hashCode()); - result = prime * result + ((adminPass == null) ? 0 : adminPass.hashCode()); - result = prime * result + ((flavorRef == null) ? 0 : flavorRef.hashCode()); - result = prime * result + ((hostId == null) ? 0 : hostId.hashCode()); - result = prime * result + id; - result = prime * result + ((imageRef == null) ? 0 : imageRef.hashCode()); - result = prime * result + ((metadata == null) ? 0 : metadata.hashCode()); - result = prime * result + ((name == null) ? 0 : name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Server other = (Server) obj; + if (addresses == null) { + if (other.addresses != null) return false; - if (getClass() != obj.getClass()) + } else if (!addresses.equals(other.addresses)) + return false; + if (adminPass == null) { + if (other.adminPass != null) return false; - Server other = (Server) obj; - if (addresses == null) { - if (other.addresses != null) - return false; - } else if (!addresses.equals(other.addresses)) + } else if (!adminPass.equals(other.adminPass)) + return false; + if (flavorRef == null) { + if (other.flavorRef != null) return false; - if (adminPass == null) { - if (other.adminPass != null) - return false; - } else if (!adminPass.equals(other.adminPass)) + } else if (!flavorRef.equals(other.flavorRef)) + return false; + if (hostId == null) { + if (other.hostId != null) return false; - if (flavorRef == null) { - if (other.flavorRef != null) - return false; - } else if (!flavorRef.equals(other.flavorRef)) + } else if (!hostId.equals(other.hostId)) + return false; + if (id != other.id) + return false; + if (imageRef == null) { + if (other.imageRef != null) return false; - if (hostId == null) { - if (other.hostId != null) - return false; - } else if (!hostId.equals(other.hostId)) + } else if (!imageRef.equals(other.imageRef)) + return false; + if (metadata == null) { + if (other.metadata != null) return false; - if (id != other.id) + } else if (!metadata.equals(other.metadata)) + return false; + if (name == null) { + if (other.name != null) return false; - if (imageRef == null) { - if (other.imageRef != null) - return false; - } else if (!imageRef.equals(other.imageRef)) - return false; - if (metadata == null) { - if (other.metadata != null) - return false; - } else if (!metadata.equals(other.metadata)) - return false; - if (name == null) { - if (other.name != null) - return false; - } else if (!name.equals(other.name)) - return false; - return true; - } + } else if (!name.equals(other.name)) + return false; + return true; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - @Override - public String toString() { - return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorRef=" - + flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef - + ", metadata=" + metadata + ", name=" + name + "]"; - } + @Override + public String toString() { + return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorRef=" + + flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef + + ", metadata=" + metadata + ", name=" + name + "]"; + } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java index be8607a17d..b93a46beb5 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java @@ -18,81 +18,88 @@ */ package org.jclouds.openstack.nova.options; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; +import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Preconditions.checkState; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + import org.jclouds.encryption.internal.Base64; import org.jclouds.http.HttpRequest; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.rest.binders.BindToJsonPayload; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import static com.google.common.base.Preconditions.*; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; /** + * * @author Adrian Cole + * */ public class CreateServerOptions extends BindToJsonPayload { - static class File { - private final String path; - private final String contents; + static class File { + private final String path; + private final String contents; - public File(String path, byte[] contents) { - this.path = checkNotNull(path, "path"); - this.contents = Base64.encodeBytes(checkNotNull(contents, "contents")); - checkArgument(path.getBytes().length < 255, String.format( - "maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path - .getBytes().length)); - checkArgument(contents.length < 10 * 1024, String.format( - "maximum size of the file is 10KB. Contents specified is %d bytes", - contents.length)); - } + public File(String path, byte[] contents) { + this.path = checkNotNull(path, "path"); + this.contents = Base64.encodeBytes(checkNotNull(contents, "contents")); + checkArgument(path.getBytes().length < 255, String.format( + "maximum length of path is 255 bytes. Path specified %s is %d bytes", path, path + .getBytes().length)); + checkArgument(contents.length < 10 * 1024, String.format( + "maximum size of the file is 10KB. Contents specified is %d bytes", + contents.length)); + } - public String getContents() { - return contents; - } + public String getContents() { + return contents; + } - public String getPath() { - return path; - } + public String getPath() { + return path; + } - } + } - @SuppressWarnings("unused") - private class ServerRequest { - final String name; - final String imageRef; - final String flavorRef; - Map metadata; - List personality; - Addresses addresses; + @SuppressWarnings("unused") + private class ServerRequest { + final String name; + final String imageRef; + final String flavorRef; + Map metadata; + List personality; + Integer sharedIpGroupId; + Addresses addresses; - private ServerRequest(String name, String imageRef, String flavorRef) { - this.name = name; - this.imageRef = imageRef; - this.flavorRef = flavorRef; - } + private ServerRequest(String name, String imageRef, String flavorRef) { + this.name = name; + this.imageRef = imageRef; + this.flavorRef = flavorRef; + } - } + } - private Map metadata = Maps.newHashMap(); - private List files = Lists.newArrayList(); + private Map metadata = Maps.newHashMap(); + private List files = Lists.newArrayList(); private String publicIp; - @Override - public R bindToRequest(R request, Map postParams) { - ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), - "name parameter not present"), checkNotNull(postParams - .get("imageRef"), "imageRef parameter not present"), checkNotNull( - postParams.get("flavorRef"), "flavorRef parameter not present")); - if (metadata.size() > 0) - server.metadata = metadata; - if (files.size() > 0) - server.personality = files; + @Override + public R bindToRequest(R request, Map postParams) { + ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), + "name parameter not present"), checkNotNull(postParams + .get("imageRef"), "imageRef parameter not present"), checkNotNull( + postParams.get("flavorRef"), "flavorRef parameter not present")); + if (metadata.size() > 0) + server.metadata = metadata; + if (files.size() > 0) + server.personality = files; if (publicIp != null) { server.addresses = new Addresses(); server.addresses.getPublicAddresses().add(publicIp); @@ -101,71 +108,69 @@ public class CreateServerOptions extends BindToJsonPayload { return bindToRequest(request, ImmutableMap.of("server", server)); } - /** - * You may further customize a cloud server by injecting data into the file system of the cloud - * server itself. This is useful, for example, for inserting ssh keys, setting configuration - * files, or storing data that you want to retrieve from within the instance itself. It is - * intended to provide a minimal amount of launch-time personalization. If significant - * customization is required, a custom image should be created. The max size of the file path - * data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents - * should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the - * decoded data not the number of characters in the encoded data. The maximum number of file - * path/content pairs that can be supplied is 5. Any existing files that match the specified file - * will be renamed to include the extension bak followed by a time stamp. For example, the file - * /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and - * the root group as owner and group owner, respectively and will allow user and group read - * access only (-r--r-----). - */ - public CreateServerOptions withFile(String path, byte[] contents) { - checkState(files.size() < 5, "maximum number of files allowed is 5"); - files.add(new File(path, contents)); - return this; - } + /** + * You may further customize a cloud server by injecting data into the file system of the cloud + * server itself. This is useful, for example, for inserting ssh keys, setting configuration + * files, or storing data that you want to retrieve from within the instance itself. It is + * intended to provide a minimal amount of launch-time personalization. If significant + * customization is required, a custom image should be created. The max size of the file path + * data is 255 bytes while the max size of the file contents is 10KB. Note that the file contents + * should be encoded as a Base64 string and the 10KB limit refers to the number of bytes in the + * decoded data not the number of characters in the encoded data. The maximum number of file + * path/content pairs that can be supplied is 5. Any existing files that match the specified file + * will be renamed to include the extension bak followed by a time stamp. For example, the file + * /etc/passwd will be backed up as /etc/passwd.bak.1246036261.5785. All files will have root and + * the root group as owner and group owner, respectively and will allow user and group read + * access only (-r--r-----). + */ + public CreateServerOptions withFile(String path, byte[] contents) { + checkState(files.size() < 5, "maximum number of files allowed is 5"); + files.add(new File(path, contents)); + return this; + } - /** - * Custom cloud server metadata can also be supplied at launch time. This metadata is stored in - * the API system where it is retrievable by querying the API for server status. The maximum size - * of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that - * can be supplied per server is 5. - */ - public CreateServerOptions withMetadata(Map metadata) { - checkNotNull(metadata, "metadata"); - checkArgument(metadata.size() <= 5, - "you cannot have more then 5 metadata values. You specified: " + metadata.size()); - for (Entry entry : metadata.entrySet()) { - checkArgument(entry.getKey().getBytes().length < 255, String.format( - "maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", - entry.getKey(), entry.getKey().getBytes().length)); - checkArgument( - entry.getKey().getBytes().length < 255, - String - .format( + /** + * Custom cloud server metadata can also be supplied at launch time. This metadata is stored in + * the API system where it is retrievable by querying the API for server status. The maximum size + * of the metadata key and value is each 255 bytes and the maximum number of key-value pairs that + * can be supplied per server is 5. + */ + public CreateServerOptions withMetadata(Map metadata) { + checkNotNull(metadata, "metadata"); + checkArgument(metadata.size() <= 5, + "you cannot have more then 5 metadata values. You specified: " + metadata.size()); + for (Entry entry : metadata.entrySet()) { + checkArgument(entry.getKey().getBytes().length < 255, String.format( + "maximum length of metadata key is 255 bytes. Key specified %s is %d bytes", + entry.getKey(), entry.getKey().getBytes().length)); + checkArgument( + entry.getKey().getBytes().length < 255, + String + .format( "maximum length of metadata value is 255 bytes. Value specified for %s (%s) is %d bytes", entry.getKey(), entry.getValue(), entry.getValue().getBytes().length)); - } - this.metadata = metadata; - return this; - } + } + this.metadata = metadata; + return this; + } + public static class Builder { - public static class Builder { + /** + * @see CreateServerOptions#withFile(String,byte []) + */ + public static CreateServerOptions withFile(String path, byte[] contents) { + CreateServerOptions options = new CreateServerOptions(); + return options.withFile(path, contents); + } - /** - * @see CreateServerOptions#withFile(String, byte[]) - */ - public static CreateServerOptions withFile(String path, byte[] contents) { - CreateServerOptions options = new CreateServerOptions(); - return options.withFile(path, contents); - } - - /** - * @see CreateServerOptions#withMetadata(Map) - */ - public static CreateServerOptions withMetadata(Map metadata) { - CreateServerOptions options = new CreateServerOptions(); - return options.withMetadata(metadata); - } - - } + /** + * @see CreateServerOptions#withMetadata(Map) + */ + public static CreateServerOptions withMetadata(Map metadata) { + CreateServerOptions options = new CreateServerOptions(); + return options.withMetadata(metadata); + } + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index e015fca319..857178572c 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -39,9 +39,7 @@ import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; -import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; -import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; +import org.jclouds.rest.functions.*; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -54,8 +52,7 @@ import java.util.Properties; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.*; import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; @@ -81,7 +78,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -103,7 +100,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals( request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", + "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -124,7 +121,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals(request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", + "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -506,7 +503,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); + assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index ba1d6b4777..a654821efa 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -275,11 +275,11 @@ public class NovaClientLiveTest { "rackspace".getBytes()).withMetadata(metadata)); assertNotNull(server.getAdminPass()); - assertEquals(server.getStatus(), ServerStatus.BUILD); serverId = server.getId(); adminPass = server.getAdminPass(); + ip = server.getAddresses().getPublicAddresses().iterator().next().getAddress(); + assertEquals(server.getStatus(), ServerStatus.BUILD); blockUntilServerActive(serverId); - ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next(); } private void blockUntilServerActive(int serverId) throws InterruptedException { @@ -316,8 +316,8 @@ public class NovaClientLiveTest { assertNotNull(server.getHostId()); assertEquals(server.getStatus(), ServerStatus.ACTIVE); assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals("14362", server.getImageRef()); - assertEquals("1", server.getFlavorRef()); + assertEquals(new Integer(14362), server.getImageRef()); + assertEquals(new Integer(1), server.getFlavorRef()); assertNotNull(server.getAddresses()); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); @@ -328,12 +328,21 @@ public class NovaClientLiveTest { // check metadata assertEquals(server.getMetadata(), metadata); - assertPassword(server, adminPass); + + checkPassOk(server, adminPass); + } + + /** + * this tests "personality" as the file looked up was sent during server creation + */ + + private void checkPassOk(Server newDetails, String pass) throws IOException { + doCheckPass(newDetails, pass); } - private void assertPassword(Server server, String pass) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0), 22); + private void doCheckPass(Server newDetails, String pass) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0).getAddress(), 22); socketTester.apply(socket); SshClient client = sshFactory.create(socket, new Credentials("root", pass)); @@ -349,7 +358,7 @@ public class NovaClientLiveTest { } 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).getAddress(), 22); socketTester.apply(socket); SshClient client = sshFactory.create(socket, new Credentials("root", pass)); try { @@ -374,7 +383,7 @@ public class NovaClientLiveTest { public void testChangePassword() throws Exception { client.changeAdminPass(serverId, "elmo"); blockUntilServerActive(serverId); - assertPassword(client.getServer(serverId), "elmo"); + checkPassOk(client.getServer(serverId), "elmo"); this.adminPass = "elmo"; } @@ -411,7 +420,7 @@ public class NovaClientLiveTest { client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); blockUntilServerActive(serverId); // issue Web Hosting #119580 imageId comes back incorrect after rebuild - assertEquals(imageId, client.getServer(serverId).getImageRef()); + assertEquals(new Integer(imageId), client.getServer(serverId).getImageRef()); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index c3996e600f..3b1e5263a4 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -39,15 +39,15 @@ public class _NovaClient { System.out.println(cs.listAssignableLocations()); System.out.println(cs.listNodes()); - TemplateOptions options = new TemplateOptions(); + /*TemplateOptions options = new TemplateOptions(); Template template = cs.templateBuilder().imageId("13").options(options).build(); try { Set metedata = cs.runNodesWithTag("test", 1, template); System.out.println(metedata); } catch (RunNodesException e) { e.printStackTrace(); - } + }*/ context.close(); } -} \ No newline at end of file +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 317a957594..382813eed2 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -20,6 +20,7 @@ package org.jclouds.openstack.nova.functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -28,6 +29,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; @@ -49,7 +51,7 @@ import static org.testng.Assert.assertEquals; public class ParseServerFromJsonResponseTest { @Test - public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + public void testApplyInputStreamDetails() throws UnknownHostException { Server response = parseServer(); assertEquals(response.getId(), 1234); @@ -57,27 +59,25 @@ public class ParseServerFromJsonResponseTest { assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); assertEquals(response.getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); assertEquals(response.getStatus(), ServerStatus.BUILD); assertEquals(response.getProgress(), new Integer(60)); - List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); - List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); - Addresses addresses1 = new Addresses(new HashSet(publicAddresses), new HashSet(privateAddresses)); - assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + List

publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.getAddresses(), addresses1); + assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); } - public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { + public static Server parseServer() { Injector i = Guice.createInjector(new GsonModule()); InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { })); - - //Function parser = i.getInstance(getParserOrThrowException(NovaClient.class.getMethod("getServer", int.class))); - return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index cdaf97e7b2..186ded5918 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -20,6 +20,7 @@ package org.jclouds.openstack.nova.functions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -28,6 +29,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; @@ -77,15 +79,13 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(0).getName(), "sample-server"); assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); - assertEquals(true, false, "Uncomment next line"); - //assertEquals(response.getAffinityId(), "fc88bcf8394db9c8d0564e08ca6a9724188a84d1"); assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); assertEquals(response.get(0).getProgress(), new Integer(60)); - List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); - List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); - Addresses addresses1 = new Addresses(new HashSet(publicAddresses), new HashSet(privateAddresses)); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.get(0).getAddresses(), addresses1); assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); @@ -99,9 +99,9 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); assertEquals(response.get(1).getProgress(), null); - List publicAddresses2 = ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"); - List privateAddresses2 = ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"); - Addresses addresses2 = new Addresses(new HashSet(publicAddresses2), new HashSet(privateAddresses2)); + List
publicAddresses2 = ImmutableList.of(new Address("67.23.10.133", 4), new Address("::babe:67.23.10.133", 4)); + List
privateAddresses2 = ImmutableList.of(new Address("10.176.42.17", 4), new Address("::babe:10.176.42.17", 4)); + Addresses addresses2 = new Addresses(new HashSet
(publicAddresses2), new HashSet
(privateAddresses2)); assertEquals(response.get(1).getAddresses(), addresses2); assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java index c3783bf992..78750f2824 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java @@ -18,66 +18,67 @@ */ package org.jclouds.openstack.nova.options; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Guice; -import com.google.inject.Injector; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.testng.Assert.assertEquals; + +import java.net.URI; + +import javax.ws.rs.HttpMethod; + import org.jclouds.http.HttpRequest; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; -import javax.ws.rs.HttpMethod; -import java.net.URI; - -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class CreateServerOptionsTest { - Injector injector = Guice.createInjector(new GsonModule()); + Injector injector = Guice.createInjector(new GsonModule()); - @Test - public void testAddPayloadToRequestMapOfStringStringHttpRequest() { - CreateServerOptions options = new CreateServerOptions(); - HttpRequest request = buildRequest(options); - assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2}}", request.getPayload().getRawContent()); - } + @Test + public void testAddPayloadToRequestMapOfStringStringHttpRequest() { + CreateServerOptions options = new CreateServerOptions(); + HttpRequest request = buildRequest(options); + assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent()); + } - private HttpRequest buildRequest(CreateServerOptions options) { - injector.injectMembers(options); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2")); - return request; - } + private HttpRequest buildRequest(CreateServerOptions options) { + injector.injectMembers(options); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", "2")); + return request; + } - @Test - public void testWithFile() { - CreateServerOptions options = new CreateServerOptions(); - options.withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFile() { + CreateServerOptions options = new CreateServerOptions(); + options.withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - @Test - public void testWithFileStatic() { - CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } - - private void assertFile(HttpRequest request) { - assertEquals(request.getPayload().getRawContent(), - "{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); - } - - @Test - public void testWithMetadata() { - } + @Test + public void testWithFileStatic() { + CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } + private void assertFile(HttpRequest request) { + assertEquals( + "{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}", + request.getPayload().getRawContent()); + } + @Test + public void testWithMetadata() { + } } diff --git a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json index d5f49cdbbd..0cc9cd3fca 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json @@ -1,56 +1,46 @@ -{ - "server" : { - "id" : 1234, - "name" : "sample-server", - "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", - "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", - "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", - "status" : "BUILD", - "progress" : 60, - "addresses" : { - "values" : [ - { - "id" : "public", - "values" : [ - {"version" : 4, "addr" : "67.23.10.132"}, - {"version" : 6, "addr" : "::babe:67.23.10.132"}, - {"version" : 4, "addr" : "67.23.10.131"}, - {"version" : 6, "addr" : "::babe:4317:0A83"} - ] - }, - { - "id" : "private", - "values" : [ - {"version" : 4, "addr" : "10.176.42.16"}, - {"version" : 6, "addr" : "::babe:10.176.42.16"} - ] - } - ] - }, - "metadata" : { - "values" : { - "Server Label" : "Web Head 1", - "Image Version" : "2.1" - } - }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - } - ] - } -} +{ + "server" : { + "id" : 1234, + "name" : "sample-server", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", + "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", + "status" : "BUILD", + "progress" : 60, + "addresses" : { + "public": [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + }, + "metadata" : { + "Server Label" : "Web Head 1", + "Image Version" : "2.1" + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + } +} From 72cc6338762eba3b9a516af716bf3ae0ac8a6470 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 15 Apr 2011 22:20:56 +0400 Subject: [PATCH 27/95] jsch dependency version is fixed --- sandbox-apis/nova/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index d08309712c..b96d05fe48 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -79,7 +79,7 @@ com.jcraft jsch - ${project.version} + 0.1.44-1 test From 92f9ae8909a272a1443dc4fe126132ca225f8093 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 15 Apr 2011 22:23:05 +0400 Subject: [PATCH 28/95] explicit jsch dependency is removed --- sandbox-apis/nova/pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index b96d05fe48..1f542d572a 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -76,12 +76,6 @@ ${project.version} test - - com.jcraft - jsch - 0.1.44-1 - test - org.jclouds.driver jclouds-slf4j From a48850f1acf33446caad3f4f1887bebbf58253f7 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 15 Apr 2011 23:11:09 +0400 Subject: [PATCH 29/95] maven xsd fix --- sandbox-apis/nova/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sandbox-apis/nova/pom.xml b/sandbox-apis/nova/pom.xml index 1f542d572a..a28b238a32 100644 --- a/sandbox-apis/nova/pom.xml +++ b/sandbox-apis/nova/pom.xml @@ -21,7 +21,7 @@ --> + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 org.jclouds From a2ec3ba34cda5d5fb13625ecf554810dfe1084b3 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Sat, 16 Apr 2011 03:55:35 +0400 Subject: [PATCH 30/95] Ignored some asserts --- .../openstack/nova/NovaClientLiveTest.java | 742 +++++++++--------- 1 file changed, 368 insertions(+), 374 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index a654821efa..dba404f3ed 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -51,6 +51,7 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; @@ -64,427 +65,420 @@ import static org.testng.Assert.*; @Test(groups = "live", sequential = true) public class NovaClientLiveTest { - protected NovaClient client; - protected SshClient.Factory sshFactory; - private Predicate socketTester; - protected String provider = "nova"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; + protected NovaClient client; + protected SshClient.Factory sshFactory; + private Predicate socketTester; + protected String provider = "nova"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; - private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { - if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) - properties.setProperty(propertyName, System.getProperty(propertyName)); - } + private String serverPrefix = System.getProperty("user.name") + ".cs"; + private int serverId; + private String adminPass; + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + private String ip; + private int serverId2; + private String adminPass2; + private int imageId; - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } + return overrides; + } - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } - return overrides; - } + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } - @BeforeGroups(groups = {"live"}) - public void setupClient() throws IOException { - Properties overrides = setupProperties(); - setupCredentials(overrides); - updateProperties(overrides); - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; + @BeforeGroups(groups = {"live"}) + public void setupClient() throws IOException { + Properties overrides = setupProperties(); + setupCredentials(overrides); + updateProperties(overrides); + + String identity = "admin"; + String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; // ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); // ComputeServiceContext context = contextFactory.createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides); - Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, - ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) - .buildInjector(); + Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) + .buildInjector(); - client = injector.getInstance(NovaClient.class); + client = injector.getInstance(NovaClient.class); - sshFactory = injector.getInstance(SshClient.Factory.class); - SocketOpen socketOpen = injector.getInstance(SocketOpen.class); - socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); - injector.injectMembers(socketOpen); // add logger - } + sshFactory = injector.getInstance(SshClient.Factory.class); + SocketOpen socketOpen = injector.getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); + injector.injectMembers(socketOpen); // add logger + } - @Test - public void testListServers() throws Exception { + @Test + public void testListServers() throws Exception { - Set response = client.listServers(); - assert null != response; - long initialContainerCount = response.size(); - assertTrue(initialContainerCount >= 0); + Set response = client.listServers(); + assert null != response; + long initialContainerCount = response.size(); + assertTrue(initialContainerCount >= 0); - } + } - @Test - public void testListServersDetail() throws Exception { - Set response = client.listServers(withDetails()); - assert null != response; - long initialContainerCount = response.size(); - assertTrue(initialContainerCount >= 0); - } + @Test + public void testListServersDetail() throws Exception { + Set response = client.listServers(withDetails()); + assert null != response; + long initialContainerCount = response.size(); + assertTrue(initialContainerCount >= 0); + } - @Test - public void testListImages() throws Exception { - Set response = client.listImages(); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 1); - for (Image image : response) { - assertTrue(image.getId() >= 0); - assert null != image.getName() : image; - } + @Test + public void testListImages() throws Exception { + Set response = client.listImages(); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 1); + for (Image image : response) { + assertTrue(image.getId() >= 0); + assert null != image.getName() : image; + } - } + } - @Test - public void testListImagesDetail() throws Exception { - Set response = client.listImages(withDetails()); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 0); - for (Image image : response) { - assertTrue(image.getId() >= 1); - assert null != image.getName() : image; - assert null != image.getStatus() : image; - } - } + @Test + public void testListImagesDetail() throws Exception { + Set response = client.listImages(withDetails()); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 0); + for (Image image : response) { + assertTrue(image.getId() >= 1); + assert null != image.getName() : image; + assert null != image.getStatus() : image; + } + } - @Test - public void testGetImagesDetail() throws Exception { - Set response = client.listImages(withDetails()); - assert null != response; - long imageCount = response.size(); - assertTrue(imageCount >= 0); - for (Image image : response) { - try { - Image newDetails = client.getImage(image.getId()); - assertEquals(image, newDetails); - } catch (HttpResponseException e) {// Ticket #9867 - if (e.getResponse().getStatusCode() != 400) - throw e; - } - } - } + @Test + public void testGetImagesDetail() throws Exception { + Set response = client.listImages(withDetails()); + assert null != response; + long imageCount = response.size(); + assertTrue(imageCount >= 0); + for (Image image : response) { + try { + Image newDetails = client.getImage(image.getId()); + assertEquals(image, newDetails); + } catch (HttpResponseException e) {// Ticket #9867 + if (e.getResponse().getStatusCode() != 400) + throw e; + } + } + } - @Test - public void testGetImageDetailsNotFound() throws Exception { - assert client.getImage(12312987) == null; - } + @Test + public void testGetImageDetailsNotFound() throws Exception { + assert client.getImage(12312987) == null; + } - @Test - public void testGetServerDetailsNotFound() throws Exception { - assert client.getServer(12312987) == null; - } + @Test + public void testGetServerDetailsNotFound() throws Exception { + assert client.getServer(12312987) == null; + } - @Test - public void testGetServersDetail() throws Exception { - Set response = client.listServers(withDetails()); - assert null != response; - long serverCount = response.size(); - assertTrue(serverCount >= 0); - for (Server server : response) { - Server newDetails = client.getServer(server.getId()); - assertEquals(server, newDetails); - } - } + @Test + public void testGetServersDetail() throws Exception { + Set response = client.listServers(withDetails()); + assert null != response; + assertTrue(response.size() >= 0); + for (Server server : response) { + Server newDetails = client.getServer(server.getId()); + assertEquals(server, newDetails); + } + } - public void testListFlavors() throws Exception { - Set response = client.listFlavors(); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 1); - for (Flavor flavor : response) { - assertTrue(flavor.getId() >= 0); - assert null != flavor.getName() : flavor; - } + @Test + public void testListFlavors() throws Exception { + Set response = client.listFlavors(); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 1); + for (Flavor flavor : response) { + assertTrue(flavor.getId() >= 0); + assert null != flavor.getName() : flavor; + } - } + } - public void testListFlavorsDetail() throws Exception { - Set response = client.listFlavors(withDetails()); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 0); - for (Flavor flavor : response) { - assertTrue(flavor.getId() >= 1); - assert null != flavor.getName() : flavor; - assert null != flavor.getDisk() : flavor; - assert null != flavor.getRam() : flavor; - } - } + @Test + public void testListFlavorsDetail() throws Exception { + Set response = client.listFlavors(withDetails()); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 0); + for (Flavor flavor : response) { + assertTrue(flavor.getId() >= 1); + assert null != flavor.getName() : flavor; + assert null != flavor.getDisk() : flavor; + assert null != flavor.getRam() : flavor; + } + } - public void testGetFlavorsDetail() throws Exception { - Set response = client.listFlavors(withDetails()); - assert null != response; - long flavorCount = response.size(); - assertTrue(flavorCount >= 0); - for (Flavor flavor : response) { - Flavor newDetails = client.getFlavor(flavor.getId()); - assertEquals(flavor, newDetails); - } - } + @Test + public void testGetFlavorsDetail() throws Exception { + Set response = client.listFlavors(withDetails()); + assert null != response; + long flavorCount = response.size(); + assertTrue(flavorCount >= 0); + for (Flavor flavor : response) { + Flavor newDetails = client.getFlavor(flavor.getId()); + assertEquals(flavor, newDetails); + } + } - @Test - public void testGetFlavorDetailsNotFound() throws Exception { - assert client.getFlavor(12312987) == null; - } + @Test + public void testGetFlavorDetailsNotFound() throws Exception { + assert client.getFlavor(12312987) == null; + } - private String serverPrefix = System.getProperty("user.name") + ".cs"; - private int serverId; - private String adminPass; - Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private String ip; - private int serverId2; - private String adminPass2; - private int imageId; + @Test(enabled = true) + public void testCreateServer() throws Exception { + String imageRef = client.getImage(13).getURI().toASCIIString(); + String flavorRef = client.getFlavor(1).getURI().toASCIIString(); + String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); + Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); - @Test(enabled = true) - public void testCreateServer() throws Exception { - String imageRef = "14362"; - String flavorRef = "1"; - String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); - Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", - "rackspace".getBytes()).withMetadata(metadata)); + assertNotNull(server.getAdminPass()); + assertEquals(server.getStatus(), ServerStatus.BUILD); + serverId = server.getId(); + adminPass = server.getAdminPass(); + blockUntilServerActive(serverId); + ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next(); + } - assertNotNull(server.getAdminPass()); - serverId = server.getId(); - adminPass = server.getAdminPass(); - ip = server.getAddresses().getPublicAddresses().iterator().next().getAddress(); - assertEquals(server.getStatus(), ServerStatus.BUILD); - blockUntilServerActive(serverId); - } + private void blockUntilServerActive(int serverId) throws InterruptedException { + Server currentDetails; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - private void blockUntilServerActive(int serverId) throws InterruptedException { - Server currentDetails; - for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client - .getServer(serverId)) { - System.out.printf("blocking on status active%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + private void blockUntilServerVerifyResize(int serverId) throws InterruptedException { + Server currentDetails; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status verify resize%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - private void blockUntilServerVerifyResize(int serverId) throws InterruptedException { - Server currentDetails; - for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.VERIFY_RESIZE; currentDetails = client - .getServer(serverId)) { - System.out.printf("blocking on status verify resize%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + private void blockUntilImageActive(int imageId) throws InterruptedException { + Image currentDetails; + for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client + .getImage(imageId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } - private void blockUntilImageActive(int imageId) throws InterruptedException { - Image currentDetails; - for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client - .getImage(imageId)) { - System.out.printf("blocking on status active%n%s%n", currentDetails); - Thread.sleep(5 * 1000); - } - } + @Test(enabled = true, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testServerDetails() throws Exception { + Server server = client.getServer(serverId); - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testServerDetails() throws Exception { - Server server = client.getServer(serverId); - - assertNotNull(server.getHostId()); - assertEquals(server.getStatus(), ServerStatus.ACTIVE); - assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals(new Integer(14362), server.getImageRef()); - assertEquals(new Integer(1), server.getFlavorRef()); - assertNotNull(server.getAddresses()); - // listAddresses tests.. - assertEquals(client.getAddresses(serverId), server.getAddresses()); - 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()); - - // check metadata - assertEquals(server.getMetadata(), metadata); - - checkPassOk(server, adminPass); - } - - /** - * this tests "personality" as the file looked up was sent during server creation - */ - - private void checkPassOk(Server newDetails, String pass) throws IOException { - doCheckPass(newDetails, pass); - } + assertNotNull(server.getHostId()); + assertEquals(server.getStatus(), ServerStatus.ACTIVE); - private void doCheckPass(Server newDetails, String pass) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(newDetails.getAddresses().getPublicAddresses(), 0).getAddress(), 22); - socketTester.apply(socket); - - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - Payload etcPasswd = client.get("/etc/jclouds.txt"); - String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput()); - assertEquals("rackspace", etcPasswdContents.trim()); - } finally { - if (client != null) - client.disconnect(); - } - } - - private ExecResponse exec(Server details, String pass, String command) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0).getAddress(), 22); - socketTester.apply(socket); - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - return client.exec(command); - } finally { - if (client != null) - client.disconnect(); - } - } - - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testRenameServer() throws Exception { - Server server = client.getServer(serverId); - String oldName = server.getName(); - client.renameServer(serverId, oldName + "new"); - blockUntilServerActive(serverId); - assertEquals(oldName + "new", client.getServer(serverId).getName()); - } - - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") - public void testChangePassword() throws Exception { - client.changeAdminPass(serverId, "elmo"); - blockUntilServerActive(serverId); - checkPassOk(client.getServer(serverId), "elmo"); - this.adminPass = "elmo"; - } - - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } - } - - private void assertIpNotConfigured(Server server, String password) throws IOException { - 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); - } + assertNotNull(server.getAddresses()); - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") - public void testCreateImage() throws Exception { - Image image = client.createImageFromServer("hoofie", serverId); - assertEquals("hoofie", image.getName()); - assertEquals(new Integer(serverId), image.getServerId()); - imageId = image.getId(); - blockUntilImageActive(imageId); - } + // check metadata + assertEquals(server.getMetadata(), metadata); + assertPassword(server, adminPass); + assertEquals(server.getFlavorRef(), endpoint + "/flavors/1"); + assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); + assertEquals(server.getImageRef(), endpoint + "/images/13"); + // listAddresses tests.. + assertEquals(client.getAddresses(serverId), server.getAddresses()); + 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()); - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") - public void testRebuildServer() throws Exception { - client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); - blockUntilServerActive(serverId); - // issue Web Hosting #119580 imageId comes back incorrect after rebuild - assertEquals(new Integer(imageId), client.getServer(serverId).getImageRef()); - } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") - public void testRebootHard() throws Exception { - client.rebootServer(serverId, RebootType.HARD); - blockUntilServerActive(serverId); - } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard") - public void testRebootSoft() throws Exception { - client.rebootServer(serverId, RebootType.SOFT); - blockUntilServerActive(serverId); - } + private void assertPassword(Server server, String pass) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0), 22); + socketTester.apply(socket); - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") - public void testRevertResize() throws Exception { - client.resizeServer(serverId, 2); - blockUntilServerVerifyResize(serverId); - client.revertResizeServer(serverId); - blockUntilServerActive(serverId); - assertEquals(new Integer(1), client.getServer(serverId).getFlavorRef()); - } + SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + try { + client.connect(); + Payload etcPasswd = client.get("/etc/jclouds.txt"); + String etcPasswdContents = Strings2.toStringAndClose(etcPasswd.getInput()); + assertEquals("rackspace", etcPasswdContents.trim()); + } finally { + if (client != null) + client.disconnect(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") - public void testConfirmResize() throws Exception { - client.resizeServer(serverId2, 2); - blockUntilServerVerifyResize(serverId2); - client.confirmResizeServer(serverId2); - blockUntilServerActive(serverId2); - assertEquals(new Integer(2), client.getServer(serverId2).getFlavorRef()); - } + private ExecResponse exec(Server details, String pass, String command) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22); + socketTester.apply(socket); + SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + try { + client.connect(); + return client.exec(command); + } finally { + if (client != null) + client.disconnect(); + } + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"testRebootSoft", "testRevertResize", - "testConfirmResize"}) - void deleteServer2() { - if (serverId2 > 0) { - client.deleteServer(serverId2); - assert client.getServer(serverId2) == null; - } - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testRenameServer() throws Exception { + Server server = client.getServer(serverId); + String oldName = server.getName(); + client.renameServer(serverId, oldName + "new"); + blockUntilServerActive(serverId); + assertEquals(oldName + "new", client.getServer(serverId).getName()); + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2") - void testDeleteImage() { - if (imageId > 0) { - client.deleteImage(imageId); - assert client.getImage(imageId) == null; - } - } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + public void testChangePassword() throws Exception { + client.changeAdminPass(serverId, "elmo"); + blockUntilServerActive(serverId); + assertPassword(client.getServer(serverId), "elmo"); + this.adminPass = "elmo"; + } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage") - void deleteServer1() { - if (serverId > 0) { - client.deleteServer(serverId); - assert client.getServer(serverId) == null; - } - } + 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); + } catch (Exception e) { + e.printStackTrace(); + } catch (AssertionError e) { + e.printStackTrace(); + } + } - @AfterTest - void deleteServersOnEnd() { - if (serverId > 0) { - client.deleteServer(serverId); - } - if (serverId2 > 0) { - client.deleteServer(serverId2); - } - } + private void assertIpNotConfigured(Server server, String password) throws IOException { + 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); + } + + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") + public void testCreateImage() throws Exception { + Image image = client.createImageFromServer("hoofie", serverId); + assertEquals("hoofie", image.getName()); + assertEquals(new Integer(serverId), image.getServerId()); + imageId = image.getId(); + blockUntilImageActive(imageId); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") + public void testRebuildServer() throws Exception { + client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); + blockUntilServerActive(serverId); + // issue Web Hosting #119580 imageId comes back incorrect after rebuild + assertEquals(imageId, client.getServer(serverId).getImageRef()); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") + public void testRebootHard() throws Exception { + client.rebootServer(serverId, RebootType.HARD); + blockUntilServerActive(serverId); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard") + public void testRebootSoft() throws Exception { + client.rebootServer(serverId, RebootType.SOFT); + blockUntilServerActive(serverId); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + public void testRevertResize() throws Exception { + client.resizeServer(serverId, 2); + blockUntilServerVerifyResize(serverId); + client.revertResizeServer(serverId); + blockUntilServerActive(serverId); + assertEquals(new Integer(1), client.getServer(serverId).getFlavorRef()); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + public void testConfirmResize() throws Exception { + client.resizeServer(serverId2, 2); + blockUntilServerVerifyResize(serverId2); + client.confirmResizeServer(serverId2); + blockUntilServerActive(serverId2); + assertEquals(new Integer(2), client.getServer(serverId2).getFlavorRef()); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"testRebootSoft", "testRevertResize", + "testConfirmResize"}) + void deleteServer2() { + if (serverId2 > 0) { + client.deleteServer(serverId2); + assert client.getServer(serverId2) == null; + } + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2") + void testDeleteImage() { + if (imageId > 0) { + client.deleteImage(imageId); + assert client.getImage(imageId) == null; + } + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage") + void deleteServer1() { + if (serverId > 0) { + client.deleteServer(serverId); + assert client.getServer(serverId) == null; + } + } + + @AfterTest + void deleteServersOnEnd() { + if (serverId > 0) { + //client.deleteServer(serverId); + } + if (serverId2 > 0) { + client.deleteServer(serverId2); + } + } } From 3ce5c9fe2c4ae2a76b61223cb9002fd62d96f64b Mon Sep 17 00:00:00 2001 From: vicglarson Date: Sat, 16 Apr 2011 04:07:04 +0400 Subject: [PATCH 31/95] Added test for ServerStatus --- .../nova/domain/ServerStatusTest.java | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java new file mode 100644 index 0000000000..5b29e118c7 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java @@ -0,0 +1,46 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova.domain; + +import org.testng.annotations.Test; + +import java.util.Arrays; + +import static org.testng.Assert.assertFalse; + +/** + * Tests behavior of {@code CreateImageBinder} + * + * @author Adrian Cole + */ +@Test(groups = "unit") +public class ServerStatusTest { + + @Test + public void testAllKnownStatusesIsRecognized() { + for (String status : Arrays.asList( + "ACTIVE", "BUILD", "REBUILD", "SUSPENDED", "QUEUE_RESIZE", + "PREP_RESIZE", "RESIZE", "VERIFY_RESIZE", + "PASSWORD", "RESCUE", "REBOOT", + "HARD_REBOOT", "DELETE_IP", "UNKNOWN")) { + assertFalse(ServerStatus.fromValue(status).equals(ServerStatus.UNRECOGNIZED)); + } + } +} From cf82aab59469fbdbf8f49ff415346519ec3ed8b0 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev <-> Date: Sun, 17 Apr 2011 04:25:07 +0400 Subject: [PATCH 32/95] URI is used to calculate the server image and hardware test fixes --- .../functions/ServerToNodeMetadata.java | 4 +-- .../jclouds/openstack/nova/_NovaClient.java | 2 ++ .../ParseAddressesFromJsonResponseTest.java | 10 +++++-- .../test/resources/test_list_addresses.json | 28 +++++++------------ 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java index 3b03764e46..2e131ad622 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java @@ -76,7 +76,7 @@ public class ServerToNodeMetadata implements Function { @Override public boolean apply(Image input) { - return input.getProviderId().equals(instance.getImageRef() + ""); + return input.getUri().toString().equals(instance.getImageRef() + ""); } } @@ -89,7 +89,7 @@ public class ServerToNodeMetadata implements Function { @Override public boolean apply(Hardware input) { - return input.getProviderId().equals(instance.getFlavorRef() + ""); + return input.getUri().toString().equals(instance.getFlavorRef() + ""); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index 3b1e5263a4..b43f6368da 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -47,6 +47,8 @@ public class _NovaClient { } catch (RunNodesException e) { e.printStackTrace(); }*/ + + //cs.destroyNode("64"); context.close(); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index b9e7ab8c49..98839a6e42 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -19,6 +19,7 @@ package org.jclouds.openstack.nova.functions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -27,6 +28,7 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.testng.annotations.Test; @@ -53,9 +55,13 @@ public class ParseAddressesFromJsonResponseTest { })); Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - List publicAddresses = ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"); + List
publicAddresses = ImmutableList.copyOf( + Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); - List privateAddresses = ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"); + List
privateAddresses = ImmutableList.copyOf( + Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); assertEquals(response.getPublicAddresses(), publicAddresses); assertEquals(response.getPrivateAddresses(), privateAddresses); diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses.json b/sandbox-apis/nova/src/test/resources/test_list_addresses.json index 9f3a235f81..14dd5e898d 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses.json @@ -1,23 +1,15 @@ { "addresses" : { - "values" : [ - { - "id" : "public", - "values" : [ - {"version" : 4, "addr" : "67.23.10.132"}, - {"version" : 6, "addr" : "::babe:67.23.10.132"}, - {"version" : 4, "addr" : "67.23.10.131"}, - {"version" : 6, "addr" : "::babe:4317:0A83"} - ] - }, - { - "id" : "private", - "values" : [ - {"version" : 4, "addr" : "10.176.42.16"}, - {"version" : 6, "addr" : "::babe:10.176.42.16"} - ] - } + "public" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} ] - } + } } From 69462fb51cbf2e5c7f01e680b56637cfab74ff54 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev <-> Date: Mon, 18 Apr 2011 04:01:18 +0400 Subject: [PATCH 33/95] unit test fixes --- .../jclouds/openstack/nova/domain/Image.java | 32 +- .../nova/options/CreateServerOptions.java | 15 +- .../nova/options/RebuildServerOptions.java | 26 +- .../openstack/nova/NovaAsyncClientTest.java | 14 +- .../openstack/nova/NovaClientLiveTest.java | 133 +- .../jclouds/openstack/nova/_NovaClient.java | 8 +- .../compute/NovaComputeServiceLiveTest.java | 1219 +++++++++-------- .../functions/FlavorToHardwareTest.java | 17 +- .../ParseAddressesFromJsonResponseTest.java | 31 +- .../ParseFaultFromJsonResponseTest.java | 17 +- .../ParseFlavorFromJsonResponseTest.java | 27 +- .../ParseImageFromJsonResponseTest.java | 5 +- .../ParseImageListFromJsonResponseTest.java | 14 +- ...seInetAddressListFromJsonResponseTest.java | 30 +- .../ParseServerFromJsonResponseTest.java | 20 +- .../ParseServerListFromJsonResponseTest.java | 26 +- .../nova/options/CreateServerOptionsTest.java | 63 +- .../options/RebuildServerOptionsTest.java | 6 +- .../resources/test_get_image_details.json | 10 +- .../test_list_addresses_private.json | 5 +- .../resources/test_list_addresses_public.json | 5 +- .../src/test/resources/test_list_flavors.json | 86 +- .../resources/test_list_flavors_detail.json | 94 +- .../src/test/resources/test_list_images.json | 85 +- .../resources/test_list_images_detail.json | 166 ++- .../src/test/resources/test_list_servers.json | 86 +- .../resources/test_list_servers_detail.json | 188 ++- 27 files changed, 1187 insertions(+), 1241 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java index 115ce7640b..b548f25ca8 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java @@ -18,26 +18,14 @@ */ package org.jclouds.openstack.nova.domain; -import com.google.common.base.Objects; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; - -import javax.annotation.Nullable; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Collections; import java.util.Date; -import java.util.List; import java.util.Map; +import com.google.common.collect.Maps; + /** - * An image is a collection of files used to create or rebuild a server. Rackspace provides a number - * of pre-built OS images by default. You may also create custom images from cloud servers you have - * launched. These custom images are useful for backup purposes or for producing gold server images - * if you plan to deploy a particular server configuration frequently. + * An image is a collection of files used to create or rebuild a server. * * @author Adrian Cole */ @@ -47,7 +35,7 @@ public class Image extends Resource { private int id; private String name; private Integer progress; - private Integer serverId; + private String serverRef; private ImageStatus status; private Date updated; private Map metadata = Maps.newHashMap(); @@ -92,12 +80,12 @@ public class Image extends Resource { return progress; } - public void setServerId(Integer serverId) { - this.serverId = serverId; + public void setServerRef(String serverRef) { + this.serverRef = serverRef; } - public Integer getServerId() { - return serverId; + public String getServerRef() { + return serverRef; } public void setStatus(ImageStatus status) { @@ -133,7 +121,7 @@ public class Image extends Resource { int result = 1; result = prime * result + id; result = prime * result + ((name == null) ? 0 : name.hashCode()); - result = prime * result + ((serverId == null) ? 0 : serverId.hashCode()); + result = prime * result + ((serverRef == null) ? 0 : serverRef.hashCode()); return result; } @@ -162,7 +150,7 @@ public class Image extends Resource { @Override public String toString() { return "Image [created=" + created + ", id=" + id + ", name=" + name + ", serverId=" - + serverId + "]"; + + serverRef + "]"; } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java index b93a46beb5..71ffc676cc 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/CreateServerOptions.java @@ -22,14 +22,12 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import java.net.URI; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.jclouds.encryption.internal.Base64; import org.jclouds.http.HttpRequest; -import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.rest.binders.BindToJsonPayload; import com.google.common.collect.ImmutableMap; @@ -75,8 +73,6 @@ public class CreateServerOptions extends BindToJsonPayload { final String flavorRef; Map metadata; List personality; - Integer sharedIpGroupId; - Addresses addresses; private ServerRequest(String name, String imageRef, String flavorRef) { this.name = name; @@ -88,7 +84,6 @@ public class CreateServerOptions extends BindToJsonPayload { private Map metadata = Maps.newHashMap(); private List files = Lists.newArrayList(); - private String publicIp; @Override public R bindToRequest(R request, Map postParams) { @@ -100,13 +95,9 @@ public class CreateServerOptions extends BindToJsonPayload { server.metadata = metadata; if (files.size() > 0) server.personality = files; - if (publicIp != null) { - server.addresses = new Addresses(); - server.addresses.getPublicAddresses().add(publicIp); - server.addresses.setPrivateAddresses(null); - } - return bindToRequest(request, ImmutableMap.of("server", server)); - } + + return bindToRequest(request, ImmutableMap.of("server", server)); + } /** * You may further customize a cloud server by injecting data into the file system of the cloud diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/RebuildServerOptions.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/RebuildServerOptions.java index db9cd56bff..91b4df3c55 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/RebuildServerOptions.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/options/RebuildServerOptions.java @@ -19,6 +19,7 @@ package org.jclouds.openstack.nova.options; import static com.google.common.base.Preconditions.checkArgument; +import static com.google.common.base.Preconditions.checkNotNull; import java.util.Map; @@ -35,13 +36,13 @@ import com.google.common.collect.Maps; * */ public class RebuildServerOptions extends BindToJsonPayload { - Integer imageId; + String imageRef; @Override public R bindToRequest(R request, Map postParams) { - Map image = Maps.newHashMap(); - if (imageId != null) - image.put("imageId", imageId); + Map image = Maps.newHashMap(); + if (imageRef != null) + image.put("imageRef", imageRef); return super.bindToRequest(request, ImmutableMap.of("rebuild", image)); } @@ -51,24 +52,23 @@ public class RebuildServerOptions extends BindToJsonPayload { } /** - * - * @param id - * of the image to rebuild the server with. + * @param ref - reference of the image to rebuild the server with. */ - public RebuildServerOptions withImage(int id) { - checkArgument(id > 0, "server id must be a positive number"); - this.imageId = id; + public RebuildServerOptions withImage(String ref) { + checkNotNull(ref, "image reference should not be null"); + checkArgument(!ref.isEmpty(), "image reference should not be empty"); + this.imageRef = ref; return this; } public static class Builder { /** - * @see RebuildServerOptions#withImage(int) + * @see RebuildServerOptions#withImage(String) */ - public static RebuildServerOptions withImage(int id) { + public static RebuildServerOptions withImage(String ref) { RebuildServerOptions options = new RebuildServerOptions(); - return options.withImage(id); + return options.withImage(ref); } } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 857178572c..ad85ee505b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -39,7 +39,9 @@ import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.RestClientTest; import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextSpec; -import org.jclouds.rest.functions.*; +import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; +import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; @@ -78,7 +80,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1}}", + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -100,7 +102,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals( request, - "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -121,7 +123,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals(request, - "{\"server\":{\"name\":\"ralphie\",\"imageId\":2,\"flavorId\":1,\"metadata\":{\"foo\":\"bar\"}}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -499,11 +501,11 @@ public class NovaAsyncClientTest extends RestClientTest { public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3, withImage(2)); + HttpRequest request = processor.createRequest(method, 3, withImage("2")); assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageId\":2}}", MediaType.APPLICATION_JSON, false); + assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index dba404f3ed..1984d1a986 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -18,20 +18,33 @@ */ package org.jclouds.openstack.nova; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Injector; -import com.google.inject.Module; +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertTrue; + +import java.io.IOException; +import java.security.SecureRandom; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.TimeUnit; + import org.jclouds.Constants; -import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; -import org.jclouds.openstack.nova.domain.*; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.ImageStatus; +import org.jclouds.openstack.nova.domain.RebootType; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.SocketOpen; @@ -43,18 +56,12 @@ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import java.io.IOException; -import java.security.SecureRandom; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.TimeUnit; - -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.testng.Assert.*; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.Injector; +import com.google.inject.Module; /** * Tests behavior of {@code NovaClient} @@ -74,15 +81,6 @@ public class NovaClientLiveTest { protected String endpoint; protected String apiversion; - private String serverPrefix = System.getProperty("user.name") + ".cs"; - private int serverId; - private String adminPass; - Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private String ip; - private int serverId2; - private String adminPass2; - private int imageId; - protected Properties setupProperties() throws IOException { Properties overrides = new Properties(); @@ -214,14 +212,14 @@ public class NovaClientLiveTest { public void testGetServersDetail() throws Exception { Set response = client.listServers(withDetails()); assert null != response; - assertTrue(response.size() >= 0); + long serverCount = response.size(); + assertTrue(serverCount >= 0); for (Server server : response) { Server newDetails = client.getServer(server.getId()); assertEquals(server, newDetails); } } - @Test public void testListFlavors() throws Exception { Set response = client.listFlavors(); assert null != response; @@ -234,7 +232,6 @@ public class NovaClientLiveTest { } - @Test public void testListFlavorsDetail() throws Exception { Set response = client.listFlavors(withDetails()); assert null != response; @@ -248,7 +245,6 @@ public class NovaClientLiveTest { } } - @Test public void testGetFlavorsDetail() throws Exception { Set response = client.listFlavors(withDetails()); assert null != response; @@ -265,10 +261,17 @@ public class NovaClientLiveTest { assert client.getFlavor(12312987) == null; } + private String serverPrefix = System.getProperty("user.name") + ".cs"; + private int serverId; + private String adminPass; + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + private int serverId2; + private int imageId; + @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = client.getImage(13).getURI().toASCIIString(); - String flavorRef = client.getFlavor(1).getURI().toASCIIString(); + String imageRef = "3"; + String flavorRef = "1"; String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata)); @@ -278,7 +281,7 @@ public class NovaClientLiveTest { serverId = server.getId(); adminPass = server.getAdminPass(); blockUntilServerActive(serverId); - ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next(); + client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); } private void blockUntilServerActive(int serverId) throws InterruptedException { @@ -308,23 +311,16 @@ public class NovaClientLiveTest { } } - @Test(enabled = true, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") public void testServerDetails() throws Exception { Server server = client.getServer(serverId); assertNotNull(server.getHostId()); assertEquals(server.getStatus(), ServerStatus.ACTIVE); - - - assertNotNull(server.getAddresses()); - - - // check metadata - assertEquals(server.getMetadata(), metadata); - assertPassword(server, adminPass); - assertEquals(server.getFlavorRef(), endpoint + "/flavors/1"); assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals(server.getImageRef(), endpoint + "/images/13"); + assertEquals("3", server.getImageRef()); + assertEquals("1", server.getFlavorRef()); + assertNotNull(server.getAddresses()); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); @@ -332,11 +328,14 @@ public class NovaClientLiveTest { assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); + // check metadata + assertEquals(server.getMetadata(), metadata); + assertPassword(server, adminPass); } private void assertPassword(Server server, String pass) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0), 22); + IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0).getAddress(), 22); socketTester.apply(socket); SshClient client = sshFactory.create(socket, new Credentials("root", pass)); @@ -351,19 +350,6 @@ public class NovaClientLiveTest { } } - private ExecResponse exec(Server details, String pass, String command) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0), 22); - socketTester.apply(socket); - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - return client.exec(command); - } finally { - if (client != null) - client.disconnect(); - } - } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") public void testRenameServer() throws Exception { Server server = client.getServer(serverId); @@ -381,37 +367,18 @@ public class NovaClientLiveTest { this.adminPass = "elmo"; } - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } - } - - private void assertIpNotConfigured(Server server, String password) throws IOException { - 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); - } - - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") public void testCreateImage() throws Exception { Image image = client.createImageFromServer("hoofie", serverId); assertEquals("hoofie", image.getName()); - assertEquals(new Integer(serverId), image.getServerId()); + assertEquals(new Integer(serverId), image.getServerRef()); imageId = image.getId(); blockUntilImageActive(imageId); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") public void testRebuildServer() throws Exception { - client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); + client.rebuildServer(serverId, new RebuildServerOptions().withImage(String.valueOf(imageId))); blockUntilServerActive(serverId); // issue Web Hosting #119580 imageId comes back incorrect after rebuild assertEquals(imageId, client.getServer(serverId).getImageRef()); @@ -475,7 +442,7 @@ public class NovaClientLiveTest { @AfterTest void deleteServersOnEnd() { if (serverId > 0) { - //client.deleteServer(serverId); + client.deleteServer(serverId); } if (serverId2 > 0) { client.deleteServer(serverId2); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index b43f6368da..e6406c47c9 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -10,6 +10,8 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; +import com.google.common.collect.ImmutableSet; + import java.util.Arrays; import java.util.Properties; import java.util.Set; @@ -30,7 +32,7 @@ public class _NovaClient { Properties overrides = new Properties(); overrides.setProperty(PROPERTY_ENDPOINT, endpoint); ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, - Arrays.asList(new JschSshClientModule(), new SLF4JLoggingModule()), overrides); + ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), overrides); ComputeService cs = context.getComputeService(); @@ -39,7 +41,7 @@ public class _NovaClient { System.out.println(cs.listAssignableLocations()); System.out.println(cs.listNodes()); - /*TemplateOptions options = new TemplateOptions(); + /*TemplateOptions options = new TemplateOptions().blockUntilRunning(false); Template template = cs.templateBuilder().imageId("13").options(options).build(); try { Set metedata = cs.runNodesWithTag("test", 1, template); @@ -48,6 +50,8 @@ public class _NovaClient { e.printStackTrace(); }*/ + //System.out.println(cs.getNodeMetadata("64")); + //cs.destroyNode("64"); context.close(); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java index cdec9d9a68..66ef4325ce 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java @@ -18,18 +18,63 @@ */ package org.jclouds.openstack.nova.compute; -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; -import com.google.inject.Guice; -import com.google.inject.Module; +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.and; +import static com.google.common.base.Predicates.not; +import static com.google.common.base.Throwables.getRootCause; +import static com.google.common.collect.Iterables.concat; +import static com.google.common.collect.Iterables.get; +import static com.google.common.collect.Iterables.getOnlyElement; +import static com.google.common.collect.Maps.newLinkedHashMap; +import static com.google.common.collect.Maps.uniqueIndex; +import static com.google.common.collect.Sets.filter; +import static com.google.common.collect.Sets.newTreeSet; +import static org.jclouds.compute.ComputeTestUtils.buildScript; +import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; +import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; +import static org.jclouds.compute.predicates.NodePredicates.TERMINATED; +import static org.jclouds.compute.predicates.NodePredicates.all; +import static org.jclouds.compute.predicates.NodePredicates.inGroup; +import static org.jclouds.compute.predicates.NodePredicates.runningInGroup; +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Properties; +import java.util.Set; +import java.util.SortedSet; +import java.util.TreeSet; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + import org.jclouds.Constants; -import org.jclouds.compute.*; -import org.jclouds.compute.domain.*; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.ComputeTestUtils; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.RunScriptData; +import org.jclouds.compute.RunScriptOnNodesException; +import org.jclouds.compute.domain.ComputeMetadata; +import org.jclouds.compute.domain.ComputeType; +import org.jclouds.compute.domain.ExecResponse; +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.domain.TemplateBuilder; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; @@ -51,31 +96,15 @@ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.not; -import static com.google.common.base.Throwables.getRootCause; -import static com.google.common.collect.Iterables.*; -import static com.google.common.collect.Maps.newLinkedHashMap; -import static com.google.common.collect.Maps.uniqueIndex; -import static com.google.common.collect.Sets.filter; -import static com.google.common.collect.Sets.newTreeSet; -import static org.jclouds.compute.ComputeTestUtils.buildScript; -import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; -import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; -import static org.jclouds.compute.predicates.NodePredicates.*; -import static org.jclouds.compute.predicates.NodePredicates.all; -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; +import com.google.common.base.Charsets; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.io.Files; +import com.google.inject.Guice; +import com.google.inject.Module; /** * Generally disabled, as it incurs higher fees. @@ -85,603 +114,595 @@ import static org.testng.Assert.assertNotNull; @Test(groups = "novalive", enabled = true, sequential = true) public class NovaComputeServiceLiveTest { - protected String group; + protected String group; - protected RetryablePredicate socketTester; - protected SortedSet nodes; - protected ComputeServiceContext context; - protected ComputeService client; + protected RetryablePredicate socketTester; + protected SortedSet nodes; + protected ComputeServiceContext context; + protected ComputeService client; - protected Template template; - protected Map keyPair; + protected Template template; + protected Map keyPair; - protected String provider; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; + protected String provider; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; - private Properties overrides; + private Properties overrides; - public NovaComputeServiceLiveTest() { - provider = "nova"; - } + public NovaComputeServiceLiveTest() { + provider = "nova"; + } - private void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { - if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) - properties.setProperty(propertyName, System.getProperty(propertyName)); - } + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } - - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } - protected Properties setupProperties() { - Properties overrides = new Properties(); - try { - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - } catch (IOException e) { - throw new RuntimeException("Can't load properties"); - } - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.public"); - overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.private"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); - return overrides; - } + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.public"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.private"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - protected Properties setupRestProperties() { - return RestContextFactory.getPropertiesFromResource("/rest.properties"); - } + return overrides; + } - private void initializeContextAndClient(Properties properties) throws IOException { - if (context != null) + protected Properties setupRestProperties() { + return RestContextFactory.getPropertiesFromResource("/rest.properties"); + } + + private void initializeContextAndClient(Properties properties) throws IOException { + if (context != null) + context.close(); + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( + new SLF4JLoggingModule(), getSshModule()), properties); + client = context.getComputeService(); + } + + public static Map setupKeyPair(Properties properties) throws FileNotFoundException, IOException { + return ImmutableMap.of( + "private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8), + "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); + } + + + @BeforeGroups(groups = {"novalive"}) + public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException { + if (group == null) + group = checkNotNull(provider, "provider"); + if (group.indexOf('-') == -1) + group = group + "-"; + Properties properties = setupProperties(); + setupCredentials(properties); + updateProperties(properties); + overrides = properties; + keyPair = setupKeyPair(properties); + initializeContextAndClient(properties); + buildSocketTester(); + } + + protected void buildSocketTester() { + SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 60, 1, TimeUnit.SECONDS); + } + + + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + @Test + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext tmContext = new ComputeServiceContextFactory() + .createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides).getProviderSpecificContext(); + } + + + protected void checkNodes(Iterable nodes, String tag) throws IOException { + _checkNodes(nodes, tag); + for (NodeMetadata node : nodes) { + assertEquals(node.getLocation().getScope(), LocationScope.HOST); + } + } + + protected void _checkNodes(Iterable nodes, String group) throws IOException { + for (NodeMetadata node : nodes) { + assertNotNull(node.getProviderId()); + assertNotNull(node.getGroup()); + assertEquals(node.getGroup(), group); + assertEquals(node.getState(), NodeState.RUNNING); + Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); + assertEquals(fromStore, node.getCredentials()); + assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; + assertNotNull(node.getCredentials()); + if (node.getCredentials().identity != null) { + assertNotNull(node.getCredentials().identity); + assertNotNull(node.getCredentials().credential); + sshPing(node); + } + } + } + + + @Test(enabled = true, expectedExceptions = AuthorizationException.class) + public void testCorrectAuthException() throws Exception { + ComputeServiceContext context = null; + try { + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet + .of(new SLF4JLoggingModule()), overrides); + context.getComputeService().listNodes(); + } catch (AuthorizationException e) { + throw e; + } catch (RuntimeException e) { + e.printStackTrace(); + throw e; + } finally { + if (context != null) context.close(); - context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( - new SLF4JLoggingModule(), getSshModule()), properties); - client = context.getComputeService(); - } + } + } - public static Map setupKeyPair(Properties properties) throws FileNotFoundException, IOException { - return ImmutableMap.of( - "private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8), - "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); - } + @Test(enabled = true) + public void testImagesCache() throws Exception { + client.listImages(); + long time = System.currentTimeMillis(); + client.listImages(); + long duration = System.currentTimeMillis() - time; + assert duration < 1000 : String.format("%dms to get images", duration); + } + + @Test(enabled = true, expectedExceptions = NoSuchElementException.class) + public void testCorrectExceptionRunningNodesNotFound() throws Exception { + client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() + .family(OsFamily.UBUNTU).description("ffoo").build())); + } + + // since surefire and eclipse don't otherwise guarantee the order, we are + // starting this one alphabetically before create2nodes.. + @Test(enabled = true, dependsOnMethods = {"testCompareSizes"}) + public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { + String group = this.group + "r"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + + TemplateOptions options = client.templateOptions().blockOnPort(22, 120); + try { + Set nodes = client.createNodesInGroup(group, 1, options); + Credentials good = nodes.iterator().next().getCredentials(); + assert good.identity != null : nodes; + assert good.credential != null : nodes; + + OperatingSystem os = get(nodes, 0).getOperatingSystem(); + try { + Map responses = runScriptWithCreds(group, os, new Credentials( + good.identity, "romeo")); + assert false : "shouldn't pass with a bad password\n" + responses; + } catch (RunScriptOnNodesException e) { + assert getRootCause(e).getMessage().contains("Auth fail") : e; + } + + for (Map.Entry response : client.runScriptOnNodesMatching( + runningInGroup(group), Statements.exec("echo hello"), + overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) + assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + + response.getValue(); + + runScriptWithCreds(group, os, good); + + checkNodes(nodes, group); + + } finally { + client.destroyNodesMatching(inGroup(group)); + } + } + + @Test(enabled = true, dependsOnMethods = {"testImagesCache"}) + public void testTemplateMatch() throws Exception { + template = buildTemplate(client.templateBuilder()); + Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build(); + assertEquals(toMatch.getImage(), template.getImage()); + } + + protected void checkHttpGet(NodeMetadata node) { + ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); + } + + @Test(enabled = true, dependsOnMethods = "testCompareSizes") + public void testCreateTwoNodesWithRunScript() throws Exception { + try { + client.destroyNodesMatching(inGroup(group)); + } catch (NoSuchElementException e) { + + } + refreshTemplate(); + try { + nodes = newTreeSet(client.createNodesInGroup(group, 2, template)); + } catch (RunNodesException e) { + nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); + throw e; + } + assertEquals(nodes.size(), 2); + checkNodes(nodes, group); + NodeMetadata node1 = nodes.first(); + NodeMetadata node2 = nodes.last(); + // credentials aren't always the same + // assertEquals(node1.getCredentials(), node2.getCredentials()); + + assertLocationSameOrChild(node1.getLocation(), template.getLocation()); + assertLocationSameOrChild(node2.getLocation(), template.getLocation()); + checkImageIdMatchesTemplate(node1); + checkImageIdMatchesTemplate(node2); + checkOsMatchesTemplate(node1); + checkOsMatchesTemplate(node2); + } + + private void refreshTemplate() { + template = buildTemplate(client.templateBuilder()); + + template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) + .runScript(buildScript(template.getImage().getOperatingSystem())); + } + + protected void checkImageIdMatchesTemplate(NodeMetadata node) { + if (node.getImageId() != null) + assertEquals(node.getImageId(), template.getImage().getId()); + } + + protected void checkOsMatchesTemplate(NodeMetadata node) { + if (node.getOperatingSystem() != null) + assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String + .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node + .getOperatingSystem()); + } + + void assertLocationSameOrChild(Location test, Location expected) { + if (!test.equals(expected)) { + assertEquals(test.getParent().getId(), expected.getId()); + } else { + assertEquals(test, expected); + } + } + + @Test(enabled = true, dependsOnMethods = "testCreateTwoNodesWithRunScript") + public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { + initializeContextAndClient(overrides); + refreshTemplate(); + TreeSet nodes = newTreeSet(client.createNodesInGroup(group, 1, template)); + checkNodes(nodes, group); + NodeMetadata node = nodes.first(); + this.nodes.add(node); + assertEquals(nodes.size(), 1); + assertLocationSameOrChild(node.getLocation(), template.getLocation()); + checkOsMatchesTemplate(node); + } + + @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") + public void testCredentialsCache() throws Exception { + initializeContextAndClient(overrides); + for (NodeMetadata node : nodes) + assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); + } + + protected Map runScriptWithCreds(final String group, OperatingSystem os, + Credentials creds) throws RunScriptOnNodesException { + try { + return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + .nameTask("runScriptWithCreds")); + } catch (SshException e) { + throw e; + } + } - @BeforeGroups(groups = {"novalive"}) - public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException { - if (group == null) - group = checkNotNull(provider, "provider"); - if (group.indexOf('-') == -1) - group = group + "-"; - Properties properties = setupProperties(); - setupCredentials(properties); - updateProperties(properties); - overrides = properties; - keyPair = setupKeyPair(properties); - initializeContextAndClient(properties); - buildSocketTester(); - } + protected Template buildTemplate(TemplateBuilder templateBuilder) { + return templateBuilder.build(); + } - protected void buildSocketTester() { - SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); - socketTester = new RetryablePredicate(socketOpen, 60, 1, TimeUnit.SECONDS); - } + @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") + public void testGet() throws Exception { + Map metadataMap = newLinkedHashMap(uniqueIndex(filter(client + .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), + new Function() { + @Override + public String apply(NodeMetadata from) { + return from.getId(); + } - protected JschSshClientModule getSshModule() { - return new JschSshClientModule(); - } + })); + for (NodeMetadata node : nodes) { + metadataMap.remove(node.getId()); + NodeMetadata metadata = client.getNodeMetadata(node.getId()); + assertEquals(metadata.getProviderId(), node.getProviderId()); + assertEquals(metadata.getGroup(), node.getGroup()); + assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); + checkImageIdMatchesTemplate(metadata); + checkOsMatchesTemplate(metadata); + assert (metadata.getState() == NodeState.RUNNING) : metadata; + // due to DHCP the addresses can actually change in-between runs. + assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size()); + assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size()); + } + assertNodeZero(metadataMap.values()); + } - @Test - public void testAssignability() throws Exception { - @SuppressWarnings("unused") - RestContext tmContext = new ComputeServiceContextFactory() - .createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides).getProviderSpecificContext(); - } + protected void assertNodeZero(Collection metadataSet) { + assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", + metadataSet, nodes); + } + @Test(enabled = true, dependsOnMethods = "testGet") + public void testReboot() throws Exception { + client.rebootNodesMatching(inGroup(group));// TODO test + // validation + testGet(); + } - protected void checkNodes(Iterable nodes, String tag) throws IOException { - _checkNodes(nodes, tag); - for (NodeMetadata node : nodes) { - assertEquals(node.getLocation().getScope(), LocationScope.HOST); - } - } + @Test(enabled = true, dependsOnMethods = "testReboot") + public void testSuspendResume() throws Exception { + client.suspendNodesMatching(inGroup(group)); - protected void _checkNodes(Iterable nodes, String group) throws IOException { - for (NodeMetadata node : nodes) { - assertNotNull(node.getProviderId()); - assertNotNull(node.getGroup()); - assertEquals(node.getGroup(), group); - assertEquals(node.getState(), NodeState.RUNNING); - Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); - assertEquals(fromStore, node.getCredentials()); - assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; - assertNotNull(node.getCredentials()); - if (node.getCredentials().identity != null) { - assertNotNull(node.getCredentials().identity); - assertNotNull(node.getCredentials().credential); - sshPing(node); - } - } - } + Set stoppedNodes = refreshNodes(); + assert Iterables.all(stoppedNodes, new Predicate() { - @Test(enabled = true, expectedExceptions = AuthorizationException.class) - public void testCorrectAuthException() throws Exception { - ComputeServiceContext context = null; - try { - context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet - .of(new SLF4JLoggingModule()), overrides); - context.getComputeService().listNodes(); - } catch (AuthorizationException e) { - throw e; - } catch (RuntimeException e) { - e.printStackTrace(); - throw e; - } finally { - if (context != null) - context.close(); - } - } + @Override + public boolean apply(NodeMetadata input) { + boolean returnVal = input.getState() == NodeState.SUSPENDED; + if (!returnVal) + System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState()); + return returnVal; + } - @Test(enabled = true) - public void testImagesCache() throws Exception { - client.listImages(); - long time = System.currentTimeMillis(); - client.listImages(); - long duration = System.currentTimeMillis() - time; - assert duration < 1000 : String.format("%dms to get images", duration); - } + }) : stoppedNodes; - @Test(enabled = true, expectedExceptions = NoSuchElementException.class) - public void testCorrectExceptionRunningNodesNotFound() throws Exception { - client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() - .family(OsFamily.UBUNTU).description("ffoo").build())); - } + client.resumeNodesMatching(inGroup(group)); + testGet(); + } - // since surefire and eclipse don't otherwise guarantee the order, we are - // starting this one alphabetically before create2nodes.. - @Test(enabled = true, dependsOnMethods = {"testCompareSizes"}) - public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { - String group = this.group + "r"; - try { - client.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { + @Test(enabled = true, dependsOnMethods = "testSuspendResume") + public void testListNodes() throws Exception { + for (ComputeMetadata node : client.listNodes()) { + assert node.getProviderId() != null; + assert node.getLocation() != null; + assertEquals(node.getType(), ComputeType.NODE); + } + } - } + @Test(enabled = true, dependsOnMethods = "testSuspendResume") + public void testGetNodesWithDetails() throws Exception { + for (NodeMetadata node : client.listNodesDetailsMatching(all())) { + assert node.getProviderId() != null : node; + assert node.getLocation() != null : node; + assertEquals(node.getType(), ComputeType.NODE); + assert node instanceof NodeMetadata; + NodeMetadata nodeMetadata = (NodeMetadata) node; + assert nodeMetadata.getProviderId() != null : nodeMetadata; + // nullable + // assert nodeMetadata.getImage() != null : node; + // user specified name is not always supported + // assert nodeMetadata.getName() != null : nodeMetadata; + if (nodeMetadata.getState() == NodeState.RUNNING) { + assert nodeMetadata.getPublicAddresses() != null : nodeMetadata; + assert nodeMetadata.getPublicAddresses().size() > 0 || nodeMetadata.getPrivateAddresses().size() > 0 : nodeMetadata; + assertNotNull(nodeMetadata.getPrivateAddresses()); + } + } + } - TemplateOptions options = client.templateOptions().blockOnPort(22, 120); - try { - Set nodes = client.createNodesInGroup(group, 1, options); - Credentials good = nodes.iterator().next().getCredentials(); - assert good.identity != null : nodes; - assert good.credential != null : nodes; + @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"}) + public void testDestroyNodes() { + int toDestroy = refreshNodes().size(); + Set destroyed = client.destroyNodesMatching(inGroup(group)); + assertEquals(toDestroy, destroyed.size()); + for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) { + assert node.getState() == NodeState.TERMINATED : node; + assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); + } + } - OperatingSystem os = get(nodes, 0).getOperatingSystem(); + private Set refreshNodes() { + return filter(client.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); + } + + @Test(enabled = true) + public void testCreateAndRunAService() throws Exception { + + String group = this.group + "s"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + + template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) + .build(); + + // note this is a dependency on the template resolution + template.getOptions().runScript( + RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() + .getOperatingSystem())); + try { + NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template)); + + checkHttpGet(node); + } finally { + client.destroyNodesMatching(inGroup(group)); + } + + } + + @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */) + public void testTemplateOptions() throws Exception { + TemplateOptions options = new TemplateOptions().withMetadata(); + Template t = client.templateBuilder().smallest().options(options).build(); + assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; + } + + public void testListImages() throws Exception { + for (Image image : client.listImages()) { + assert image.getProviderId() != null : image; + // image.getLocationId() can be null, if it is a location-free image + assertEquals(image.getType(), ComputeType.IMAGE); + } + } + + @Test(groups = {"integration", "live"}) + public void testGetAssignableLocations() throws Exception { + for (Location location : client.listAssignableLocations()) { + System.err.printf("location %s%n", location); + assert location.getId() != null : location; + assert location != location.getParent() : location; + assert location.getScope() != null : location; + switch (location.getScope()) { + case PROVIDER: + assertProvider(location); + break; + case REGION: + assertProvider(location.getParent()); + break; + case ZONE: + Location provider = location.getParent().getParent(); + // zone can be a direct descendant of provider + if (provider == null) + provider = location.getParent(); + assertProvider(provider); + break; + case HOST: + Location provider2 = location.getParent().getParent().getParent(); + // zone can be a direct descendant of provider + if (provider2 == null) + provider2 = location.getParent().getParent(); + assertProvider(provider2); + break; + } + } + } + + public void testOptionToNotBlock() throws Exception { + String group = this.group + "block"; + try { + client.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + // no inbound ports + TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts(); + try { + long time = System.currentTimeMillis(); + Set nodes = client.createNodesInGroup(group, 1, options); + NodeMetadata node = getOnlyElement(nodes); + assert node.getState() != NodeState.RUNNING; + long duration = System.currentTimeMillis() - time; + assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; + } finally { + client.destroyNodesMatching(inGroup(group)); + } + } + + private void assertProvider(Location provider) { + assertEquals(provider.getScope(), LocationScope.PROVIDER); + assertEquals(provider.getParent(), null); + } + + public void testListSizes() throws Exception { + for (Hardware hardware : client.listHardwareProfiles()) { + assert hardware.getProviderId() != null; + assert getCores(hardware) > 0; + assert hardware.getVolumes().size() >= 0; + assert hardware.getRam() > 0; + assertEquals(hardware.getType(), ComputeType.HARDWARE); + } + } + + @Test(enabled = true) + public void testCompareSizes() throws Exception { + Hardware defaultSize = client.templateBuilder().build().getHardware(); + + Hardware smallest = client.templateBuilder().smallest().build().getHardware(); + Hardware fastest = client.templateBuilder().fastest().build().getHardware(); + Hardware biggest = client.templateBuilder().biggest().build().getHardware(); + + System.out.printf("smallest %s%n", smallest); + System.out.printf("fastest %s%n", fastest); + System.out.printf("biggest %s%n", biggest); + + assertEquals(defaultSize, smallest); + + assert getCores(smallest) <= getCores(fastest) : String.format("%d ! <= %d", smallest, fastest); + assert getCores(biggest) <= getCores(fastest) : String.format("%d ! <= %d", biggest, fastest); + + assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest); + assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest); + + assert getCores(fastest) >= getCores(biggest) : String.format("%d ! >= %d", fastest, biggest); + assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest); + } + + private void sshPing(NodeMetadata node) throws IOException { + for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate. + try { + doCheckJavaIsInstalledViaSsh(node); + return; + } catch (SshException e) { try { - Map responses = runScriptWithCreds(group, os, new Credentials( - good.identity, "romeo")); - assert false : "shouldn't pass with a bad password\n" + responses; - } catch (RunScriptOnNodesException e) { - assert getRootCause(e).getMessage().contains("Auth fail") : e; + Thread.sleep(10 * 1000); + } catch (InterruptedException e1) { } + continue; + } + } + } - for (Map.Entry response : client.runScriptOnNodesMatching( - runningInGroup(group), Statements.exec("echo hello"), - overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) - assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " - + response.getValue(); + protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { + SshClient ssh = context.utils().sshForNode().apply(node); + try { + ssh.connect(); + ExecResponse hello = ssh.exec("echo hello"); + assertEquals(hello.getOutput().trim(), "hello"); + ExecResponse exec = ssh.exec("java -version"); + assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" + + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); + } finally { + if (ssh != null) + ssh.disconnect(); + } + } - runScriptWithCreds(group, os, good); - - checkNodes(nodes, group); - - } finally { - client.destroyNodesMatching(inGroup(group)); - } - } - - @Test(enabled = true, dependsOnMethods = {"testImagesCache"}) - public void testTemplateMatch() throws Exception { - template = buildTemplate(client.templateBuilder()); - Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build(); - assertEquals(toMatch.getImage(), template.getImage()); - } - - protected void checkHttpGet(NodeMetadata node) { - ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); - } - - @Test(enabled = true, dependsOnMethods = "testCompareSizes") - public void testCreateTwoNodesWithRunScript() throws Exception { - try { - client.destroyNodesMatching(inGroup(group)); - } catch (NoSuchElementException e) { - - } - refreshTemplate(); - try { - nodes = newTreeSet(client.createNodesInGroup(group, 2, template)); - } catch (RunNodesException e) { - nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); - throw e; - } - assertEquals(nodes.size(), 2); - checkNodes(nodes, group); - NodeMetadata node1 = nodes.first(); - NodeMetadata node2 = nodes.last(); - // credentials aren't always the same - // assertEquals(node1.getCredentials(), node2.getCredentials()); - - assertLocationSameOrChild(node1.getLocation(), template.getLocation()); - assertLocationSameOrChild(node2.getLocation(), template.getLocation()); - checkImageIdMatchesTemplate(node1); - checkImageIdMatchesTemplate(node2); - checkOsMatchesTemplate(node1); - checkOsMatchesTemplate(node2); - } - - private void refreshTemplate() { - template = buildTemplate(client.templateBuilder()); - - template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) - .runScript(buildScript(template.getImage().getOperatingSystem())); - } - - protected void checkImageIdMatchesTemplate(NodeMetadata node) { - if (node.getImageId() != null) - assertEquals(node.getImageId(), template.getImage().getId()); - } - - protected void checkOsMatchesTemplate(NodeMetadata node) { - if (node.getOperatingSystem() != null) - assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String - .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node - .getOperatingSystem()); - } - - void assertLocationSameOrChild(Location test, Location expected) { - if (!test.equals(expected)) { - assertEquals(test.getParent().getId(), expected.getId()); - } else { - assertEquals(test, expected); - } - } - - @Test(enabled = true, dependsOnMethods = "testCreateTwoNodesWithRunScript") - public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { - initializeContextAndClient(overrides); - refreshTemplate(); - TreeSet nodes = newTreeSet(client.createNodesInGroup(group, 1, template)); - checkNodes(nodes, group); - NodeMetadata node = nodes.first(); - this.nodes.add(node); - assertEquals(nodes.size(), 1); - assertLocationSameOrChild(node.getLocation(), template.getLocation()); - checkOsMatchesTemplate(node); - } - - @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") - public void testCredentialsCache() throws Exception { - initializeContextAndClient(overrides); - for (NodeMetadata node : nodes) - assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); - } - - protected Map runScriptWithCreds(final String group, OperatingSystem os, - Credentials creds) throws RunScriptOnNodesException { - try { - return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) - .nameTask("runScriptWithCreds")); - } catch (SshException e) { - throw e; - } - } - - - protected Template buildTemplate(TemplateBuilder templateBuilder) { - return templateBuilder.build(); - } - - @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") - public void testGet() throws Exception { - Map metadataMap = newLinkedHashMap(uniqueIndex(filter(client - .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), - new Function() { - - @Override - public String apply(NodeMetadata from) { - return from.getId(); - } - - })); - for (NodeMetadata node : nodes) { - metadataMap.remove(node.getId()); - NodeMetadata metadata = client.getNodeMetadata(node.getId()); - assertEquals(metadata.getProviderId(), node.getProviderId()); - assertEquals(metadata.getGroup(), node.getGroup()); - assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); - checkImageIdMatchesTemplate(metadata); - checkOsMatchesTemplate(metadata); - assert (metadata.getState() == NodeState.RUNNING) : metadata; - // due to DHCP the addresses can actually change in-between runs. - assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size()); - assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size()); - } - assertNodeZero(metadataMap.values()); - } - - protected void assertNodeZero(Collection metadataSet) { - assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", - metadataSet, nodes); - } - - @Test(enabled = true, dependsOnMethods = "testGet") - public void testReboot() throws Exception { - client.rebootNodesMatching(inGroup(group));// TODO test - // validation - testGet(); - } - - @Test(enabled = true, dependsOnMethods = "testReboot") - public void testSuspendResume() throws Exception { - client.suspendNodesMatching(inGroup(group)); - - Set stoppedNodes = refreshNodes(); - - assert Iterables.all(stoppedNodes, new Predicate() { - - @Override - public boolean apply(NodeMetadata input) { - boolean returnVal = input.getState() == NodeState.SUSPENDED; - if (!returnVal) - System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState()); - return returnVal; - } - - }) : stoppedNodes; - - client.resumeNodesMatching(inGroup(group)); - testGet(); - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - public void testListNodes() throws Exception { - for (ComputeMetadata node : client.listNodes()) { - assert node.getProviderId() != null; - assert node.getLocation() != null; - assertEquals(node.getType(), ComputeType.NODE); - } - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - public void testGetNodesWithDetails() throws Exception { - for (NodeMetadata node : client.listNodesDetailsMatching(all())) { - assert node.getProviderId() != null : node; - assert node.getLocation() != null : node; - assertEquals(node.getType(), ComputeType.NODE); - assert node instanceof NodeMetadata; - NodeMetadata nodeMetadata = (NodeMetadata) node; - assert nodeMetadata.getProviderId() != null : nodeMetadata; - // nullable - // assert nodeMetadata.getImage() != null : node; - // user specified name is not always supported - // assert nodeMetadata.getName() != null : nodeMetadata; - if (nodeMetadata.getState() == NodeState.RUNNING) { - assert nodeMetadata.getPublicAddresses() != null : nodeMetadata; - assert nodeMetadata.getPublicAddresses().size() > 0 || nodeMetadata.getPrivateAddresses().size() > 0 : nodeMetadata; - assertNotNull(nodeMetadata.getPrivateAddresses()); - } - } - } - - @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"}) - public void testDestroyNodes() { - int toDestroy = refreshNodes().size(); - Set destroyed = client.destroyNodesMatching(inGroup(group)); - assertEquals(toDestroy, destroyed.size()); - for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) { - assert node.getState() == NodeState.TERMINATED : node; - assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); - } - } - - private Set refreshNodes() { - return filter(client.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); - } - - @Test(enabled = true) - public void testCreateAndRunAService() throws Exception { - - String group = this.group + "s"; - try { - client.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { - - } - - template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) - .build(); - - // note this is a dependency on the template resolution - template.getOptions().runScript( - RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() - .getOperatingSystem())); - try { - NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template)); - - checkHttpGet(node); - } finally { - client.destroyNodesMatching(inGroup(group)); - } - - } - - @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */) - public void testTemplateOptions() throws Exception { - TemplateOptions options = new TemplateOptions().withMetadata(); - Template t = client.templateBuilder().smallest().options(options).build(); - assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; - } - - public void testListImages() throws Exception { - for (Image image : client.listImages()) { - assert image.getProviderId() != null : image; - // image.getLocationId() can be null, if it is a location-free image - assertEquals(image.getType(), ComputeType.IMAGE); - } - } - - @Test(groups = {"integration", "live"}) - public void testGetAssignableLocations() throws Exception { - for (Location location : client.listAssignableLocations()) { - System.err.printf("location %s%n", location); - assert location.getId() != null : location; - assert location != location.getParent() : location; - assert location.getScope() != null : location; - switch (location.getScope()) { - case PROVIDER: - assertProvider(location); - break; - case REGION: - assertProvider(location.getParent()); - break; - case ZONE: - Location provider = location.getParent().getParent(); - // zone can be a direct descendant of provider - if (provider == null) - provider = location.getParent(); - assertProvider(provider); - break; - case HOST: - Location provider2 = location.getParent().getParent().getParent(); - // zone can be a direct descendant of provider - if (provider2 == null) - provider2 = location.getParent().getParent(); - assertProvider(provider2); - break; - } - } - } - - public void testOptionToNotBlock() throws Exception { - String group = this.group + "block"; - try { - client.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { - - } - // no inbound ports - TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts(); - try { - long time = System.currentTimeMillis(); - Set nodes = client.createNodesInGroup(group, 1, options); - NodeMetadata node = getOnlyElement(nodes); - assert node.getState() != NodeState.RUNNING; - long duration = System.currentTimeMillis() - time; - assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; - } finally { - client.destroyNodesMatching(inGroup(group)); - } - } - - private void assertProvider(Location provider) { - assertEquals(provider.getScope(), LocationScope.PROVIDER); - assertEquals(provider.getParent(), null); - } - - public void testListSizes() throws Exception { - for (Hardware hardware : client.listHardwareProfiles()) { - assert hardware.getProviderId() != null; - assert getCores(hardware) > 0; - assert hardware.getVolumes().size() >= 0; - assert hardware.getRam() > 0; - assertEquals(hardware.getType(), ComputeType.HARDWARE); - } - } - - @Test(enabled = true) - public void testCompareSizes() throws Exception { - Hardware defaultSize = client.templateBuilder().build().getHardware(); - - Hardware smallest = client.templateBuilder().smallest().build().getHardware(); - Hardware fastest = client.templateBuilder().fastest().build().getHardware(); - Hardware biggest = client.templateBuilder().biggest().build().getHardware(); - - System.out.printf("smallest %s%n", smallest); - System.out.printf("fastest %s%n", fastest); - System.out.printf("biggest %s%n", biggest); - - assertEquals(defaultSize, smallest); - - assert getCores(smallest) <= getCores(fastest) : String.format("%d ! <= %d", smallest, fastest); - assert getCores(biggest) <= getCores(fastest) : String.format("%d ! <= %d", biggest, fastest); - - assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest); - assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest); - - assert getCores(fastest) >= getCores(biggest) : String.format("%d ! >= %d", fastest, biggest); - assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest); - } - - private void sshPing(NodeMetadata node) throws IOException { - for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate. - try { - doCheckJavaIsInstalledViaSsh(node); - return; - } catch (SshException e) { - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e1) { - } - continue; - } - } - } - - protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { - SshClient ssh = context.utils().sshForNode().apply(node); - try { - ssh.connect(); - ExecResponse hello = ssh.exec("echo hello"); - assertEquals(hello.getOutput().trim(), "hello"); - ExecResponse exec = ssh.exec("java -version"); - assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" - + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); - } finally { - if (ssh != null) - ssh.disconnect(); - } - } - - @AfterTest - protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException { - if (nodes != null) { - testDestroyNodes(); - } - context.close(); - } + @AfterTest + protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException { + if (nodes != null) { + testDestroyNodes(); + } + context.close(); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java index a8f8607b92..b1aada24be 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java @@ -20,6 +20,8 @@ package org.jclouds.openstack.nova.compute.functions; import static org.testng.Assert.assertEquals; +import java.net.URI; +import java.net.URISyntaxException; import java.net.UnknownHostException; import org.jclouds.openstack.nova.domain.Flavor; @@ -44,11 +46,16 @@ public class FlavorToHardwareTest { Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); @Test - public void test() throws UnknownHostException { - assertEquals(convertFlavor(), new HardwareBuilder().ids("1").name("256 MB Server").processors( - ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true) - .build())).build()); + public void test() throws UnknownHostException, URISyntaxException { + Hardware flavor = convertFlavor(); + Hardware tempFlavor = new HardwareBuilder().ids("1").name("256 MB Server") + .processors(ImmutableList.of(new Processor(1.0, 1.0))) + .ram(256) + .volumes(ImmutableList.of( + new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true).build())) + .uri(new URI("http://servers.api.openstack.org/v1.1/1234/flavors/1")) + .build(); + assertEquals(flavor, tempFlavor); } public static Hardware convertFlavor() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index 98839a6e42..ebf522ff81 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -18,12 +18,12 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.List; + import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -32,11 +32,13 @@ import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.testng.annotations.Test; -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - -import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseAddressesFromJsonResponse} @@ -51,8 +53,7 @@ public class ParseAddressesFromJsonResponseTest { public void testApplyInputStreamDetails() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); List
publicAddresses = ImmutableList.copyOf( @@ -63,7 +64,7 @@ public class ParseAddressesFromJsonResponseTest { Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); - assertEquals(response.getPublicAddresses(), publicAddresses); - assertEquals(response.getPrivateAddresses(), privateAddresses); + assertEquals(response.getPublicAddresses(), Sets.newHashSet(publicAddresses)); + assertEquals(response.getPrivateAddresses(), Sets.newHashSet(privateAddresses)); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java index 781e62e2db..4881949d35 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java @@ -19,10 +19,11 @@ package org.jclouds.openstack.nova.functions; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; + import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -33,10 +34,10 @@ import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.handlers.ParseNovaErrorFromHttpResponse; import org.testng.annotations.Test; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseServerListFromJsonResponse} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java index 7669a50f8a..10ad7d36a9 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java @@ -18,23 +18,22 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.gson.Gson; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.io.InputStream; + import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.util.Strings2; import org.testng.annotations.Test; -import java.io.IOException; -import java.io.InputStream; - -import static org.testng.Assert.assertEquals; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} @@ -48,18 +47,10 @@ public class ParseFlavorFromJsonResponseTest { public void testParseFlavorFromJsonResponseTest() throws IOException { Flavor response = parseFlavor(); - String json = new Gson().toJson(response); - - String expectedJson = Strings2.toStringAndClose( - ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json")) - .replace("\n", "").replace("\t", "").replace("\r", "").replace(" ", ""); - assertEquals(response.getId(), 1); assertEquals(response.getName(), "256 MB Server"); assertEquals(response.getDisk().intValue(), 10); assertEquals(response.getRam().intValue(), 256); - - assertEquals(json, expectedJson); } public static Flavor parseFlavor() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java index 92ab3919a2..d9357d0e98 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java @@ -57,14 +57,13 @@ public class ParseImageFromJsonResponseTest { public void testApplyInputStreamDetails() throws UnknownHostException { Image response = parseImage(); - assertEquals(response.getId(), 2); + assertEquals(response.getId(), 1); assertEquals(response.getName(), "CentOS 5.2"); - assertEquals(response.getServerId(), new Integer(12)); assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); assertEquals(response.getProgress(), new Integer(80)); assertEquals(response.getStatus(), ImageStatus.SAVING); assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z"))); - assertEquals(response.getServerId(), "http://servers.api.openstack.org/v1.1/1234/servers/12", "Change serverId to serverRefs"); + assertEquals(response.getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); assertEquals(response.getMetadata().get("ImageVersion"), "1.5"); assertEquals(response.getMetadata().get("ImageType"), "Gold"); assertEquals(response.getMetadata().size(), 2); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java index 34a5a97d35..4de761a6ac 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java @@ -60,9 +60,8 @@ public class ParseImageListFromJsonResponseTest { List expects = ImmutableList.of(new Image(1, "CentOS 5.2"), new Image(743, "My Server Backup")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); + UnwrapOnlyJsonValue> parser = i.getInstance( + Key.get(new TypeLiteral>>() {})); List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); assertEquals(response, expects); @@ -81,26 +80,21 @@ public class ParseImageListFromJsonResponseTest { assertEquals(response.get(0).getName(), "CentOS 5.2"); assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); assertEquals(response.get(0).getProgress(), null); - assertEquals(response.get(0).getServerId(), null); + assertEquals(response.get(0).getServerRef(), null); assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE); assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); assertEquals(response.get(0).getMetadata().get("ImageType"), "Gold"); assertEquals(response.get(0).getMetadata().get("ImageVersion"), "1.5"); assertEquals(response.get(0).getMetadata().size(), 2); - assertEquals(response.get(0).getServerId(), null, "Change serverId to serverRef"); assertEquals(response.get(1).getId(), 743); assertEquals(response.get(1).getName(), "My Server Backup"); assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16Z")); assertEquals(response.get(1).getProgress(), new Integer(80)); - assertEquals(response.get(1).getServerId(), new Integer(12)); assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); - assertEquals(response.get(1).getServerId(), "http://servers.api.openstack.org/v1.1/1234/servers/12", "Change serverId to serverRef"); - - //short form of reference - assertEquals(response.get(2).getServerId().intValue(), 12, "Change serverId to serverRef"); + assertEquals(response.get(1).getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java index 090fb1639c..12d7980a55 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java @@ -19,6 +19,7 @@ package org.jclouds.openstack.nova.functions; import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -27,11 +28,13 @@ import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; import org.testng.annotations.Test; import java.io.InputStream; import java.net.UnknownHostException; import java.util.List; +import java.util.Map; import static org.testng.Assert.assertEquals; @@ -49,23 +52,30 @@ public class ParseInetAddressListFromJsonResponseTest { public void testPublic() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue>> parser = i.getInstance( + Key.get(new TypeLiteral>>>() {})); + List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))) + .get("public"); - assertEquals(response, ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")); + List
addresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); + assertEquals(response, addresses); } @Test public void testPrivate() throws UnknownHostException { InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue>> parser = i.getInstance( + Key.get(new TypeLiteral>>>() {})); + List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))) + .get("private"); + + List
addresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); - assertEquals(response, ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")); + assertEquals(response, addresses); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 382813eed2..7fd3e8f94d 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -51,7 +51,7 @@ import static org.testng.Assert.assertEquals; public class ParseServerFromJsonResponseTest { @Test - public void testApplyInputStreamDetails() throws UnknownHostException { + public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { Server response = parseServer(); assertEquals(response.getId(), 1234); @@ -62,22 +62,26 @@ public class ParseServerFromJsonResponseTest { assertEquals(response.getStatus(), ServerStatus.BUILD); assertEquals(response.getProgress(), new Integer(60)); - List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.getAddresses(), addresses1); assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.getAddresses(), addresses1); } - public static Server parseServer() { + public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { Injector i = Guice.createInjector(new GsonModule()); InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Server response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); + + return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index 186ded5918..f9bb444875 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -36,6 +36,8 @@ import org.jclouds.openstack.nova.domain.ServerStatus; import org.testng.annotations.Test; import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.HashSet; import java.util.List; @@ -67,7 +69,7 @@ public class ParseServerListFromJsonResponseTest { } @Test - public void testApplyInputStreamDetails() throws UnknownHostException { + public void testApplyInputStreamDetails() throws UnknownHostException, URISyntaxException { InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); UnwrapOnlyJsonValue> parser = i.getInstance(Key @@ -83,29 +85,35 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); assertEquals(response.get(0).getProgress(), new Integer(60)); - List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.get(0).getAddresses(), addresses1); assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); assertEquals(response.get(1).getId(), 5678); assertEquals(response.get(1).getName(), "sample-server2"); - assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1"); + assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); - assertEquals(true, false, "Uncomment next line"); - //assertEquals(response.getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2"); assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); assertEquals(response.get(1).getProgress(), null); - List
publicAddresses2 = ImmutableList.of(new Address("67.23.10.133", 4), new Address("::babe:67.23.10.133", 4)); - List
privateAddresses2 = ImmutableList.of(new Address("10.176.42.17", 4), new Address("::babe:10.176.42.17", 4)); + List
publicAddresses2 = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"), + Address.newString2AddressFunction())); + List
privateAddresses2 = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"), + Address.newString2AddressFunction())); Addresses addresses2 = new Addresses(new HashSet
(publicAddresses2), new HashSet
(privateAddresses2)); assertEquals(response.get(1).getAddresses(), addresses2); assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); - assertEquals(response.get(1).getURI(), "http://servers.api.openstack.org/1234/servers/56789"); + assertEquals(response.get(1).getURI(), new URI("http://servers.api.openstack.org/v1.1/1234/servers/5678")); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java index 78750f2824..cd198667ce 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java @@ -35,48 +35,47 @@ import com.google.inject.Injector; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") public class CreateServerOptionsTest { - Injector injector = Guice.createInjector(new GsonModule()); + Injector injector = Guice.createInjector(new GsonModule()); - @Test - public void testAddPayloadToRequestMapOfStringStringHttpRequest() { - CreateServerOptions options = new CreateServerOptions(); - HttpRequest request = buildRequest(options); - assertEquals("{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2}}", request.getPayload().getRawContent()); - } + @Test + public void testAddPayloadToRequestMapOfStringStringHttpRequest() { + CreateServerOptions options = new CreateServerOptions(); + HttpRequest request = buildRequest(options); + assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\"}}", request.getPayload().getRawContent()); + } - private HttpRequest buildRequest(CreateServerOptions options) { - injector.injectMembers(options); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageId", "1", "flavorId", "2")); - return request; - } + private HttpRequest buildRequest(CreateServerOptions options) { + injector.injectMembers(options); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2")); + return request; + } - @Test - public void testWithFile() { - CreateServerOptions options = new CreateServerOptions(); - options.withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFile() { + CreateServerOptions options = new CreateServerOptions(); + options.withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - @Test - public void testWithFileStatic() { - CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFileStatic() { + CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - private void assertFile(HttpRequest request) { - assertEquals( - "{\"server\":{\"name\":\"foo\",\"imageId\":1,\"flavorId\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}", - request.getPayload().getRawContent()); - } + private void assertFile(HttpRequest request) { + assertEquals(request.getPayload().getRawContent(), + "{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\",\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); + } @Test public void testWithMetadata() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java index 7d6ded590f..e3c33156fe 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java @@ -60,20 +60,20 @@ public class RebuildServerOptionsTest { @Test public void testWithServer() { RebuildServerOptions options = new RebuildServerOptions(); - options.withImage(3); + options.withImage("3"); HttpRequest request = buildRequest(options); assertRebuild(request); } @Test public void testWithServerStatic() { - RebuildServerOptions options = withImage(3); + RebuildServerOptions options = withImage("3"); HttpRequest request = buildRequest(options); assertRebuild(request); } private void assertRebuild(HttpRequest request) { - assertEquals("{\"rebuild\":{\"imageId\":3}}", request.getPayload().getRawContent()); + assertEquals("{\"rebuild\":{\"imageRef\":\"3\"}}", request.getPayload().getRawContent()); } } diff --git a/sandbox-apis/nova/src/test/resources/test_get_image_details.json b/sandbox-apis/nova/src/test/resources/test_get_image_details.json index 07fdb578e4..035e3beffa 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_image_details.json +++ b/sandbox-apis/nova/src/test/resources/test_get_image_details.json @@ -7,12 +7,10 @@ "created" : "2010-08-10T12:00:00Z", "status" : "SAVING", "progress" : 80, - "metadata" : { - "values" : { - "ImageVersion" : "1.5", - "ImageType" : "Gold" - } - }, + "metadata" : { + "ImageVersion" : "1.5", + "ImageType" : "Gold" + }, "links": [ { "rel" : "self", diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json index 44297c1ebf..62935ae947 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json @@ -1,7 +1,6 @@ { - "network" { - "id" : "private", - "values" : [ + "network" : { + "private" : [ {"version" : 4, "addr" : "67.23.10.132"}, {"version" : 6, "addr" : "::babe:67.23.10.132"}, {"version" : 4, "addr" : "67.23.10.131"}, diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json index 81277bf69d..0c7a67a2b2 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json @@ -1,7 +1,6 @@ { - "network" { - "id" : "public", - "values" : [ + "network" : { + "public" : [ {"version" : 4, "addr" : "67.23.10.132"}, {"version" : 6, "addr" : "::babe:67.23.10.132"}, {"version" : 4, "addr" : "67.23.10.131"}, diff --git a/sandbox-apis/nova/src/test/resources/test_list_flavors.json b/sandbox-apis/nova/src/test/resources/test_list_flavors.json index c677ff3f5e..51ef1bc28f 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_flavors.json +++ b/sandbox-apis/nova/src/test/resources/test_list_flavors.json @@ -1,46 +1,44 @@ { - "flavors" : { - "values" : [ - { - "id" : 1, - "name" : "256 MB Server", - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/flavors/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/flavors/1" - } - ] - }, - { - "id" : 2, - "name" : "512 MB Server", - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/flavors/2" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/flavors/2" - } - ] - } - ] - } + "flavors" : [ + { + "id" : 1, + "name" : "256 MB Server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + } + ] + }, + { + "id" : 2, + "name" : "512 MB Server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + } + ] + } + ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json b/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json index 36c6f6852d..c8939ee520 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_flavors_detail.json @@ -1,50 +1,48 @@ { - "flavors" : { - "values" : [ - { - "id" : 1, - "name" : "256 MB Server", - "ram" : 256, - "disk" : 10, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/flavors/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/flavors/1" - } - ] - }, - { - "id" : 2, - "name" : "512 MB Server", - "ram" : 512, - "disk" : 20, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/flavors/2" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/flavors/2" - } - ] - } - ] - } + "flavors" : [ + { + "id" : 1, + "name" : "256 MB Server", + "ram" : 256, + "disk" : 10, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/1" + } + ] + }, + { + "id" : 2, + "name" : "512 MB Server", + "ram" : 512, + "disk" : 20, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/flavors/2" + } + ] + } + ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_images.json b/sandbox-apis/nova/src/test/resources/test_list_images.json index 50bfb5ac90..4772219ece 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images.json @@ -1,47 +1,44 @@ { - "images" : { - "values" : [ - { - "id" : 1, - "name" : "CentOS 5.2", + "images" : [ + { + "id" : 1, + "name" : "CentOS 5.2", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/1" - } - ] - }, - { - "id" : 743, - "name" : "My Server Backup", - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/images/743" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/743" - } - ] - } - ] - } + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + }, + { + "id" : 743, + "name" : "My Server Backup", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/743" + } + ] + } + ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json index 865cfdc082..2ad7bd9688 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_images_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_images_detail.json @@ -1,90 +1,84 @@ { - "images" : { - "values" : [ - { - "id" : 1, - "name" : "CentOS 5.2", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "status" : "ACTIVE", - "metadata" : { - "values" : { - "ImageType" : "Gold", - "ImageVersion" : "1.5" - } - }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/1" - } - ] + "images" : [ + { + "id" : 1, + "name" : "CentOS 5.2", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "ACTIVE", + "metadata" : { + "ImageType" : "Gold", + "ImageVersion" : "1.5" }, - { - "id" : 743, - "name" : "My Server Backup", - "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2009-07-07T09:56:16Z", - "status" : "SAVING", - "progress" : 80, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/images/743" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/743" - } - ] - }, - { - "id" : 5, - "name" : "CentOS 5.2", - "serverRef" : 12, - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "status" : "ACTIVE", - "metadata" : { - "values" : { - "ImageType" : "Gold", - "ImageVersion" : "1.5" - } + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/images/1" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/1" - } - ] - } - ] - } + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + }, + { + "id" : 743, + "name" : "My Server Backup", + "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2009-07-07T09:56:16Z", + "status" : "SAVING", + "progress" : 80, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/743" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/743" + } + ] + }, + { + "id" : 5, + "name" : "CentOS 5.2", + "serverRef" : 12, + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "status" : "ACTIVE", + "metadata" : { + "ImageType" : "Gold", + "ImageVersion" : "1.5" + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/images/1" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/images/1" + } + ] + } + ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers.json b/sandbox-apis/nova/src/test/resources/test_list_servers.json index c3b22c9d74..82c53075c7 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers.json @@ -1,47 +1,45 @@ { - "servers" : { - "values" : [ - { - "id" : 1234, - "name" : "sample-server", - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - } - ] - }, - { - "id" : 5678, - "name" : "sample-server2", - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/servers/5678" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/5678" - } - ] - } - ] - } + "servers" : [ + { + "id" : 1234, + "name" : "sample-server", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + }, + { + "id" : 5678, + "name" : "sample-server2", + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + } + ] + } + ] } diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json index 219d501bca..15bb6b491d 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json @@ -1,111 +1,89 @@ { - "servers" : { - "values" : [ - { - "id" : 1234, - "name" : "sample-server", - "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", - "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", - "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", - "status" : "BUILD", - "progress" : 60, - "addresses" : { - "values" : [ - { - "id" : "public", - "values" : [ - {"version" : 4, "addr" : "67.23.10.132"}, - {"version" : 6, "addr" : "::babe:67.23.10.132"}, - {"version" : 4, "addr" : "67.23.10.131"}, - {"version" : 6, "addr" : "::babe:4317:0A83"} - ] - }, - { - "id" : "private", - "values" : [ - {"version" : 4, "addr" : "10.176.42.16"}, - {"version" : 6, "addr" : "::babe:10.176.42.16"} - ] - } - ] - }, - "metadata" : { - "values" : { - "Server Label" : "Web Head 1", - "Image Version" : "2.1" - } - }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/1234" - } - ] + "servers" : [ + { + "id" : 1234, + "name" : "sample-server", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", + "affinityId" : "fc88bcf8394db9c8d0564e08ca6a9724188a84d1", + "status" : "BUILD", + "progress" : 60, + "addresses" : { + "public" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + }, + "metadata" : { + "Server Label" : "Web Head 1", + "Image Version" : "2.1" }, - { - "id" : 5678, - "name" : "sample-server2", - "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1", - "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", - "updated" : "2010-10-10T12:00:00Z", - "created" : "2010-08-10T12:00:00Z", - "hostId" : "9e107d9d372bb6826bd81d3542a419d6", - "affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2", - "status" : "ACTIVE", - "addresses" : { - "values" : [ - { - "id" : "public", - "values" : [ - {"version" : 4, "addr" : "67.23.10.133"}, - {"version" : 6, "addr" : "::babe:67.23.10.133"} - ] - }, - { - "id" : "private", - "values" : [ - {"version" : 4, "addr" : "10.176.42.17"}, - {"version" : 6, "addr" : "::babe:10.176.42.17"} - ] - } - ] + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/1234" }, - "metadata" : { - "values" : { - "Server Label" : "DB 1" - } + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/1234" }, - "links": [ - { - "rel" : "self", - "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+xml", - "href" : "http://servers.api.openstack.org/1234/servers/5678" - }, - { - "rel" : "bookmark", - "type" : "application/vnd.openstack.compute-v1.1+json", - "href" : "http://servers.api.openstack.org/1234/servers/56789" - } - ] - } - ] - } + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/1234" + } + ] + }, + { + "id" : 5678, + "name" : "sample-server2", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1", + "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "updated" : "2010-10-10T12:00:00Z", + "created" : "2010-08-10T12:00:00Z", + "hostId" : "9e107d9d372bb6826bd81d3542a419d6", + "affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2", + "status" : "ACTIVE", + "addresses" : { + "public" : [ + {"version" : 4, "addr" : "67.23.10.133"}, + {"version" : 6, "addr" : "::babe:67.23.10.133"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.17"}, + {"version" : 6, "addr" : "::babe:10.176.42.17"} + ] + }, + "metadata" : { + "Server Label" : "DB 1" + }, + "links": [ + { + "rel" : "self", + "href" : "http://servers.api.openstack.org/v1.1/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+xml", + "href" : "http://servers.api.openstack.org/1234/servers/5678" + }, + { + "rel" : "bookmark", + "type" : "application/vnd.openstack.compute-v1.1+json", + "href" : "http://servers.api.openstack.org/1234/servers/56789" + } + ] + } + ] } From f52f331be9177ea55e260d026c64ce253c8c7215 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Mon, 18 Apr 2011 15:12:40 +0400 Subject: [PATCH 34/95] Fixed tests. Added affinity id and dates. --- .../jclouds/openstack/nova/domain/Image.java | 43 +- .../openstack/nova/domain/Resource.java | 1 + .../jclouds/openstack/nova/domain/Server.java | 32 +- .../openstack/nova/NovaAsyncClientTest.java | 881 +++++++++--------- .../openstack/nova/NovaClientLiveTest.java | 132 ++- .../openstack/nova/PropertyHelper.java | 8 +- .../functions/FlavorToHardwareTest.java | 37 +- .../functions/NovaImageToImageTest.java | 43 +- .../functions/ServerToNodeMetadataTest.java | 158 ++-- .../openstack/nova/domain/ServerTest.java | 6 +- .../ParseAddressesFromJsonResponseTest.java | 51 +- .../ParseFaultFromJsonResponseTest.java | 145 ++- .../ParseFlavorFromJsonResponseTest.java | 52 +- .../ParseFlavorListFromJsonResponseTest.java | 54 +- .../ParseImageFromJsonResponseTest.java | 78 +- .../ParseImageListFromJsonResponseTest.java | 87 +- ...seInetAddressListFromJsonResponseTest.java | 54 +- .../openstack/nova/functions/ParseModule.java | 19 + .../ParseServerFromJsonResponseTest.java | 67 +- .../ParseServerListFromJsonResponseTest.java | 100 +- .../nova/options/CreateServerOptionsTest.java | 78 +- .../nova/options/ListOptionsTest.java | 18 +- .../options/RebuildServerOptionsTest.java | 20 +- .../resources/test_get_image_details.json | 4 +- .../test/resources/test_list_addresses.json | 22 +- .../test_list_addresses_private.json | 4 +- .../resources/test_list_addresses_public.json | 4 +- .../src/test/resources/test_list_flavors.json | 2 + .../src/test/resources/test_list_servers.json | 2 +- .../resources/test_list_servers_detail.json | 26 +- 30 files changed, 1144 insertions(+), 1084 deletions(-) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java index b548f25ca8..8a3934ee6d 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Image.java @@ -18,28 +18,41 @@ */ package org.jclouds.openstack.nova.domain; +import com.google.common.collect.Maps; + import java.util.Collections; import java.util.Date; import java.util.Map; -import com.google.common.collect.Maps; - /** - * An image is a collection of files used to create or rebuild a server. - * + * An image is a collection of files used to create or rebuild a server. Rackspace provides a number + * of pre-built OS images by default. You may also create custom images from cloud servers you have + * launched. These custom images are useful for backup purposes or for producing gold server images + * if you plan to deploy a particular server configuration frequently. + * * @author Adrian Cole */ public class Image extends Resource { - private Date created; private int id; private String name; private Integer progress; private String serverRef; private ImageStatus status; - private Date updated; private Map metadata = Maps.newHashMap(); + private Date created; + private Date updated; + + public Date getCreated() { + return created; + } + + public Date getUpdated() { + return updated; + } + + public Image() { } @@ -48,13 +61,6 @@ public class Image extends Resource { this.name = name; } - public void setCreated(Date created) { - this.created = created; - } - - public Date getCreated() { - return created; - } public void setId(int id) { this.id = id; @@ -96,13 +102,6 @@ public class Image extends Resource { return status; } - public void setUpdated(Date updated) { - this.updated = updated; - } - - public Date getUpdated() { - return updated; - } public Map getMetadata() { return Collections.unmodifiableMap(metadata); @@ -149,8 +148,8 @@ public class Image extends Resource { @Override public String toString() { - return "Image [created=" + created + ", id=" + id + ", name=" + name + ", serverId=" - + serverRef + "]"; + return "Image [created=" + getCreated() + ", id=" + id + ", name=" + name + ", serverRef=" + + serverRef + "]"; } } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java index ea6b09d3fa..b97f29f2f4 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java @@ -11,6 +11,7 @@ import java.util.Map; * @author Dmitri Babaev */ public class Resource { + private List> links = Lists.newArrayList(); public URI getURI() { diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java index 69c3d841f5..c496210097 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Server.java @@ -18,14 +18,15 @@ */ package org.jclouds.openstack.nova.domain; -import java.util.Map; - import com.google.common.collect.Maps; +import java.util.Date; +import java.util.Map; + /** * A server is a virtual machine instance in the OpenStack Nova system. Flavor and image are * requisite elements when creating a server. - * + * * @author Adrian Cole */ public class Server extends Resource { @@ -39,6 +40,19 @@ public class Server extends Resource { private String flavorRef; private String hostId; private String imageRef; + private String affinityId; + + private Date created; + private Date updated; + + public Date getCreated() { + return created; + } + + public Date getUpdated() { + return updated; + } + private Integer progress; private ServerStatus status; @@ -51,6 +65,14 @@ public class Server extends Resource { this.name = name; } + public String getAffinityId() { + return affinityId; + } + + public void setAffinityId(String affinityId) { + this.affinityId = affinityId; + } + public void setMetadata(Map metadata) { this.metadata = metadata; } @@ -206,8 +228,8 @@ public class Server extends Resource { @Override public String toString() { return "Server [addresses=" + addresses + ", adminPass=" + adminPass + ", flavorRef=" - + flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef - + ", metadata=" + metadata + ", name=" + name + "]"; + + flavorRef + ", hostId=" + hostId + ", id=" + id + ", imageRef=" + imageRef + + ", metadata=" + metadata + ", name=" + name + "]"; } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index ad85ee505b..cf59a2cd75 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -54,7 +54,8 @@ import java.util.Properties; import static org.jclouds.Constants.PROPERTY_API_VERSION; import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.*; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; @@ -68,562 +69,562 @@ import static org.testng.Assert.assertEquals; // NOTE:without testName, this will not call @Before* and fail w/NPE during surefire @Test(groups = "unit", testName = "NovaAsyncClientTest") public class NovaAsyncClientTest extends RestClientTest { - private static final Class listOptionsVarargsClass = new ListOptions[]{}.getClass(); - private static final Class createServerOptionsVarargsClass = new CreateServerOptions[]{} - .getClass(); + private static final Class listOptionsVarargsClass = new ListOptions[]{}.getClass(); + private static final Class createServerOptionsVarargsClass = new CreateServerOptions[]{} + .getClass(); - @Test - public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1); + @Test + public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", - "application/json", false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", + "application/json", false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - @Test - public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor - .createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())); + @Test + public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor + .createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals( - request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", - "application/json", false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals( + request, + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", + "application/json", false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - @Test - public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, - createServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, - withMetadata(ImmutableMap.of("foo", "bar"))); + @Test + public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + createServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, + withMetadata(ImmutableMap.of("foo", "bar"))); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", - "application/json", false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", + "application/json", false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testDeleteImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteImage", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/images/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/images/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListServers() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + public void testListServers() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - Date now = new Date(10000000l); + Date now = new Date(10000000l); - public void testListServersOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + public void testListServersOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/servers?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListServersDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + public void testListServersDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listServers", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testGetServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getServer", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testGetServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getServer", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListFlavors() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + public void testListFlavors() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListFlavorsOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + public void testListFlavorsOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/flavors?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListFlavorsDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + public void testListFlavorsDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListFlavorsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); + public void testListFlavorsDetailOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listFlavors", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/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); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testGetFlavor() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testGetFlavor() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getFlavor", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/flavors/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListImages() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method); + public void testListImages() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListImagesDetail() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails()); + public void testListImagesDetail() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails()); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/detail?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/detail?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListImagesOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); + public void testListImagesOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/images?format=json&changes-since=10000&limit=1&offset=2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testListImagesDetailOptions() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); + public void testListImagesDetailOptions() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listImages", listOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, withDetails().changesSince(now).maxResults(1).startAt(2)); - assertRequestLineEquals(request, - "GET http://endpoint/vapiversion/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); + assertRequestLineEquals(request, + "GET http://endpoint/vapiversion/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, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testGetImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getImage", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testGetImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getImage", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/2?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/images/2?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnNullOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testDeleteServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testDeleteServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("deleteServer", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "DELETE http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, ReturnTrueIf2xx.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnFalseOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); - HttpRequest request = processor.createRequest(method, 2, "foo"); + public void testChangeAdminPass() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); + HttpRequest request = processor.createRequest(method, 2, "foo"); - assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - public void testChangeServerName() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class); - HttpRequest request = processor.createRequest(method, 2, "foo"); + public void testChangeServerName() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("renameServer", int.class, String.class); + HttpRequest request = processor.createRequest(method, 2, "foo"); - assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"server\":{\"name\":\"foo\"}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testListAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("getAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips?format=json 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); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); - } + checkFilters(request); + } - public void testListPublicAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + public void testListPublicAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listPublicAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/public?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/public?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - @Test - public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class); - HttpRequest request = processor.createRequest(method, 2); + @Test + public void testListPrivateAddresses() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("listPrivateAddresses", int.class); + HttpRequest request = processor.createRequest(method, 2); - assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/private?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, null, null, false); + assertRequestLineEquals(request, "GET http://endpoint/vapiversion/servers/2/ips/private?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, null, null, false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class); - checkFilters(request); - } + checkFilters(request); + } - @Test - public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); - HttpRequest request = processor.createRequest(method, "ralphie", 2); + @Test + public void testCreateImageWithIpGroup() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("createImageFromServer", String.class, int.class); + HttpRequest request = processor.createRequest(method, "ralphie", 2); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/images?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, - false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/images?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); + assertPayloadEquals(request, "{\"image\":{\"serverId\":2,\"name\":\"ralphie\"}}", MediaType.APPLICATION_JSON, + false); - assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); + checkFilters(request); - } + } - private static final Class rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{} - .getClass(); + private static final Class rebuildServerOptionsVarargsClass = new RebuildServerOptions[]{} + .getClass(); - @Test - public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, - rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3); + @Test + public void testRebuildServer() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, + rebuildServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, 3); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"rebuild\":{}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); - } + checkFilters(request); + } - @Test - public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, - rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3, withImage("2")); + @Test + public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, + rebuildServerOptionsVarargsClass); + HttpRequest request = processor.createRequest(method, 3, withImage(2)); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); - checkFilters(request); - } + checkFilters(request); + } - @Test - public void testReboot() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class); - HttpRequest request = processor.createRequest(method, 2, RebootType.HARD); + @Test + public void testReboot() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("rebootServer", int.class, RebootType.class); + HttpRequest request = processor.createRequest(method, 2, RebootType.HARD); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"reboot\":{\"type\":\"HARD\"}}", MediaType.APPLICATION_JSON, false); - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - @Test - public void testResize() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class); - HttpRequest request = processor.createRequest(method, 2, 3); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - - } - - public void testConfirmResize() throws IOException, IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - public void testRevertResize() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class); - HttpRequest request = processor.createRequest(method, 2); - - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); - assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false); - - assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); - assertSaxResponseParserClassEquals(method, null); - assertExceptionParserClassEquals(method, null); - - checkFilters(request); - } - - @Override - protected TypeLiteral> createTypeLiteral() { - return new TypeLiteral>() { - }; - } - - @Override - protected void checkFilters(HttpRequest request) { - assertEquals(request.getFilters().size(), 2); - assertEquals(request.getFilters().get(0).getClass(), AuthenticateRequest.class); - assertEquals(request.getFilters().get(1).getClass(), AddTimestampQuery.class); - - } - - @Override - protected Module createModule() { - return new TestNovaRestClientModule(); - } - - @ConfiguresRestClient - @RequiresHttp - protected static class TestNovaRestClientModule extends NovaRestClientModule { - private TestNovaRestClientModule() { - super(new TestOpenStackAuthenticationModule()); - } - - @Override - protected URI provideServerUrl(AuthenticationResponse response) { - return URI.create("http://endpoint"); - } - - } - - protected String provider = "nova"; - - @Override - public RestContextSpec createContextSpec() { - return new RestContextFactory(getProperties()).createContextSpec(provider, "user", "password", new Properties()); - } - - @Override - protected Properties getProperties() { - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_REGIONS, "US"); - overrides.setProperty(PROPERTY_API_VERSION, "apiversion"); - overrides.setProperty(provider + ".endpoint", "http://endpoint"); - overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); - return overrides; - } + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Test + public void testResize() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("resizeServer", int.class, int.class); + HttpRequest request = processor.createRequest(method, 2, 3); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"resize\":{\"flavorId\":3}}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + + } + + public void testConfirmResize() throws IOException, IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("confirmResizeServer", int.class); + HttpRequest request = processor.createRequest(method, 2); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"confirmResize\":null}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + public void testRevertResize() throws IOException, SecurityException, NoSuchMethodException { + Method method = NovaAsyncClient.class.getMethod("revertResizeServer", int.class); + HttpRequest request = processor.createRequest(method, 2); + + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action?format=json HTTP/1.1"); + assertNonPayloadHeadersEqual(request, ""); + assertPayloadEquals(request, "{\"revertResize\":null}", MediaType.APPLICATION_JSON, false); + + assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); + assertSaxResponseParserClassEquals(method, null); + assertExceptionParserClassEquals(method, null); + + checkFilters(request); + } + + @Override + protected TypeLiteral> createTypeLiteral() { + return new TypeLiteral>() { + }; + } + + @Override + protected void checkFilters(HttpRequest request) { + assertEquals(request.getFilters().size(), 2); + assertEquals(request.getFilters().get(0).getClass(), AuthenticateRequest.class); + assertEquals(request.getFilters().get(1).getClass(), AddTimestampQuery.class); + + } + + @Override + protected Module createModule() { + return new TestNovaRestClientModule(); + } + + @ConfiguresRestClient + @RequiresHttp + protected static class TestNovaRestClientModule extends NovaRestClientModule { + private TestNovaRestClientModule() { + super(new TestOpenStackAuthenticationModule()); + } + + @Override + protected URI provideServerUrl(AuthenticationResponse response) { + return URI.create("http://endpoint"); + } + + } + + protected String provider = "nova"; + + @Override + public RestContextSpec createContextSpec() { + return new RestContextFactory(getProperties()).createContextSpec(provider, "user", "password", new Properties()); + } + + @Override + protected Properties getProperties() { + Properties overrides = new Properties(); + overrides.setProperty(PROPERTY_REGIONS, "US"); + overrides.setProperty(PROPERTY_API_VERSION, "apiversion"); + overrides.setProperty(provider + ".endpoint", "http://endpoint"); + overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); + return overrides; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 1984d1a986..ef8735c34c 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -16,35 +16,23 @@ * limitations under the License. * ==================================================================== */ + package org.jclouds.openstack.nova; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; -import static org.testng.Assert.assertTrue; - -import java.io.IOException; -import java.security.SecureRandom; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.concurrent.TimeUnit; - +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.Injector; +import com.google.inject.Module; import org.jclouds.Constants; +import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.ImageStatus; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; +import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.SocketOpen; @@ -56,12 +44,18 @@ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Injector; -import com.google.inject.Module; +import java.io.IOException; +import java.security.SecureRandom; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.testng.Assert.*; /** * Tests behavior of {@code NovaClient} @@ -81,6 +75,15 @@ public class NovaClientLiveTest { protected String endpoint; protected String apiversion; + private String serverPrefix = System.getProperty("user.name") + ".cs"; + private int serverId; + private String adminPass; + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + private String ip; + private int serverId2; + private String adminPass2; + private int imageId; + protected Properties setupProperties() throws IOException { Properties overrides = new Properties(); @@ -212,14 +215,14 @@ public class NovaClientLiveTest { public void testGetServersDetail() throws Exception { Set response = client.listServers(withDetails()); assert null != response; - long serverCount = response.size(); - assertTrue(serverCount >= 0); + assertTrue(response.size() >= 0); for (Server server : response) { Server newDetails = client.getServer(server.getId()); assertEquals(server, newDetails); } } + @Test public void testListFlavors() throws Exception { Set response = client.listFlavors(); assert null != response; @@ -232,6 +235,7 @@ public class NovaClientLiveTest { } + @Test public void testListFlavorsDetail() throws Exception { Set response = client.listFlavors(withDetails()); assert null != response; @@ -245,6 +249,7 @@ public class NovaClientLiveTest { } } + @Test public void testGetFlavorsDetail() throws Exception { Set response = client.listFlavors(withDetails()); assert null != response; @@ -261,17 +266,10 @@ public class NovaClientLiveTest { assert client.getFlavor(12312987) == null; } - private String serverPrefix = System.getProperty("user.name") + ".cs"; - private int serverId; - private String adminPass; - Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private int serverId2; - private int imageId; - @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = "3"; - String flavorRef = "1"; + String imageRef = client.getImage(13).getURI().toASCIIString(); + String flavorRef = client.getFlavor(1).getURI().toASCIIString(); String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata)); @@ -281,7 +279,7 @@ public class NovaClientLiveTest { serverId = server.getId(); adminPass = server.getAdminPass(); blockUntilServerActive(serverId); - client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); + ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); } private void blockUntilServerActive(int serverId) throws InterruptedException { @@ -311,16 +309,23 @@ public class NovaClientLiveTest { } } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + @Test(enabled = true, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") public void testServerDetails() throws Exception { Server server = client.getServer(serverId); assertNotNull(server.getHostId()); assertEquals(server.getStatus(), ServerStatus.ACTIVE); - assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals("3", server.getImageRef()); - assertEquals("1", server.getFlavorRef()); + + assertNotNull(server.getAddresses()); + + + // check metadata + assertEquals(server.getMetadata(), metadata); + assertPassword(server, adminPass); + assertEquals(server.getFlavorRef(), endpoint + "/flavors/1"); + assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); + assertEquals(server.getImageRef(), endpoint + "/images/13"); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); @@ -328,9 +333,6 @@ public class NovaClientLiveTest { assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); - // check metadata - assertEquals(server.getMetadata(), metadata); - assertPassword(server, adminPass); } @@ -350,6 +352,19 @@ public class NovaClientLiveTest { } } + private ExecResponse exec(Server details, String pass, String command) throws IOException { + IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0).getAddress(), 22); + socketTester.apply(socket); + SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + try { + client.connect(); + return client.exec(command); + } finally { + if (client != null) + client.disconnect(); + } + } + @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") public void testRenameServer() throws Exception { Server server = client.getServer(serverId); @@ -367,18 +382,37 @@ public class NovaClientLiveTest { this.adminPass = "elmo"; } + 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); + } catch (Exception e) { + e.printStackTrace(); + } catch (AssertionError e) { + e.printStackTrace(); + } + } + + private void assertIpNotConfigured(Server server, String password) throws IOException { + 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); + } + + @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") public void testCreateImage() throws Exception { Image image = client.createImageFromServer("hoofie", serverId); assertEquals("hoofie", image.getName()); - assertEquals(new Integer(serverId), image.getServerRef()); + assertEquals(serverId, image.getServerRef()); imageId = image.getId(); blockUntilImageActive(imageId); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") public void testRebuildServer() throws Exception { - client.rebuildServer(serverId, new RebuildServerOptions().withImage(String.valueOf(imageId))); + client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); blockUntilServerActive(serverId); // issue Web Hosting #119580 imageId comes back incorrect after rebuild assertEquals(imageId, client.getServer(serverId).getImageRef()); @@ -442,7 +476,7 @@ public class NovaClientLiveTest { @AfterTest void deleteServersOnEnd() { if (serverId > 0) { - client.deleteServer(serverId); + //client.deleteServer(serverId); } if (serverId2 > 0) { client.deleteServer(serverId2); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java index f91d323ceb..0a0432420b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java @@ -11,10 +11,10 @@ import java.util.Properties; */ public class PropertyHelper { - public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { - if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) - properties.setProperty(propertyName, System.getProperty(propertyName)); - } + public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { + if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) + properties.setProperty(propertyName, System.getProperty(propertyName)); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java index b1aada24be..fdab38a748 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java @@ -16,27 +16,21 @@ * limitations under the License. * ==================================================================== */ + package org.jclouds.openstack.nova.compute.functions; -import static org.testng.Assert.assertEquals; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; - -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.functions.ParseFlavorFromJsonResponseTest; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.VolumeBuilder; +import com.google.common.collect.ImmutableList; +import org.jclouds.compute.domain.*; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; +import org.jclouds.openstack.nova.domain.Flavor; +import org.jclouds.openstack.nova.functions.ParseFlavorFromJsonResponseTest; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; +import java.net.UnknownHostException; + +import static org.testng.Assert.assertEquals; /** * @author Adrian Cole @@ -46,16 +40,11 @@ public class FlavorToHardwareTest { Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); @Test - public void test() throws UnknownHostException, URISyntaxException { - Hardware flavor = convertFlavor(); - Hardware tempFlavor = new HardwareBuilder().ids("1").name("256 MB Server") - .processors(ImmutableList.of(new Processor(1.0, 1.0))) - .ram(256) - .volumes(ImmutableList.of( - new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true).build())) - .uri(new URI("http://servers.api.openstack.org/v1.1/1234/flavors/1")) - .build(); - assertEquals(flavor, tempFlavor); + public void test() throws UnknownHostException { + assertEquals(convertFlavor(), new HardwareBuilder().ids("1").name("256 MB Server").processors( + ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( + ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true) + .build())).build()); } public static Hardware convertFlavor() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index e780ba0c2d..d5dc9151ea 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -18,6 +18,7 @@ */ package org.jclouds.openstack.nova.compute.functions; +import com.google.inject.AbstractModule; import com.google.inject.Guice; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; @@ -27,7 +28,6 @@ import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.json.Json; -import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.testng.annotations.Test; @@ -41,25 +41,30 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class NovaImageToImageTest { - @Test - public void testApplyWhereImageNotFound() throws UnknownHostException { - assertEquals( - convertImage(), - new ImageBuilder() - .name("CentOS 5.2") - .operatingSystem( - new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) - .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("2").version("1286712000000").build()); - } + @Test + public void testApplyWhereImageNotFound() throws UnknownHostException { + assertEquals( + convertImage(), + new ImageBuilder() + .name("CentOS 5.2") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) + .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) + .ids("2").version("1286712000000").build()); + } - public static Image convertImage() { - org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); + public static Image convertImage() { + org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); - NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) - .getInstance(Json.class)))); + NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { + }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new AbstractModule() { + @Override + protected void configure() { + //To change body of implemented methods use File | Settings | File Templates. + } + }) + .getInstance(Json.class)))); - return parser.apply(image); - } + return parser.apply(image); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index 8ae3a15b54..674f75b38e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -44,102 +44,102 @@ import static org.testng.Assert.assertEquals; */ @Test(groups = "unit") public class ServerToNodeMetadataTest { - Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); + Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); - @Test - public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { - Credentials creds = new Credentials("root", "abdce"); + @Test + public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Credentials creds = new Credentials("root", "abdce"); - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - .of("node#1234", creds), Suppliers.>ofInstance(images), - Suppliers.ofInstance(provider), Suppliers.>ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of("node#1234", creds), Suppliers.>ofInstance(images), + Suppliers.ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( + new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + } - @Test - public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - .of(), Suppliers.>ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.>ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").id("1234").providerId("1234").name("sample-server").location( + new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + } - @Test - public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); - Set images = ImmutableSet.of(jcImage); - Set hardwares = ImmutableSet.of(); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); + Set images = ImmutableSet.of(jcImage); + Set hardwares = ImmutableSet.of(); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - .of(), Suppliers.>ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.>ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").operatingSystem( + new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") + .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( + new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + } - @Test - public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { - Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; - Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); - Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); - Server server = ParseServerFromJsonResponseTest.parseServer(); + @Test + public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; + Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); + Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); + Server server = ParseServerFromJsonResponseTest.parseServer(); - ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap - .of(), Suppliers.>ofInstance(images), Suppliers - .ofInstance(provider), Suppliers.>ofInstance(hardwares)); + ServerToNodeMetadata parser = new ServerToNodeMetadata(serverStateToNodeState, ImmutableMap + .of(), Suppliers.>ofInstance(images), Suppliers + .ofInstance(provider), Suppliers.>ofInstance(hardwares)); - NodeMetadata metadata = parser.apply(server); + NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").hardware( - new HardwareBuilder().ids("1").name("256 MB Server").processors( - ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) - .bootDevice(true).build())).build()).operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); - } + assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( + ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) + .imageId("2").hardware( + new HardwareBuilder().ids("1").name("256 MB Server").processors( + ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( + ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) + .bootDevice(true).build())).build()).operatingSystem( + new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") + .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( + new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerTest.java index bbeefa7dfe..e9e81f2800 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerTest.java @@ -18,13 +18,13 @@ */ package org.jclouds.openstack.nova.domain; -import static org.testng.Assert.assertEquals; - import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; + /** * Tests behavior of {@code CreateImageBinder} - * + * * @author Adrian Cole */ @Test(groups = "unit") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index ebf522ff81..de27b9931c 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -18,12 +18,11 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.List; - +import com.google.common.collect.ImmutableSet; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -32,13 +31,10 @@ import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.UnknownHostException; + +import static org.testng.Assert.assertEqualsNoOrder; /** * Tests behavior of {@code ParseAddressesFromJsonResponse} @@ -47,24 +43,23 @@ import com.google.inject.TypeLiteral; */ @Test(groups = "unit") public class ParseAddressesFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - @Test - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); - Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - List
publicAddresses = ImmutableList.copyOf( - Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), - Address.newString2AddressFunction())); + ImmutableSet
publicAddresses = ImmutableSet.of(new Address("67.23.10.132", 4) + , new Address("::babe:67.23.10.132", 6), new Address("67.23.10.131", 4), new Address("::babe:4317:0A83", 6)); - List
privateAddresses = ImmutableList.copyOf( - Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), - Address.newString2AddressFunction())); + ImmutableSet
privateAddresses = ImmutableSet.of(new Address("10.176.42.16", 4), + new Address("::babe:10.176.42.16", 6)); - assertEquals(response.getPublicAddresses(), Sets.newHashSet(publicAddresses)); - assertEquals(response.getPrivateAddresses(), Sets.newHashSet(privateAddresses)); - } + assertEqualsNoOrder(response.getPublicAddresses().toArray(), publicAddresses.toArray()); + assertEqualsNoOrder(response.getPrivateAddresses().toArray(), privateAddresses.toArray()); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java index 4881949d35..3b382b22fd 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFaultFromJsonResponseTest.java @@ -19,11 +19,10 @@ package org.jclouds.openstack.nova.functions; -import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.List; - +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpCommand; import org.jclouds.http.HttpRequest; import org.jclouds.http.HttpResponse; @@ -34,10 +33,10 @@ import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.handlers.ParseNovaErrorFromHttpResponse; import org.testng.annotations.Test; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.List; /** * Tests behavior of {@code ParseServerListFromJsonResponse} @@ -47,25 +46,25 @@ import com.google.inject.TypeLiteral; @Test(groups = "unit") public class ParseFaultFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - @Test - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - //List response = parser.apply(new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); - new ParseNovaErrorFromHttpResponse().handleError(createHttpCommand(), new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + //List response = parser.apply(new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); + new ParseNovaErrorFromHttpResponse().handleError(createHttpCommand(), new HttpResponse(413, "Over limit", Payloads.newInputStreamPayload(is))); - //assertEquals(response, expects); - } + //assertEquals(response, expects); + } - @Test - public void testHandler() { - //InputStream is = getClass().getResourceAsStream("/test_error_handler.json"); + @Test + public void testHandler() { + //InputStream is = getClass().getResourceAsStream("/test_error_handler.json"); // // @@ -90,62 +89,62 @@ public class ParseFaultFromJsonResponseTest { // } catch (IOException e) { // // this is the excepted output // } - } + } - HttpCommand createHttpCommand() { - return new HttpCommand() { - private Exception exception; + HttpCommand createHttpCommand() { + return new HttpCommand() { + private Exception exception; - @Override - public int incrementRedirectCount() { - return 0; //To change body of implemented methods use File | Settings | File Templates. + @Override + public int incrementRedirectCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getRedirectCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public boolean isReplayable() { + return false; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int incrementFailureCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public int getFailureCount() { + return 0; //To change body of implemented methods use File | Settings | File Templates. + } + + @Override + public HttpRequest getCurrentRequest() { + try { + return new HttpRequest("method", new URI("http://endpoint")); + } catch (URISyntaxException e) { + throw new RuntimeException(e); } + } - @Override - public int getRedirectCount() { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public void setCurrentRequest(HttpRequest request) { + //To change body of implemented methods use File | Settings | File Templates. + } - @Override - public boolean isReplayable() { - return false; //To change body of implemented methods use File | Settings | File Templates. - } + @Override + public void setException(Exception exception) { + this.exception = exception; + } - @Override - public int incrementFailureCount() { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public int getFailureCount() { - return 0; //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public HttpRequest getCurrentRequest() { - try { - return new HttpRequest("method", new URI("http://endpoint")); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - - @Override - public void setCurrentRequest(HttpRequest request) { - //To change body of implemented methods use File | Settings | File Templates. - } - - @Override - public void setException(Exception exception) { - this.exception = exception; - } - - @Override - public Exception getException() { - return exception; - } - }; - } + @Override + public Exception getException() { + return exception; + } + }; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java index 10ad7d36a9..7b9b01d8d9 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorFromJsonResponseTest.java @@ -18,11 +18,11 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.io.InputStream; - +import com.google.gson.Gson; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -30,10 +30,11 @@ import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Flavor; import org.testng.annotations.Test; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.IOException; +import java.io.InputStream; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} @@ -43,24 +44,27 @@ import com.google.inject.TypeLiteral; @Test(groups = "unit") public class ParseFlavorFromJsonResponseTest { - @Test - public void testParseFlavorFromJsonResponseTest() throws IOException { - Flavor response = parseFlavor(); + @Test + public void testParseFlavorFromJsonResponseTest() throws IOException { + Flavor response = parseFlavor(); - assertEquals(response.getId(), 1); - assertEquals(response.getName(), "256 MB Server"); - assertEquals(response.getDisk().intValue(), 10); - assertEquals(response.getRam().intValue(), 256); - } + String json = new Gson().toJson(response); + assertNotNull(json); - public static Flavor parseFlavor() { - Injector i = Guice.createInjector(new GsonModule()); + assertEquals(response.getId(), 1); + assertEquals(response.getName(), "256 MB Server"); + assertEquals(response.getDisk().intValue(), 10); + assertEquals(response.getRam().intValue(), 256); + } - InputStream is = ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json"); + public static Flavor parseFlavor() { + Injector i = Guice.createInjector(new GsonModule()); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - return parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - } + InputStream is = ParseFlavorFromJsonResponseTest.class.getResourceAsStream("/test_get_flavor_details.json"); + + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + return parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java index 064cac1561..1603185edd 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseFlavorListFromJsonResponseTest.java @@ -44,39 +44,39 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseFlavorListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new GsonModule()); - @Test - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_flavors.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_flavors.json"); - List expects = ImmutableList.of(new Flavor(1, "256 MB Server"), new Flavor(2, "512 MB Server")); + List expects = ImmutableList.of(new Flavor(1, "256 MB Server"), new Flavor(2, "512 MB Server")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + assertEquals(response, expects); + } - @Test - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_flavors_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 1); - assertEquals(response.get(0).getName(), "256 MB Server"); - assertEquals(response.get(0).getDisk(), new Integer(10)); - assertEquals(response.get(0).getRam(), new Integer(256)); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + assertEquals(response.get(0).getId(), 1); + assertEquals(response.get(0).getName(), "256 MB Server"); + assertEquals(response.get(0).getDisk(), new Integer(10)); + assertEquals(response.get(0).getRam(), new Integer(256)); - assertEquals(response.get(1).getId(), 2); - assertEquals(response.get(1).getName(), "512 MB Server"); - assertEquals(response.get(1).getDisk(), new Integer(20)); - assertEquals(response.get(1).getRam(), new Integer(512)); + assertEquals(response.get(1).getId(), 2); + assertEquals(response.get(1).getName(), "512 MB Server"); + assertEquals(response.get(1).getDisk(), new Integer(20)); + assertEquals(response.get(1).getRam(), new Integer(512)); - } + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java index d9357d0e98..550406e300 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageFromJsonResponseTest.java @@ -42,49 +42,49 @@ import static org.testng.Assert.assertEquals; */ @Test(groups = "unit") public class ParseImageFromJsonResponseTest { - Injector i = Guice.createInjector(new AbstractModule() { + Injector i = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } + + }, new GsonModule()); + + DateService dateService = i.getInstance(DateService.class); + + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + Image response = parseImage(); + + assertEquals(response.getId(), 2); + assertEquals(response.getName(), "CentOS 5.2"); + assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); + assertEquals(response.getProgress(), new Integer(80)); + assertEquals(response.getStatus(), ImageStatus.SAVING); + assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z"))); + assertEquals(response.getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); + assertEquals(response.getMetadata().get("ImageVersion"), "1.5"); + assertEquals(response.getMetadata().get("ImageType"), "Gold"); + assertEquals(response.getMetadata().size(), 2); + } + + public static Image parseImage() { + Injector i = Guice.createInjector(new AbstractModule() { + + @Override + protected void configure() { bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } + } - }, new GsonModule()); + }, new GsonModule()); - DateService dateService = i.getInstance(DateService.class); + InputStream is = ParseImageFromJsonResponseTest.class.getResourceAsStream("/test_get_image_details.json"); - @Test - public void testApplyInputStreamDetails() throws UnknownHostException { - Image response = parseImage(); - - assertEquals(response.getId(), 1); - assertEquals(response.getName(), "CentOS 5.2"); - assertEquals(response.getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); - assertEquals(response.getProgress(), new Integer(80)); - assertEquals(response.getStatus(), ImageStatus.SAVING); - assertEquals(response.getUpdated(), dateService.iso8601SecondsDateParse(("2010-10-10T12:00:00Z"))); - assertEquals(response.getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); - assertEquals(response.getMetadata().get("ImageVersion"), "1.5"); - assertEquals(response.getMetadata().get("ImageType"), "Gold"); - assertEquals(response.getMetadata().size(), 2); - } - - public static Image parseImage() { - Injector i = Guice.createInjector(new AbstractModule() { - - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } - - }, new GsonModule()); - - InputStream is = ParseImageFromJsonResponseTest.class.getResourceAsStream("/test_get_image_details.json"); - - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - return response; - } + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + Image response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + return response; + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java index 4de761a6ac..9fe0df1e36 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseImageListFromJsonResponseTest.java @@ -44,57 +44,62 @@ import static org.testng.Assert.assertEquals; */ @Test(groups = "unit") public class ParseImageListFromJsonResponseTest { - Injector i = Guice.createInjector(new AbstractModule() { + Injector i = Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } + @Override + protected void configure() { + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } - }, new GsonModule()); - DateService dateService = i.getInstance(DateService.class); + }, new GsonModule()); + DateService dateService = i.getInstance(DateService.class); - @Test - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_images.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_images.json"); - List expects = ImmutableList.of(new Image(1, "CentOS 5.2"), new Image(743, "My Server Backup")); + List expects = ImmutableList.of(new Image(1, "CentOS 5.2"), new Image(743, "My Server Backup")); - UnwrapOnlyJsonValue> parser = i.getInstance( - Key.get(new TypeLiteral>>() {})); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + assertEquals(response, expects); + } - @Test - public void testApplyInputStreamDetails() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_images_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 1); - assertEquals(response.get(0).getName(), "CentOS 5.2"); - assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); - assertEquals(response.get(0).getProgress(), null); - assertEquals(response.get(0).getServerRef(), null); - assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE); - assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); - assertEquals(response.get(0).getMetadata().get("ImageType"), "Gold"); - assertEquals(response.get(0).getMetadata().get("ImageVersion"), "1.5"); - assertEquals(response.get(0).getMetadata().size(), 2); + assertEquals(response.get(0).getId(), 1); + assertEquals(response.get(0).getName(), "CentOS 5.2"); + assertEquals(response.get(0).getCreated(), dateService.iso8601SecondsDateParse("2010-08-10T12:00:00Z")); + assertEquals(response.get(0).getProgress(), null); + assertEquals(response.get(0).getServerRef(), null); + assertEquals(response.get(0).getStatus(), ImageStatus.ACTIVE); + assertEquals(response.get(0).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); + assertEquals(response.get(0).getMetadata().get("ImageType"), "Gold"); + assertEquals(response.get(0).getMetadata().get("ImageVersion"), "1.5"); + assertEquals(response.get(0).getMetadata().size(), 2); - assertEquals(response.get(1).getId(), 743); - assertEquals(response.get(1).getName(), "My Server Backup"); - assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16Z")); - assertEquals(response.get(1).getProgress(), new Integer(80)); - assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); - assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); - assertEquals(response.get(1).getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); - } + assertEquals(response.get(1).getId(), 743); + assertEquals(response.get(1).getName(), "My Server Backup"); + assertEquals(response.get(1).getCreated(), dateService.iso8601SecondsDateParse("2009-07-07T09:56:16Z")); + + assertEquals(response.get(1).getProgress(), new Integer(80)); + assertEquals(response.get(1).getStatus(), ImageStatus.SAVING); + assertEquals(response.get(1).getUpdated(), dateService.iso8601SecondsDateParse("2010-10-10T12:00:00Z")); + assertEquals(response.get(1).getServerRef(), "http://servers.api.openstack.org/v1.1/1234/servers/12"); + + //short form of reference + assertEquals(response.get(2).getServerRef(), "12"); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java index 12d7980a55..e34ffaf23b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java @@ -19,7 +19,6 @@ package org.jclouds.openstack.nova.functions; import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -27,14 +26,12 @@ import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Address; import org.testng.annotations.Test; import java.io.InputStream; import java.net.UnknownHostException; import java.util.List; -import java.util.Map; import static org.testng.Assert.assertEquals; @@ -46,36 +43,35 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseInetAddressListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new ParserModule()); - @Test - public void testPublic() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); + @Test + public void testPublic() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses_public.json"); - UnwrapOnlyJsonValue>> parser = i.getInstance( - Key.get(new TypeLiteral>>>() {})); - List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))) - .get("public"); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - List
addresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), - Address.newString2AddressFunction())); - assertEquals(response, addresses); - } + assertEquals(response, ImmutableList.of(Address.valueOf("67.23.10.132"), + Address.valueOf("::babe:67.23.10.132"), + Address.valueOf("67.23.10.131"), Address.valueOf("::babe:4317:0A83"))); + } - @Test - public void testPrivate() throws UnknownHostException { - InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); + @Test + public void testPrivate() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_addresses_private.json"); - UnwrapOnlyJsonValue>> parser = i.getInstance( - Key.get(new TypeLiteral>>>() {})); - List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))) - .get("private"); - - List
addresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), - Address.newString2AddressFunction())); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List
response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, addresses); - } + assertEquals(response, ImmutableList.of(Address.valueOf("67.23.10.132"), + Address.valueOf("::babe:67.23.10.132"), + Address.valueOf("67.23.10.131"), Address.valueOf("::babe:4317:0A83"))); + + + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java new file mode 100644 index 0000000000..8392b741c6 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java @@ -0,0 +1,19 @@ +package org.jclouds.openstack.nova.functions; + +import org.jclouds.json.config.GsonModule; + +/** + * Created by IntelliJ IDEA. + * User: VGalkin + * Date: 4/16/11 + * Time: 7:47 AM + * To change this template use File | Settings | File Templates. + */ +class ParserModule extends GsonModule { + + @Override + protected void configure() { + super.configure(); + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 7fd3e8f94d..70e12db6e0 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -28,7 +28,6 @@ import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Server; @@ -37,8 +36,12 @@ import org.testng.annotations.Test; import java.io.InputStream; import java.net.UnknownHostException; +import java.text.ParseException; +import java.text.SimpleDateFormat; import java.util.HashSet; import java.util.List; +import java.util.Locale; +import java.util.SimpleTimeZone; import static org.testng.Assert.assertEquals; @@ -50,38 +53,46 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseServerFromJsonResponseTest { - @Test - public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { - Server response = parseServer(); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, ParseException { + Server response = parseServer(); - assertEquals(response.getId(), 1234); - assertEquals(response.getName(), "sample-server"); - assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); - assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(response.getStatus(), ServerStatus.BUILD); - assertEquals(response.getProgress(), new Integer(60)); + assertEquals(response.getId(), 1234); + assertEquals(response.getName(), "sample-server"); + assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); + assertEquals(response.getStatus(), ServerStatus.BUILD); + assertEquals(response.getProgress(), new Integer(60)); + SimpleDateFormat dateFormat = new SimpleDateFormat( + "yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); + dateFormat.setTimeZone(new SimpleTimeZone(0, "GMT")); + assertEquals(response.getCreated(), + dateFormat.parse("2010-08-10T12:00:00Z")); + assertEquals(response.getUpdated(), + dateFormat.parse("2010-10-10T12:00:00Z")); - List
publicAddresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), - Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), - Address.newString2AddressFunction())); - Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); - assertEquals(response.getAddresses(), addresses1); - assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); - assertEquals(response.getAddresses(), addresses1); - } - public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { - Injector i = Guice.createInjector(new GsonModule()); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); + assertEquals(response.getAddresses(), addresses1); + assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.getAddresses(), addresses1); + } - InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); + public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { - return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - } + Injector i = Guice.createInjector(new ParserModule()); + + InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); + + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + + //Function parser = i.getInstance(getParserOrThrowException(NovaClient.class.getMethod("getServer", int.class))); + return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index f9bb444875..0c61c1deb7 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -28,7 +28,6 @@ import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Address; import org.jclouds.openstack.nova.domain.Addresses; import org.jclouds.openstack.nova.domain.Server; @@ -36,8 +35,6 @@ import org.jclouds.openstack.nova.domain.ServerStatus; import org.testng.annotations.Test; import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.HashSet; import java.util.List; @@ -52,69 +49,62 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseServerListFromJsonResponseTest { - Injector i = Guice.createInjector(new GsonModule()); + Injector i = Guice.createInjector(new ParserModule()); - @Test - public void testApplyInputStream() { - InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); + @Test + public void testApplyInputStream() { + InputStream is = getClass().getResourceAsStream("/test_list_servers.json"); - List expects = ImmutableList.of(new Server(1234, "sample-server"), new Server(5678, "sample-server2")); + List expects = ImmutableList.of(new Server(1234, "sample-server"), new Server(5678, "sample-server2")); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response, expects); - } + assertEquals(response, expects); + } - @Test - public void testApplyInputStreamDetails() throws UnknownHostException, URISyntaxException { - InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); + @Test + public void testApplyInputStreamDetails() throws UnknownHostException { + InputStream is = getClass().getResourceAsStream("/test_list_servers_detail.json"); - UnwrapOnlyJsonValue> parser = i.getInstance(Key - .get(new TypeLiteral>>() { - })); - List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); + UnwrapOnlyJsonValue> parser = i.getInstance(Key + .get(new TypeLiteral>>() { + })); + List response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - assertEquals(response.get(0).getId(), 1234); - assertEquals(response.get(0).getName(), "sample-server"); - assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); - assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); - assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); - assertEquals(response.get(0).getProgress(), new Integer(60)); + assertEquals(response.get(0).getId(), 1234); + assertEquals(response.get(0).getName(), "sample-server"); + assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); + assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.get(0).getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); + assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); + assertEquals(response.get(0).getProgress(), new Integer(60)); - List
publicAddresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), - Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), - Address.newString2AddressFunction())); - Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); - assertEquals(response.get(0).getAddresses(), addresses1); - assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); - assertEquals(response.get(1).getId(), 5678); - assertEquals(response.get(1).getName(), "sample-server2"); - assertEquals(response.get(0).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.get(0).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); - assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); - assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); - assertEquals(response.get(1).getProgress(), null); + assertEquals(response.get(0).getAddresses(), addresses1); + assertEquals(response.get(0).getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); + assertEquals(response.get(1).getId(), 5678); + assertEquals(response.get(1).getName(), "sample-server2"); + assertEquals(response.get(1).getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1"); + assertEquals(response.get(1).getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.get(1).getAffinityId(), "b414fa41cb37b97dcb58d6c76112af1258e9eae2"); + assertEquals(response.get(1).getHostId(), "9e107d9d372bb6826bd81d3542a419d6"); + assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); + assertEquals(response.get(1).getProgress(), null); - List
publicAddresses2 = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"), - Address.newString2AddressFunction())); - List
privateAddresses2 = ImmutableList.copyOf(Iterables.transform( - ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"), - Address.newString2AddressFunction())); - Addresses addresses2 = new Addresses(new HashSet
(publicAddresses2), new HashSet
(privateAddresses2)); + List
publicAddresses2 = ImmutableList.of(new Address("67.23.10.133", 4), new Address("::babe:67.23.10.133", 6)); + List
privateAddresses2 = ImmutableList.of(new Address("10.176.42.17", 4), new Address("::babe:10.176.42.17", 6)); + Addresses addresses2 = new Addresses(new HashSet
(publicAddresses2), new HashSet
(privateAddresses2)); - assertEquals(response.get(1).getAddresses(), addresses2); - assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); - assertEquals(response.get(1).getURI(), new URI("http://servers.api.openstack.org/v1.1/1234/servers/5678")); + assertEquals(response.get(1).getAddresses(), addresses2); + assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); + assertEquals(response.get(1).getURI(), "http://servers.api.openstack.org/1234/servers/56789"); - } + } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java index cd198667ce..11ace1d635 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java @@ -18,20 +18,18 @@ */ package org.jclouds.openstack.nova.options; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.testng.Assert.assertEquals; - -import java.net.URI; - -import javax.ws.rs.HttpMethod; - +import com.google.common.collect.ImmutableMap; +import com.google.inject.Guice; +import com.google.inject.Injector; import org.jclouds.http.HttpRequest; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Guice; -import com.google.inject.Injector; +import javax.ws.rs.HttpMethod; +import java.net.URI; + +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} @@ -41,41 +39,41 @@ import com.google.inject.Injector; @Test(groups = "unit") public class CreateServerOptionsTest { - Injector injector = Guice.createInjector(new GsonModule()); + Injector injector = Guice.createInjector(new GsonModule()); - @Test - public void testAddPayloadToRequestMapOfStringStringHttpRequest() { - CreateServerOptions options = new CreateServerOptions(); - HttpRequest request = buildRequest(options); - assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\"}}", request.getPayload().getRawContent()); - } + @Test + public void testAddPayloadToRequestMapOfStringStringHttpRequest() { + CreateServerOptions options = new CreateServerOptions(); + HttpRequest request = buildRequest(options); + assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2}}", request.getPayload().getRawContent()); + } - private HttpRequest buildRequest(CreateServerOptions options) { - injector.injectMembers(options); - HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); - options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2")); - return request; - } + private HttpRequest buildRequest(CreateServerOptions options) { + injector.injectMembers(options); + HttpRequest request = new HttpRequest(HttpMethod.POST, URI.create("http://localhost")); + options.bindToRequest(request, ImmutableMap.of("name", "foo", "imageRef", "1", "flavorRef", "2")); + return request; + } - @Test - public void testWithFile() { - CreateServerOptions options = new CreateServerOptions(); - options.withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFile() { + CreateServerOptions options = new CreateServerOptions(); + options.withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - @Test - public void testWithFileStatic() { - CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); - HttpRequest request = buildRequest(options); - assertFile(request); - } + @Test + public void testWithFileStatic() { + CreateServerOptions options = withFile("/tmp/rhubarb", "foo".getBytes()); + HttpRequest request = buildRequest(options); + assertFile(request); + } - private void assertFile(HttpRequest request) { - assertEquals(request.getPayload().getRawContent(), - "{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\",\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); - } + private void assertFile(HttpRequest request) { + assertEquals(request.getPayload().getRawContent(), + "{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); + } @Test public void testWithMetadata() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/ListOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/ListOptionsTest.java index f87773cf17..27d92cbd87 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/ListOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/ListOptionsTest.java @@ -18,21 +18,17 @@ */ package org.jclouds.openstack.nova.options; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.maxResults; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.startAt; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableList; +import org.testng.annotations.Test; import java.util.Date; -import org.testng.annotations.Test; - -import com.google.common.collect.ImmutableList; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.*; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ListOptions} - * + * * @author Adrian Cole */ @Test(groups = "unit") @@ -52,7 +48,7 @@ public class ListOptionsTest { Date ifModifiedSince = new Date(); ListOptions options = new ListOptions().changesSince(ifModifiedSince); assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options - .buildQueryParameters().get("changes-since")); + .buildQueryParameters().get("changes-since")); } public void testStartAt() { @@ -71,7 +67,7 @@ public class ListOptionsTest { Date ifModifiedSince = new Date(); ListOptions options = changesSince(ifModifiedSince); assertEquals(ImmutableList.of(ifModifiedSince.getTime() / 1000 + ""), options - .buildQueryParameters().get("changes-since")); + .buildQueryParameters().get("changes-since")); } public void testStartAtStatic() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java index e3c33156fe..b70b6f06e5 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/RebuildServerOptionsTest.java @@ -18,24 +18,22 @@ */ package org.jclouds.openstack.nova.options; -import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; -import static org.testng.Assert.assertEquals; - -import java.net.URI; -import java.util.HashMap; - -import javax.ws.rs.HttpMethod; - +import com.google.inject.Guice; +import com.google.inject.Injector; import org.jclouds.http.HttpRequest; import org.jclouds.json.config.GsonModule; import org.testng.annotations.Test; -import com.google.inject.Guice; -import com.google.inject.Injector; +import javax.ws.rs.HttpMethod; +import java.net.URI; +import java.util.HashMap; + +import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseFlavorFromJsonResponse} - * + * * @author Adrian Cole */ @Test(groups = "unit") diff --git a/sandbox-apis/nova/src/test/resources/test_get_image_details.json b/sandbox-apis/nova/src/test/resources/test_get_image_details.json index 035e3beffa..3e3b93fb02 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_image_details.json +++ b/sandbox-apis/nova/src/test/resources/test_get_image_details.json @@ -1,6 +1,6 @@ { "image" : { - "id" : 1, + "id" : 2, "name" : "CentOS 5.2", "serverRef" : "http://servers.api.openstack.org/v1.1/1234/servers/12", "updated" : "2010-10-10T12:00:00Z", @@ -10,7 +10,7 @@ "metadata" : { "ImageVersion" : "1.5", "ImageType" : "Gold" - }, + }, "links": [ { "rel" : "self", diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses.json b/sandbox-apis/nova/src/test/resources/test_list_addresses.json index 14dd5e898d..8f3b3aab93 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses.json @@ -1,15 +1,15 @@ { "addresses" : { - "public" : [ - {"version" : 4, "addr" : "67.23.10.132"}, - {"version" : 6, "addr" : "::babe:67.23.10.132"}, - {"version" : 4, "addr" : "67.23.10.131"}, - {"version" : 6, "addr" : "::babe:4317:0A83"} - ], - "private" : [ - {"version" : 4, "addr" : "10.176.42.16"}, - {"version" : 6, "addr" : "::babe:10.176.42.16"} - ] - } + "public" : [ + {"version" : 4, "addr" : "67.23.10.132"}, + {"version" : 6, "addr" : "::babe:67.23.10.132"}, + {"version" : 4, "addr" : "67.23.10.131"}, + {"version" : 6, "addr" : "::babe:4317:0A83"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + } } diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json index 62935ae947..eb49fbdf1e 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_private.json @@ -1,10 +1,8 @@ { - "network" : { - "private" : [ + "private":[ {"version" : 4, "addr" : "67.23.10.132"}, {"version" : 6, "addr" : "::babe:67.23.10.132"}, {"version" : 4, "addr" : "67.23.10.131"}, {"version" : 6, "addr" : "::babe:4317:0A83"} ] - } } diff --git a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json index 0c7a67a2b2..60bf20f718 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json +++ b/sandbox-apis/nova/src/test/resources/test_list_addresses_public.json @@ -1,10 +1,8 @@ { - "network" : { - "public" : [ + "public" : [ {"version" : 4, "addr" : "67.23.10.132"}, {"version" : 6, "addr" : "::babe:67.23.10.132"}, {"version" : 4, "addr" : "67.23.10.131"}, {"version" : 6, "addr" : "::babe:4317:0A83"} ] - } } diff --git a/sandbox-apis/nova/src/test/resources/test_list_flavors.json b/sandbox-apis/nova/src/test/resources/test_list_flavors.json index 51ef1bc28f..5953f252a2 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_flavors.json +++ b/sandbox-apis/nova/src/test/resources/test_list_flavors.json @@ -20,6 +20,7 @@ } ] }, + { "id" : 2, "name" : "512 MB Server", @@ -42,3 +43,4 @@ } ] } + diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers.json b/sandbox-apis/nova/src/test/resources/test_list_servers.json index 82c53075c7..8cf580c3fc 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers.json @@ -1,5 +1,5 @@ { - "servers" : [ + "servers" : [ { "id" : 1234, "name" : "sample-server", diff --git a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json index 15bb6b491d..d428ced299 100644 --- a/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_list_servers_detail.json @@ -12,17 +12,17 @@ "status" : "BUILD", "progress" : 60, "addresses" : { - "public" : [ + "public" : [ {"version" : 4, "addr" : "67.23.10.132"}, {"version" : 6, "addr" : "::babe:67.23.10.132"}, {"version" : 4, "addr" : "67.23.10.131"}, {"version" : 6, "addr" : "::babe:4317:0A83"} ], "private" : [ - {"version" : 4, "addr" : "10.176.42.16"}, - {"version" : 6, "addr" : "::babe:10.176.42.16"} - ] - }, + {"version" : 4, "addr" : "10.176.42.16"}, + {"version" : 6, "addr" : "::babe:10.176.42.16"} + ] + }, "metadata" : { "Server Label" : "Web Head 1", "Image Version" : "2.1" @@ -55,14 +55,14 @@ "affinityId" : "b414fa41cb37b97dcb58d6c76112af1258e9eae2", "status" : "ACTIVE", "addresses" : { - "public" : [ - {"version" : 4, "addr" : "67.23.10.133"}, - {"version" : 6, "addr" : "::babe:67.23.10.133"} - ], - "private" : [ - {"version" : 4, "addr" : "10.176.42.17"}, - {"version" : 6, "addr" : "::babe:10.176.42.17"} - ] + "public" : [ + {"version" : 4, "addr" : "67.23.10.133"}, + {"version" : 6, "addr" : "::babe:67.23.10.133"} + ], + "private" : [ + {"version" : 4, "addr" : "10.176.42.17"}, + {"version" : 6, "addr" : "::babe:10.176.42.17"} + ] }, "metadata" : { "Server Label" : "DB 1" From 7f02824928c929490204320f222e0c5212db9f37 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Mon, 18 Apr 2011 20:15:56 +0400 Subject: [PATCH 35/95] Fixes in live tests --- .../openstack/nova/NovaClientLiveTest.java | 151 +++++++--------- .../openstack/nova/PropertyHelper.java | 7 +- .../openstack/nova/live/ServerCreateTest.java | 171 ++++++++++++++++++ .../nova/src/test/resources/keys/rhelimpg.pub | 0 4 files changed, 238 insertions(+), 91 deletions(-) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java create mode 100644 sandbox-apis/nova/src/test/resources/keys/rhelimpg.pub diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index ef8735c34c..922495b409 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -26,7 +26,6 @@ import com.google.common.collect.Iterables; import com.google.inject.Injector; import com.google.inject.Module; import org.jclouds.Constants; -import org.jclouds.compute.domain.ExecResponse; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; @@ -75,15 +74,16 @@ public class NovaClientLiveTest { protected String endpoint; protected String apiversion; + private String ip; + + private String adminPass2; + + private String serverPrefix = System.getProperty("user.name") + ".cs"; private int serverId; private String adminPass; Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private String ip; - private int serverId2; - private String adminPass2; - private int imageId; - + private int createdImageId; protected Properties setupProperties() throws IOException { Properties overrides = new Properties(); @@ -266,6 +266,7 @@ public class NovaClientLiveTest { assert client.getFlavor(12312987) == null; } + @Test(enabled = true) public void testCreateServer() throws Exception { String imageRef = client.getImage(13).getURI().toASCIIString(); @@ -279,7 +280,8 @@ public class NovaClientLiveTest { serverId = server.getId(); adminPass = server.getAdminPass(); blockUntilServerActive(serverId); - ip = client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); + Thread.sleep(2000); + client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); } private void blockUntilServerActive(int serverId) throws InterruptedException { @@ -300,39 +302,38 @@ public class NovaClientLiveTest { } } - private void blockUntilImageActive(int imageId) throws InterruptedException { + private void blockUntilImageActive(int createdImageId) throws InterruptedException { Image currentDetails; - for (currentDetails = client.getImage(imageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client - .getImage(imageId)) { + for (currentDetails = client.getImage(createdImageId); currentDetails.getStatus() != ImageStatus.ACTIVE; currentDetails = client + .getImage(createdImageId)) { System.out.printf("blocking on status active%n%s%n", currentDetails); Thread.sleep(5 * 1000); } } - @Test(enabled = true, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + @Test(enabled = true, timeOut = 300000) public void testServerDetails() throws Exception { + if (serverId <= 0) testCreateServer(); Server server = client.getServer(serverId); assertNotNull(server.getHostId()); assertEquals(server.getStatus(), ServerStatus.ACTIVE); - assertNotNull(server.getAddresses()); - - // check metadata assertEquals(server.getMetadata(), metadata); - assertPassword(server, adminPass); - assertEquals(server.getFlavorRef(), endpoint + "/flavors/1"); - assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); - assertEquals(server.getImageRef(), endpoint + "/images/13"); + + + assertEquals(server.getImageRef(), endpoint + "/v1.1/images/13"); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); 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()); - + assertPassword(server, adminPass); + assertEquals(server.getFlavorRef(), endpoint + "/v1.1/flavors/1"); + assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); } @@ -352,21 +353,9 @@ public class NovaClientLiveTest { } } - private ExecResponse exec(Server details, String pass, String command) throws IOException { - IPSocket socket = new IPSocket(Iterables.get(details.getAddresses().getPublicAddresses(), 0).getAddress(), 22); - socketTester.apply(socket); - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); - try { - client.connect(); - return client.exec(command); - } finally { - if (client != null) - client.disconnect(); - } - } - - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testRenameServer() throws Exception { + if (serverId <= 0) testCreateServer(); Server server = client.getServer(serverId); String oldName = server.getName(); client.renameServer(serverId, oldName + "new"); @@ -374,99 +363,92 @@ public class NovaClientLiveTest { assertEquals(oldName + "new", client.getServer(serverId).getName()); } - @Test(enabled = false, timeOut = 5 * 60 * 1000, dependsOnMethods = "testCreateServer") + @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testChangePassword() throws Exception { + if (serverId <= 0) testCreateServer(); client.changeAdminPass(serverId, "elmo"); blockUntilServerActive(serverId); assertPassword(client.getServer(serverId), "elmo"); this.adminPass = "elmo"; } - 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); - } catch (Exception e) { - e.printStackTrace(); - } catch (AssertionError e) { - e.printStackTrace(); - } - } - - private void assertIpNotConfigured(Server server, String password) throws IOException { - 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); - } - - - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testBackup") + @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testCreateImage() throws Exception { + if (serverId <= 0) testCreateServer(); Image image = client.createImageFromServer("hoofie", serverId); assertEquals("hoofie", image.getName()); assertEquals(serverId, image.getServerRef()); - imageId = image.getId(); - blockUntilImageActive(imageId); + createdImageId = image.getId(); + blockUntilImageActive(createdImageId); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testCreateImage") + @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebuildServer() throws Exception { - client.rebuildServer(serverId, new RebuildServerOptions().withImage(imageId)); + if (serverId <= 0) testCreateServer(); + client.rebuildServer(serverId, new RebuildServerOptions().withImage(String.valueOf(createdImageId))); blockUntilServerActive(serverId); - // issue Web Hosting #119580 imageId comes back incorrect after rebuild - assertEquals(imageId, client.getServer(serverId).getImageRef()); + // issue Web Hosting #119580 createdImageId comes back incorrect after rebuild + assertEquals(createdImageId, client.getServer(serverId).getImageRef()); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebuildServer") + @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootHard() throws Exception { + if (serverId <= 0) testCreateServer(); client.rebootServer(serverId, RebootType.HARD); blockUntilServerActive(serverId); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootHard") + @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootSoft() throws Exception { + if (serverId <= 0) testCreateServer(); client.rebootServer(serverId, RebootType.SOFT); blockUntilServerActive(serverId); } @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") public void testRevertResize() throws Exception { + if (serverId <= 0) testCreateServer(); client.resizeServer(serverId, 2); blockUntilServerVerifyResize(serverId); client.revertResizeServer(serverId); blockUntilServerActive(serverId); - assertEquals(new Integer(1), client.getServer(serverId).getFlavorRef()); + assertEquals(1, client.getServer(serverId).getFlavorRef()); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + @Test(enabled = false, timeOut = 10 * 60 * 1000) public void testConfirmResize() throws Exception { - client.resizeServer(serverId2, 2); - blockUntilServerVerifyResize(serverId2); - client.confirmResizeServer(serverId2); - blockUntilServerActive(serverId2); - assertEquals(new Integer(2), client.getServer(serverId2).getFlavorRef()); + if (serverId <= 0) testCreateServer(); + client.resizeServer(serverId, 2); + blockUntilServerVerifyResize(serverId); + client.confirmResizeServer(serverId); + blockUntilServerActive(serverId); + assertEquals(2, client.getServer(serverId).getFlavorRef()); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = {"testRebootSoft", "testRevertResize", - "testConfirmResize"}) - void deleteServer2() { - if (serverId2 > 0) { - client.deleteServer(serverId2); - assert client.getServer(serverId2) == null; + @Test(enabled = true, timeOut = 10 * 60 * 1000) + void deleteServer2() throws Exception { + if (serverId <= 0) testCreateServer(); + if (serverId > 0) { + client.deleteServer(serverId); + Thread.sleep(1000); + assert client.getServer(serverId) == null; } } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "deleteServer2") - void testDeleteImage() { - if (imageId > 0) { - client.deleteImage(imageId); - assert client.getImage(imageId) == null; + @Test(enabled = true, timeOut = 10 * 60 * 1000) + void testDeleteImage() throws Exception { + if (createdImageId <= 0) { + testCreateImage(); + } + if (createdImageId > 0) { + client.deleteImage(createdImageId); + assert client.getImage(createdImageId) == null; } } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testDeleteImage") - void deleteServer1() { + @Test(enabled = true, timeOut = 10 * 60 * 1000) + void deleteServer1() throws Exception { + if (serverId <= 0) testCreateServer(); if (serverId > 0) { client.deleteServer(serverId); assert client.getServer(serverId) == null; @@ -476,10 +458,7 @@ public class NovaClientLiveTest { @AfterTest void deleteServersOnEnd() { if (serverId > 0) { - //client.deleteServer(serverId); - } - if (serverId2 > 0) { - client.deleteServer(serverId2); + client.deleteServer(serverId); } } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java index 0a0432420b..8d24ec5102 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java @@ -3,12 +3,9 @@ package org.jclouds.openstack.nova; import java.util.Properties; /** - * Created by IntelliJ IDEA. - * User: VGalkin - * Date: 4/14/11 - * Time: 4:32 PM - * To change this template use File | Settings | File Templates. + * @author Victor Galkin */ + public class PropertyHelper { public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java new file mode 100644 index 0000000000..e62772594d --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java @@ -0,0 +1,171 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova.live; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Injector; +import com.google.inject.Module; +import org.jclouds.Constants; +import org.jclouds.http.HttpResponseException; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.NovaClient; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.jclouds.predicates.RetryablePredicate; +import org.jclouds.predicates.SocketOpen; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.ssh.SshClient; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; + +/** + * @author Victor Galkin + */ + +@Test(groups = "live", sequential = true) +public class ServerCreateTest { + + protected NovaClient client; + protected SshClient.Factory sshFactory; + private Predicate socketTester; + protected String provider = "nova"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + Server server = null; + + + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } + + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } + + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } + + + @BeforeGroups(groups = {"live"}) + public void setupClient() throws IOException { + Properties overrides = setupProperties(); + setupCredentials(overrides); + updateProperties(overrides); + + Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) + .buildInjector(); + + client = injector.getInstance(NovaClient.class); + + sshFactory = injector.getInstance(SshClient.Factory.class); + SocketOpen socketOpen = injector.getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); + injector.injectMembers(socketOpen); // add logger + } + + @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") + public void testCreateServerWithUnknownImage() throws Exception { + try { + server = client.createServer("serverName", String.valueOf(88888888), "1", withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + } catch (HttpResponseException e) { + throw e; + } + } + + @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") + public void testCreateServerWithUnknownFlavor() throws Exception { + try { + server = client.createServer("serverName", String.valueOf(13), "88888888", withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + } catch (HttpResponseException e) { + throw e; + } + } + + @AfterMethod + public void after() { + if (server != null) client.deleteServer(server.getId()); + } + + @Test(enabled = true) + public void testCreateServer() throws Exception { +// String imageRef = client.getImage(13).getURI().toASCIIString(); +// String flavorRef = client.getFlavor(1).getURI().toASCIIString(); +// String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); +// Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", +// "rackspace".getBytes()).withMetadata(metadata)); +// +// assertNotNull(server.getAdminPass()); +// assertEquals(server.getStatus(), ServerStatus.BUILD); +// serverId = server.getId(); +// adminPass = server.getAdminPass(); +// blockUntilServerActive(serverId); +// client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); + } + + private void blockUntilServerActive(int serverId) throws InterruptedException { + Server currentDetails; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } +} diff --git a/sandbox-apis/nova/src/test/resources/keys/rhelimpg.pub b/sandbox-apis/nova/src/test/resources/keys/rhelimpg.pub new file mode 100644 index 0000000000..e69de29bb2 From 06b99c1cdc2af6a7fbe900968798b57f6b11a1d0 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev <-> Date: Mon, 18 Apr 2011 21:37:01 +0400 Subject: [PATCH 36/95] unit test fixes --- .../compute/functions/NovaImageToImage.java | 3 - .../functions/ServerToNodeMetadata.java | 62 ++++----- .../openstack/nova/domain/Address.java | 1 + .../openstack/nova/domain/Resource.java | 10 +- .../functions/FlavorToHardwareTest.java | 17 ++- .../functions/NovaImageToImageTest.java | 39 +++--- .../functions/ServerToNodeMetadataTest.java | 128 +++++++++++------- .../ParseAddressesFromJsonResponseTest.java | 21 +-- ...seInetAddressListFromJsonResponseTest.java | 3 +- .../openstack/nova/functions/ParseModule.java | 19 --- .../ParseServerFromJsonResponseTest.java | 57 ++++---- .../ParseServerListFromJsonResponseTest.java | 58 +++++--- .../resources/test_get_image_details.json | 2 +- .../resources/test_get_server_detail.json | 4 +- 14 files changed, 239 insertions(+), 185 deletions(-) delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java index 6a880dd9fc..e606c5b13a 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImage.java @@ -28,9 +28,6 @@ import org.jclouds.domain.Credentials; import com.google.common.base.Function; -import java.util.List; -import java.util.Map; - /** * * @author Adrian Cole diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java index 2e131ad622..715a2521a0 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadata.java @@ -18,39 +18,32 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; - -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -import javax.annotation.Resource; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import org.jclouds.openstack.nova.domain.Address; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.base.Supplier; +import com.google.common.collect.Iterables; import org.jclouds.collect.Memoized; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.*; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; import org.jclouds.domain.LocationScope; import org.jclouds.logging.Logger; +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.Iterables; +import javax.annotation.Resource; +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; /** * @author Adrian Cole @@ -95,8 +88,8 @@ public class ServerToNodeMetadata implements Function { @Inject ServerToNodeMetadata(Map serverStateToNodeState, Map credentialStore, - @Memoized Supplier> images, Supplier location, - @Memoized Supplier> hardwares) { + @Memoized Supplier> images, Supplier location, + @Memoized Supplier> hardwares) { this.serverToNodeState = checkNotNull(serverStateToNodeState, "serverStateToNodeState"); this.credentialStore = checkNotNull(credentialStore, "credentialStore"); this.images = checkNotNull(images, "images"); @@ -110,11 +103,14 @@ public class ServerToNodeMetadata implements Function { builder.ids(from.getId() + ""); builder.name(from.getName()); builder.location(new LocationBuilder().scope(LocationScope.HOST).id(from.getHostId()).description( - from.getHostId()).parent(location.get()).build()); + from.getHostId()).parent(location.get()).build()); builder.userMetadata(from.getMetadata()); builder.group(parseGroupFromName(from.getName())); - builder.imageId(from.getImageRef() + ""); - builder.operatingSystem(parseOperatingSystem(from)); + Image image = parseImage(from); + if (image != null) { + builder.imageId(image.getId()); + builder.operatingSystem(image.getOperatingSystem()); + } builder.hardware(parseHardware(from)); builder.state(serverToNodeState.get(from.getStatus())); builder.publicAddresses(Iterables.transform(from.getAddresses().getPublicAddresses(), Address.newAddress2StringFunction())); @@ -132,10 +128,10 @@ public class ServerToNodeMetadata implements Function { } return null; } - - protected OperatingSystem parseOperatingSystem(Server from) { + + protected Image parseImage(Server from) { try { - return Iterables.find(images.get(), new FindImageForServer(from)).getOperatingSystem(); + return Iterables.find(images.get(), new FindImageForServer(from)); } catch (NoSuchElementException e) { logger.warn("could not find a matching image for server %s in location %s", from, location); } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java index 8ef964acb9..96a8538d99 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Address.java @@ -14,6 +14,7 @@ public class Address { private int version; //for de-serialization + @SuppressWarnings("unused") private Address() { } diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java index b97f29f2f4..6e6f9f241e 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/Resource.java @@ -1,12 +1,13 @@ package org.jclouds.openstack.nova.domain; -import com.google.common.collect.Lists; - import java.net.URI; import java.net.URISyntaxException; import java.util.List; import java.util.Map; +import com.google.common.base.Functions; +import com.google.common.collect.Lists; + /** * @author Dmitri Babaev */ @@ -17,6 +18,11 @@ public class Resource { public URI getURI() { for (Map linkProperties : links) { try { + if (!Functions.forMap(linkProperties, "").apply("rel").equals("bookmark")) + continue; + if (!Functions.forMap(linkProperties, "").apply("type").contains("json")) + continue; + return new URI(linkProperties.get("href")); } catch (URISyntaxException e) { throw new RuntimeException(e); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java index fdab38a748..414f5ba06e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/FlavorToHardwareTest.java @@ -28,6 +28,8 @@ import org.jclouds.openstack.nova.domain.Flavor; import org.jclouds.openstack.nova.functions.ParseFlavorFromJsonResponseTest; import org.testng.annotations.Test; +import java.net.URI; +import java.net.URISyntaxException; import java.net.UnknownHostException; import static org.testng.Assert.assertEquals; @@ -40,11 +42,16 @@ public class FlavorToHardwareTest { Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); @Test - public void test() throws UnknownHostException { - assertEquals(convertFlavor(), new HardwareBuilder().ids("1").name("256 MB Server").processors( - ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true) - .build())).build()); + public void test() throws UnknownHostException, URISyntaxException { + Hardware flavor = convertFlavor(); + Hardware tempFlavor = new HardwareBuilder().ids("1").name("256 MB Server") + .processors(ImmutableList.of(new Processor(1.0, 1.0))) + .ram(256) + .volumes(ImmutableList.of( + new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true).bootDevice(true).build())) + .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) + .build(); + assertEquals(flavor, tempFlavor); } public static Hardware convertFlavor() { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index d5dc9151ea..c207d53357 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -18,8 +18,12 @@ */ package org.jclouds.openstack.nova.compute.functions; -import com.google.inject.AbstractModule; -import com.google.inject.Guice; +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; @@ -28,12 +32,11 @@ import org.jclouds.compute.domain.OsFamily; import org.jclouds.compute.reference.ComputeServiceConstants; import org.jclouds.domain.Credentials; import org.jclouds.json.Json; +import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.testng.annotations.Test; -import java.net.UnknownHostException; - -import static org.testng.Assert.assertEquals; +import com.google.inject.Guice; /** * @author Adrian Cole @@ -42,27 +45,23 @@ import static org.testng.Assert.assertEquals; public class NovaImageToImageTest { @Test - public void testApplyWhereImageNotFound() throws UnknownHostException { - assertEquals( - convertImage(), - new ImageBuilder() - .name("CentOS 5.2") - .operatingSystem( - new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) - .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("2").version("1286712000000").build()); + public void testApplyWhereImageNotFound() throws UnknownHostException, URISyntaxException { + Image image = new ImageBuilder() + .name("CentOS 5.2") + .operatingSystem( + new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) + .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) + .ids("1").version("1286712000000").uri(new URI("http://servers.api.openstack.org/1234/images/1")).build(); + Image parsedImage = convertImage(); + + assertEquals(parsedImage, image); } public static Image convertImage() { org.jclouds.openstack.nova.domain.Image image = ParseImageFromJsonResponseTest.parseImage(); NovaImageToImage parser = new NovaImageToImage(new NovaImageToOperatingSystem(new BaseComputeServiceContextModule() { - }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new AbstractModule() { - @Override - protected void configure() { - //To change body of implemented methods use File | Settings | File Templates. - } - }) + }.provideOsVersionMap(new ComputeServiceConstants.ReferenceData(), Guice.createInjector(new GsonModule()) .getInstance(Json.class)))); return parser.apply(image); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index 674f75b38e..cdc5a13838 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -18,11 +18,25 @@ */ package org.jclouds.openstack.nova.compute.functions; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import org.jclouds.compute.domain.*; +import static org.testng.Assert.assertEquals; + +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.util.Map; +import java.util.Set; + +import org.jclouds.compute.domain.Hardware; +import org.jclouds.compute.domain.HardwareBuilder; +import org.jclouds.compute.domain.Image; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.NodeMetadataBuilder; +import org.jclouds.compute.domain.NodeState; +import org.jclouds.compute.domain.OperatingSystem; +import org.jclouds.compute.domain.OsFamily; +import org.jclouds.compute.domain.Processor; +import org.jclouds.compute.domain.Volume; +import org.jclouds.compute.domain.VolumeBuilder; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -33,11 +47,10 @@ import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; import org.testng.annotations.Test; -import java.net.UnknownHostException; -import java.util.Map; -import java.util.Set; - -import static org.testng.Assert.assertEquals; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; /** * @author Adrian Cole @@ -47,7 +60,7 @@ public class ServerToNodeMetadataTest { Location provider = new LocationBuilder().scope(LocationScope.ZONE).id("dallas").description("description").build(); @Test - public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + public void testApplyWhereImageAndHardwareNotFoundButCredentialsFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { Credentials creds = new Credentials("root", "abdce"); Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; @@ -61,16 +74,13 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").credentials(creds).location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + NodeMetadata constructedMetadata = newNodeMetadataBuilder() + .credentials(creds).build(); + assertEquals(metadata, constructedMetadata); } @Test - public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + public void testApplyWhereImageAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Set images = ImmutableSet.of(); Set hardwares = ImmutableSet.of(); @@ -82,17 +92,31 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + NodeMetadata constructedMetadata = newNodeMetadataBuilder().build(); + + assertEquals(metadata, constructedMetadata); } + private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException { + return new NodeMetadataBuilder() + .state(NodeState.PENDING) + .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) + .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) + .id("1234") + .providerId("1234") + .name("sample-server") + .location(new LocationBuilder() + .scope(LocationScope.HOST) + .id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0") + .parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) + .uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); + } + @Test - public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + public void testApplyWhereImageFoundAndHardwareNotFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; org.jclouds.compute.domain.Image jcImage = NovaImageToImageTest.convertImage(); Set images = ImmutableSet.of(jcImage); @@ -105,19 +129,21 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + NodeMetadata constructedMetadata = newNodeMetadataBuilder() + .imageId("1") + .operatingSystem(new OperatingSystem.Builder() + .family(OsFamily.CENTOS) + .description("CentOS 5.2") + .version("5.2") + .is64Bit(true).build()) + .build(); + + assertEquals(metadata, constructedMetadata); } @Test - public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException { + public void testApplyWhereImageAndHardwareFound() throws UnknownHostException, NoSuchMethodException, ClassNotFoundException, URISyntaxException { Map serverStateToNodeState = NovaComputeServiceDependenciesModule.serverToNodeState; Set images = ImmutableSet.of(NovaImageToImageTest.convertImage()); Set hardwares = ImmutableSet.of(FlavorToHardwareTest.convertFlavor()); @@ -128,18 +154,28 @@ public class ServerToNodeMetadataTest { .ofInstance(provider), Suppliers.>ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); + + NodeMetadata constructedMetadata = newNodeMetadataBuilder() + .imageId("1") + .operatingSystem(new OperatingSystem.Builder() + .family(OsFamily.CENTOS) + .description("CentOS 5.2") + .version("5.2") + .is64Bit(true).build()) + .hardware(new HardwareBuilder() + .ids("1") + .name("256 MB Server") + .processors(ImmutableList.of(new Processor(1.0, 1.0))) + .ram(256) + .volumes(ImmutableList.of(new VolumeBuilder() + .type(Volume.Type.LOCAL) + .size(10.0f) + .durable(true) + .bootDevice(true).build())) + .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) + .build()) + .build(); - assertEquals(metadata, new NodeMetadataBuilder().state(NodeState.PENDING).publicAddresses( - ImmutableSet.of("67.23.10.132", "67.23.10.131")).privateAddresses(ImmutableSet.of("10.176.42.16")) - .imageId("2").hardware( - new HardwareBuilder().ids("1").name("256 MB Server").processors( - ImmutableList.of(new Processor(1.0, 1.0))).ram(256).volumes( - ImmutableList.of(new VolumeBuilder().type(Volume.Type.LOCAL).size(10.0f).durable(true) - .bootDevice(true).build())).build()).operatingSystem( - new OperatingSystemBuilder().family(OsFamily.CENTOS).description("CentOS 5.2").version("5.2") - .is64Bit(true).build()).id("1234").providerId("1234").name("sample-server").location( - new LocationBuilder().scope(LocationScope.HOST).id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0").parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")).build()); + assertEquals(metadata, constructedMetadata); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java index de27b9931c..a945d1522a 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseAddressesFromJsonResponseTest.java @@ -18,7 +18,9 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; @@ -33,8 +35,9 @@ import org.testng.annotations.Test; import java.io.InputStream; import java.net.UnknownHostException; +import java.util.List; -import static org.testng.Assert.assertEqualsNoOrder; +import static org.testng.Assert.assertTrue; /** * Tests behavior of {@code ParseAddressesFromJsonResponse} @@ -53,13 +56,15 @@ public class ParseAddressesFromJsonResponseTest { })); Addresses response = parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); - ImmutableSet
publicAddresses = ImmutableSet.of(new Address("67.23.10.132", 4) - , new Address("::babe:67.23.10.132", 6), new Address("67.23.10.131", 4), new Address("::babe:4317:0A83", 6)); + List
publicAddresses = ImmutableList.copyOf( + Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); - ImmutableSet
privateAddresses = ImmutableSet.of(new Address("10.176.42.16", 4), - new Address("::babe:10.176.42.16", 6)); + List
privateAddresses = ImmutableList.copyOf( + Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); - assertEqualsNoOrder(response.getPublicAddresses().toArray(), publicAddresses.toArray()); - assertEqualsNoOrder(response.getPrivateAddresses().toArray(), privateAddresses.toArray()); + assertTrue(response.getPublicAddresses().equals(Sets.newHashSet(publicAddresses))); + assertTrue(response.getPrivateAddresses().equals(Sets.newHashSet(privateAddresses))); } } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java index e34ffaf23b..dbdc14c41f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseInetAddressListFromJsonResponseTest.java @@ -26,6 +26,7 @@ import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.domain.Address; import org.testng.annotations.Test; @@ -43,7 +44,7 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseInetAddressListFromJsonResponseTest { - Injector i = Guice.createInjector(new ParserModule()); + Injector i = Guice.createInjector(new GsonModule()); @Test public void testPublic() throws UnknownHostException { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java deleted file mode 100644 index 8392b741c6..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseModule.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.jclouds.openstack.nova.functions; - -import org.jclouds.json.config.GsonModule; - -/** - * Created by IntelliJ IDEA. - * User: VGalkin - * Date: 4/16/11 - * Time: 7:47 AM - * To change this template use File | Settings | File Templates. - */ -class ParserModule extends GsonModule { - - @Override - protected void configure() { - super.configure(); - bind(DateAdapter.class).to(Iso8601DateAdapter.class); - } -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 70e12db6e0..d574659d8c 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -18,21 +18,7 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.openstack.nova.domain.Address; -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; import java.io.InputStream; import java.net.UnknownHostException; @@ -43,7 +29,23 @@ import java.util.List; import java.util.Locale; import java.util.SimpleTimeZone; -import static org.testng.Assert.assertEquals; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code ParseServerFromJsonResponse} @@ -72,9 +74,12 @@ public class ParseServerFromJsonResponseTest { assertEquals(response.getUpdated(), dateFormat.parse("2010-10-10T12:00:00Z")); - - List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.getAddresses(), addresses1); assertEquals(response.getMetadata(), ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")); @@ -84,14 +89,18 @@ public class ParseServerFromJsonResponseTest { public static Server parseServer() throws NoSuchMethodException, ClassNotFoundException { - Injector i = Guice.createInjector(new ParserModule()); + Injector i = Guice.createInjector(new GsonModule() { + @Override + protected void configure() { + super.configure(); + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } + }); InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { - })); - - //Function parser = i.getInstance(getParserOrThrowException(NovaClient.class.getMethod("getServer", int.class))); + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); + return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java index 0c61c1deb7..5d55e9c9c6 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerListFromJsonResponseTest.java @@ -18,6 +18,23 @@ */ package org.jclouds.openstack.nova.functions; +import static org.testng.Assert.assertEquals; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.util.HashSet; +import java.util.List; + +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; @@ -25,21 +42,6 @@ import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.Key; import com.google.inject.TypeLiteral; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.openstack.nova.domain.Address; -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.testng.annotations.Test; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.util.HashSet; -import java.util.List; - -import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseServerListFromJsonResponse} @@ -49,7 +51,13 @@ import static org.testng.Assert.assertEquals; @Test(groups = "unit") public class ParseServerListFromJsonResponseTest { - Injector i = Guice.createInjector(new ParserModule()); + Injector i = Guice.createInjector(new GsonModule() { + @Override + protected void configure() { + super.configure(); + bind(DateAdapter.class).to(Iso8601DateAdapter.class); + } + }); @Test public void testApplyInputStream() { @@ -82,8 +90,12 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(0).getStatus(), ServerStatus.BUILD); assertEquals(response.get(0).getProgress(), new Integer(60)); - List
publicAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), Address.newString2AddressFunction())); - List
privateAddresses = ImmutableList.copyOf(Iterables.transform(ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), Address.newString2AddressFunction())); + List
publicAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83"), + Address.newString2AddressFunction())); + List
privateAddresses = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.16", "::babe:10.176.42.16"), + Address.newString2AddressFunction())); Addresses addresses1 = new Addresses(new HashSet
(publicAddresses), new HashSet
(privateAddresses)); assertEquals(response.get(0).getAddresses(), addresses1); @@ -97,13 +109,17 @@ public class ParseServerListFromJsonResponseTest { assertEquals(response.get(1).getStatus(), ServerStatus.ACTIVE); assertEquals(response.get(1).getProgress(), null); - List
publicAddresses2 = ImmutableList.of(new Address("67.23.10.133", 4), new Address("::babe:67.23.10.133", 6)); - List
privateAddresses2 = ImmutableList.of(new Address("10.176.42.17", 4), new Address("::babe:10.176.42.17", 6)); + List
publicAddresses2 = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("67.23.10.133", "::babe:67.23.10.133"), + Address.newString2AddressFunction())); + List
privateAddresses2 = ImmutableList.copyOf(Iterables.transform( + ImmutableList.of("10.176.42.17", "::babe:10.176.42.17"), + Address.newString2AddressFunction())); Addresses addresses2 = new Addresses(new HashSet
(publicAddresses2), new HashSet
(privateAddresses2)); assertEquals(response.get(1).getAddresses(), addresses2); assertEquals(response.get(1).getMetadata(), ImmutableMap.of("Server Label", "DB 1")); - assertEquals(response.get(1).getURI(), "http://servers.api.openstack.org/1234/servers/56789"); + assertEquals(response.get(1).getURI().toString(), "http://servers.api.openstack.org/1234/servers/56789"); } diff --git a/sandbox-apis/nova/src/test/resources/test_get_image_details.json b/sandbox-apis/nova/src/test/resources/test_get_image_details.json index 3e3b93fb02..f9aa2f5719 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_image_details.json +++ b/sandbox-apis/nova/src/test/resources/test_get_image_details.json @@ -24,7 +24,7 @@ { "rel" : "bookmark", "type" : "application/vnd.openstack.computev1.1+json", - "href" : "http://servers.api.openstack.org/1234/images/1" + "href" : "https://servers.api.rackspacecloud.com/v1.1/1234/images/1" } ] } diff --git a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json index 0cc9cd3fca..6a7bd39af3 100644 --- a/sandbox-apis/nova/src/test/resources/test_get_server_detail.json +++ b/sandbox-apis/nova/src/test/resources/test_get_server_detail.json @@ -2,8 +2,8 @@ "server" : { "id" : 1234, "name" : "sample-server", - "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234", - "flavorRef" : "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1", + "imageRef" : "https://servers.api.rackspacecloud.com/v1.1/1234/images/1", + "flavorRef" : "http://servers.api.openstack.org/1234/flavors/1", "updated" : "2010-10-10T12:00:00Z", "created" : "2010-08-10T12:00:00Z", "hostId" : "e4d909c290d0fb1ca068ffaddf22cbd0", From d8a721c1759976eca612e20e7ca16f1700084bce Mon Sep 17 00:00:00 2001 From: vicglarson Date: Mon, 18 Apr 2011 23:55:19 +0400 Subject: [PATCH 37/95] Fixes in live tests --- .../openstack/nova/NovaAsyncClient.java | 57 ++++++------------- .../openstack/nova/NovaClientLiveTest.java | 23 ++++---- 2 files changed, 31 insertions(+), 49 deletions(-) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java index f21a5d1e0d..663ade8c32 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/NovaAsyncClient.java @@ -18,43 +18,22 @@ */ package org.jclouds.openstack.nova; -import java.util.Set; -import java.util.concurrent.ExecutionException; - -import javax.ws.rs.Consumes; -import javax.ws.rs.DELETE; -import javax.ws.rs.GET; -import javax.ws.rs.POST; -import javax.ws.rs.PUT; -import javax.ws.rs.Path; -import javax.ws.rs.PathParam; -import javax.ws.rs.Produces; -import javax.ws.rs.core.MediaType; - -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Flavor; -import org.jclouds.openstack.nova.domain.Image; -import org.jclouds.openstack.nova.domain.RebootType; -import org.jclouds.openstack.nova.domain.Server; +import com.google.common.util.concurrent.ListenableFuture; +import org.jclouds.openstack.filters.AddTimestampQuery; +import org.jclouds.openstack.filters.AuthenticateRequest; +import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.CreateServerOptions; import org.jclouds.openstack.nova.options.ListOptions; import org.jclouds.openstack.nova.options.RebuildServerOptions; -import org.jclouds.openstack.filters.AddTimestampQuery; -import org.jclouds.openstack.filters.AuthenticateRequest; -import org.jclouds.rest.annotations.Endpoint; -import org.jclouds.rest.annotations.ExceptionParser; -import org.jclouds.rest.annotations.MapBinder; -import org.jclouds.rest.annotations.Payload; -import org.jclouds.rest.annotations.PayloadParam; -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.annotations.*; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnFalseOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; -import com.google.common.util.concurrent.ListenableFuture; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import java.util.Set; +import java.util.concurrent.ExecutionException; /** * Provides asynchronous access to OpenStack Nova via their REST API. @@ -62,13 +41,13 @@ import com.google.common.util.concurrent.ListenableFuture; * All commands return a ListenableFuture of the result from OpenStack Nova. Any exceptions incurred * during processing will be wrapped in an {@link ExecutionException} as documented in * {@link ListenableFuture#get()}. - * + * + * @author Adrian Cole * @see NovaClient * @see - * @author Adrian Cole */ -@SkipEncoding({ '/', '=' }) -@RequestFilters({ AuthenticateRequest.class, AddTimestampQuery.class }) +@SkipEncoding({'/', '='}) +@RequestFilters({AuthenticateRequest.class, AddTimestampQuery.class}) @Endpoint(ServerManagement.class) public interface NovaAsyncClient { @@ -152,7 +131,7 @@ public interface NovaAsyncClient { @Path("/servers") @MapBinder(CreateServerOptions.class) ListenableFuture createServer(@PayloadParam("name") String name, @PayloadParam("imageRef") String imageRef, - @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); + @PayloadParam("flavorRef") String flavorRef, CreateServerOptions... options); /** * @see NovaClient#rebuildServer @@ -167,10 +146,10 @@ public interface NovaAsyncClient { /** * @see NovaClient#changeAdminPass */ - @PUT - @Path("/servers/{id}") + @POST + @Path("/servers/{id}/action") @Produces(MediaType.APPLICATION_JSON) - @Payload("%7B\"server\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") + @Payload("%7B\"changePassword\":%7B\"adminPass\":\"{adminPass}\"%7D%7D") ListenableFuture changeAdminPass(@PathParam("id") int id, @PayloadParam("adminPass") String adminPass); /** @@ -245,7 +224,7 @@ public interface NovaAsyncClient { @Produces(MediaType.APPLICATION_JSON) @Payload("%7B\"image\":%7B\"serverId\":{serverId},\"name\":\"{name}\"%7D%7D") ListenableFuture createImageFromServer(@PayloadParam("name") String imageName, - @PayloadParam("serverId") int serverId); + @PayloadParam("serverId") int serverId); /** * @see NovaClient#listAddresses diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 922495b409..31bcd08134 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -316,7 +316,7 @@ public class NovaClientLiveTest { if (serverId <= 0) testCreateServer(); Server server = client.getServer(serverId); - assertNotNull(server.getHostId()); + assertNotNull(server.getHostId(), "Host id: "); assertEquals(server.getStatus(), ServerStatus.ACTIVE); assertNotNull(server.getAddresses()); @@ -366,13 +366,13 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testChangePassword() throws Exception { if (serverId <= 0) testCreateServer(); - client.changeAdminPass(serverId, "elmo"); blockUntilServerActive(serverId); + client.changeAdminPass(serverId, "elmo"); assertPassword(client.getServer(serverId), "elmo"); this.adminPass = "elmo"; } - @Test(enabled = true, timeOut = 10 * 60 * 1000) + @Test(enabled = true, timeOut = 10 * 600 * 1000) public void testCreateImage() throws Exception { if (serverId <= 0) testCreateServer(); Image image = client.createImageFromServer("hoofie", serverId); @@ -405,7 +405,7 @@ public class NovaClientLiveTest { blockUntilServerActive(serverId); } - @Test(enabled = false, timeOut = 10 * 60 * 1000, dependsOnMethods = "testRebootSoft") + @Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft") public void testRevertResize() throws Exception { if (serverId <= 0) testCreateServer(); client.resizeServer(serverId, 2); @@ -425,17 +425,16 @@ public class NovaClientLiveTest { assertEquals(2, client.getServer(serverId).getFlavorRef()); } - @Test(enabled = true, timeOut = 10 * 60 * 1000) + @Test(enabled = true, timeOut = 60000) void deleteServer2() throws Exception { if (serverId <= 0) testCreateServer(); if (serverId > 0) { client.deleteServer(serverId); - Thread.sleep(1000); - assert client.getServer(serverId) == null; + waitServerDeleted(serverId); } } - @Test(enabled = true, timeOut = 10 * 60 * 1000) + @Test(enabled = true, timeOut = 60000) void testDeleteImage() throws Exception { if (createdImageId <= 0) { testCreateImage(); @@ -446,15 +445,19 @@ public class NovaClientLiveTest { } } - @Test(enabled = true, timeOut = 10 * 60 * 1000) + @Test(enabled = true, timeOut = 60000) void deleteServer1() throws Exception { if (serverId <= 0) testCreateServer(); if (serverId > 0) { client.deleteServer(serverId); - assert client.getServer(serverId) == null; + waitServerDeleted(serverId); } } + private void waitServerDeleted(int serverId) throws InterruptedException { + while (null != client.getServer(serverId)) Thread.sleep(1000); + } + @AfterTest void deleteServersOnEnd() { if (serverId > 0) { From 1035516c2db62c1b1273169ed31bf5bebda82f6e Mon Sep 17 00:00:00 2001 From: Dmitri Babaev <-> Date: Tue, 19 Apr 2011 23:01:20 +0400 Subject: [PATCH 38/95] Unit test fixes --- .../NovaComputeServiceDependenciesModule.java | 8 --- .../openstack/nova/domain/ServerStatus.java | 4 +- .../openstack/nova/NovaAsyncClientTest.java | 56 +++++++++---------- .../jclouds/openstack/nova/_NovaClient.java | 29 +++++----- .../functions/NovaImageToImageTest.java | 2 +- .../nova/domain/ServerStatusTest.java | 29 ++++++++-- .../ParseServerFromJsonResponseTest.java | 4 +- ...ateTest.java => ServerCreateLiveTest.java} | 2 +- 8 files changed, 74 insertions(+), 60 deletions(-) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ServerCreateTest.java => ServerCreateLiveTest.java} (99%) diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceDependenciesModule.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceDependenciesModule.java index acd932d565..234b2971bc 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceDependenciesModule.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/compute/config/NovaComputeServiceDependenciesModule.java @@ -89,19 +89,11 @@ public class NovaComputeServiceDependenciesModule extends AbstractModule { .put(ServerStatus.PREP_RESIZE, NodeState.PENDING)// .put(ServerStatus.RESIZE, NodeState.PENDING)// .put(ServerStatus.VERIFY_RESIZE, NodeState.PENDING)// - .put(ServerStatus.QUEUE_MOVE, NodeState.PENDING)// - .put(ServerStatus.PREP_MOVE, NodeState.PENDING)// - .put(ServerStatus.MOVE, NodeState.PENDING)// - .put(ServerStatus.VERIFY_MOVE, NodeState.PENDING)// .put(ServerStatus.RESCUE, NodeState.PENDING)// - .put(ServerStatus.ERROR, NodeState.ERROR)// .put(ServerStatus.BUILD, NodeState.PENDING)// - .put(ServerStatus.RESTORING, NodeState.PENDING)// .put(ServerStatus.PASSWORD, NodeState.PENDING)// .put(ServerStatus.REBUILD, NodeState.PENDING)// .put(ServerStatus.DELETE_IP, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP_NO_CONFIG, NodeState.PENDING)// - .put(ServerStatus.SHARE_IP, NodeState.PENDING)// .put(ServerStatus.REBOOT, NodeState.PENDING)// .put(ServerStatus.HARD_REBOOT, NodeState.PENDING)// .put(ServerStatus.UNKNOWN, NodeState.UNRECOGNIZED)// diff --git a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ServerStatus.java b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ServerStatus.java index 8b433524e4..5fe64c794a 100644 --- a/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ServerStatus.java +++ b/sandbox-apis/nova/src/main/java/org/jclouds/openstack/nova/domain/ServerStatus.java @@ -37,8 +37,8 @@ package org.jclouds.openstack.nova.domain; */ public enum ServerStatus { - ACTIVE, SUSPENDED, DELETED, QUEUE_RESIZE, PREP_RESIZE, RESIZE, VERIFY_RESIZE, QUEUE_MOVE, PREP_MOVE, MOVE, VERIFY_MOVE, RESCUE, ERROR, BUILD, RESTORING, PASSWORD, REBUILD, DELETE_IP, SHARE_IP_NO_CONFIG, SHARE_IP, REBOOT, HARD_REBOOT, UNKNOWN, UNRECOGNIZED; - + ACTIVE, SUSPENDED, QUEUE_RESIZE, PREP_RESIZE, RESIZE, VERIFY_RESIZE, RESCUE, BUILD, PASSWORD, REBUILD, REBOOT, HARD_REBOOT, UNKNOWN, DELETE_IP, UNRECOGNIZED, DELETED; + public String value() { return name(); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index cf59a2cd75..9ba20c56e6 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -18,9 +18,22 @@ */ package org.jclouds.openstack.nova; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; +import static org.testng.Assert.assertEquals; + +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Date; +import java.util.Properties; + +import javax.ws.rs.core.MediaType; + import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.http.functions.ReleasePayloadAndReturn; @@ -45,21 +58,9 @@ import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; -import javax.ws.rs.core.MediaType; -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.Date; -import java.util.Properties; - -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.location.reference.LocationConstants.PROPERTY_REGIONS; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; -import static org.testng.Assert.assertEquals; +import com.google.common.collect.ImmutableMap; +import com.google.inject.Module; +import com.google.inject.TypeLiteral; /** * Tests behavior of {@code NovaAsyncClient} @@ -75,13 +76,13 @@ public class NovaAsyncClientTest extends RestClientTest { @Test public void testCreateServer() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class, createServerOptionsVarargsClass); HttpRequest request = processor.createRequest(method, "ralphie", 2, 1); assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); - assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1}}", + assertPayloadEquals(request, "{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\"}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -94,7 +95,7 @@ public class NovaAsyncClientTest extends RestClientTest { @Test public void testCreateServerWithFile() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class, createServerOptionsVarargsClass); HttpRequest request = processor .createRequest(method, "ralphie", 2, 1, withFile("/etc/jclouds", "foo".getBytes())); @@ -103,7 +104,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals( request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\",\"personality\":[{\"path\":\"/etc/jclouds\",\"contents\":\"Zm9v\"}]}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -116,7 +117,7 @@ public class NovaAsyncClientTest extends RestClientTest { @Test public void testCreateServerWithMetadata() throws IOException, SecurityException, NoSuchMethodException { - Method method = NovaAsyncClient.class.getMethod("createServer", String.class, int.class, int.class, + Method method = NovaAsyncClient.class.getMethod("createServer", String.class, String.class, String.class, createServerOptionsVarargsClass); HttpRequest request = processor.createRequest(method, "ralphie", 2, 1, withMetadata(ImmutableMap.of("foo", "bar"))); @@ -124,7 +125,7 @@ public class NovaAsyncClientTest extends RestClientTest { assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, "Accept: application/json\n"); assertPayloadEquals(request, - "{\"server\":{\"name\":\"ralphie\",\"imageRef\":2,\"flavorRef\":1,\"metadata\":{\"foo\":\"bar\"}}}", + "{\"server\":{\"name\":\"ralphie\",\"imageRef\":\"2\",\"flavorRef\":\"1\",\"metadata\":{\"foo\":\"bar\"}}}", "application/json", false); assertResponseParserClassEquals(method, request, UnwrapOnlyJsonValue.class); @@ -502,11 +503,11 @@ public class NovaAsyncClientTest extends RestClientTest { public void testRebuildServerWithImage() throws IOException, SecurityException, NoSuchMethodException { Method method = NovaAsyncClient.class.getMethod("rebuildServer", int.class, rebuildServerOptionsVarargsClass); - HttpRequest request = processor.createRequest(method, 3, withImage(2)); + HttpRequest request = processor.createRequest(method, 3, withImage("2")); assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/3/action?format=json HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":2}}", MediaType.APPLICATION_JSON, false); + assertPayloadEquals(request, "{\"rebuild\":{\"imageRef\":\"2\"}}", MediaType.APPLICATION_JSON, false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); @@ -606,7 +607,7 @@ public class NovaAsyncClientTest extends RestClientTest { @Override protected URI provideServerUrl(AuthenticationResponse response) { - return URI.create("http://endpoint"); + return URI.create("http://endpoint/vapiversion"); } } @@ -621,7 +622,6 @@ public class NovaAsyncClientTest extends RestClientTest { @Override protected Properties getProperties() { Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_REGIONS, "US"); overrides.setProperty(PROPERTY_API_VERSION, "apiversion"); overrides.setProperty(provider + ".endpoint", "http://endpoint"); overrides.setProperty(provider + ".contextbuilder", NovaContextBuilder.class.getName()); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java index e6406c47c9..b160536b6f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java @@ -1,5 +1,6 @@ package org.jclouds.openstack.nova; +import com.google.common.collect.ImmutableSet; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.ComputeServiceContextFactory; @@ -10,15 +11,13 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.ssh.jsch.config.JschSshClientModule; -import com.google.common.collect.ImmutableSet; - -import java.util.Arrays; import java.util.Properties; import java.util.Set; import static org.jclouds.Constants.PROPERTY_ENDPOINT; public class _NovaClient { + @SuppressWarnings("unused") static public void main(String[] args) { //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json @@ -41,19 +40,21 @@ public class _NovaClient { System.out.println(cs.listAssignableLocations()); System.out.println(cs.listNodes()); - /*TemplateOptions options = new TemplateOptions().blockUntilRunning(false); - Template template = cs.templateBuilder().imageId("13").options(options).build(); - try { - Set metedata = cs.runNodesWithTag("test", 1, template); - System.out.println(metedata); - } catch (RunNodesException e) { - e.printStackTrace(); - }*/ - + if (false) { + TemplateOptions options = new TemplateOptions().blockUntilRunning(false); + Template template = cs.templateBuilder().imageId("95").hardwareId("2").options(options).build(); + try { + Set metedata = cs.createNodesInGroup("test", 1, template); + System.out.println(metedata); + } catch (RunNodesException e) { + e.printStackTrace(); + } + } + //System.out.println(cs.getNodeMetadata("64")); - + //cs.destroyNode("64"); context.close(); } -} +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index c207d53357..c4e3e594ae 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -51,7 +51,7 @@ public class NovaImageToImageTest { .operatingSystem( new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("1").version("1286712000000").uri(new URI("http://servers.api.openstack.org/1234/images/1")).build(); + .ids("1").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); Image parsedImage = convertImage(); assertEquals(parsedImage, image); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java index 5b29e118c7..b01e46fb35 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java @@ -19,11 +19,18 @@ package org.jclouds.openstack.nova.domain; -import org.testng.annotations.Test; +import static junit.framework.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; import java.util.Arrays; +import java.util.List; +import java.util.Set; -import static org.testng.Assert.assertFalse; +import org.testng.annotations.Test; + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; /** * Tests behavior of {@code CreateImageBinder} @@ -35,12 +42,26 @@ public class ServerStatusTest { @Test public void testAllKnownStatusesIsRecognized() { - for (String status : Arrays.asList( + List knownStatuses = Arrays.asList( "ACTIVE", "BUILD", "REBUILD", "SUSPENDED", "QUEUE_RESIZE", "PREP_RESIZE", "RESIZE", "VERIFY_RESIZE", "PASSWORD", "RESCUE", "REBOOT", - "HARD_REBOOT", "DELETE_IP", "UNKNOWN")) { + "HARD_REBOOT", "DELETE_IP", "UNKNOWN", "DELETED"); + for (String status : knownStatuses) { assertFalse(ServerStatus.fromValue(status).equals(ServerStatus.UNRECOGNIZED)); } + + List allStatuses = Lists.newArrayList(knownStatuses); + allStatuses.add("UNRECOGNIZED"); + + Set enumValues = Sets.newHashSet(ServerStatus.values()); + + assertEquals(enumValues.size(), allStatuses.size()); + + for (String status : allStatuses) { + assertTrue(enumValues.contains(ServerStatus.valueOf(status))); + } } + } + diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index d574659d8c..7be82417b7 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -61,8 +61,8 @@ public class ParseServerFromJsonResponseTest { assertEquals(response.getId(), 1234); assertEquals(response.getName(), "sample-server"); - assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/images/1234"); - assertEquals(response.getFlavorRef(), "https://servers.api.rackspacecloud.com/v1.1/32278/flavors/1"); + assertEquals(response.getImageRef(), "https://servers.api.rackspacecloud.com/v1.1/1234/images/1"); + assertEquals(response.getFlavorRef(), "http://servers.api.openstack.org/1234/flavors/1"); assertEquals(response.getHostId(), "e4d909c290d0fb1ca068ffaddf22cbd0"); assertEquals(response.getStatus(), ServerStatus.BUILD); assertEquals(response.getProgress(), new Integer(60)); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java similarity index 99% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java index e62772594d..b653ff3aa0 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java @@ -54,7 +54,7 @@ import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.wit */ @Test(groups = "live", sequential = true) -public class ServerCreateTest { +public class ServerCreateLiveTest { protected NovaClient client; protected SshClient.Factory sshFactory; From 3899ff2f991215e41997095085da0e495a88e708 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Wed, 20 Apr 2011 17:39:01 +0400 Subject: [PATCH 39/95] Fixes in live tests --- .../openstack/nova/NovaClientLiveTest.java | 142 ++++++------- .../openstack/nova/PropertyHelper.java | 39 ++++ .../compute/NovaComputeServiceLiveTest.java | 198 ++++++++---------- .../DeleteServersInVariousStatesLiveTest.java | 143 +++++++++++++ 4 files changed, 328 insertions(+), 194 deletions(-) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java index 31bcd08134..e48640c586 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java @@ -25,7 +25,6 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.inject.Injector; import com.google.inject.Module; -import org.jclouds.Constants; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; @@ -40,7 +39,7 @@ import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; @@ -50,8 +49,7 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.PropertyHelper.*; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; @@ -69,67 +67,19 @@ public class NovaClientLiveTest { protected SshClient.Factory sshFactory; private Predicate socketTester; protected String provider = "nova"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; - - private String ip; - - private String adminPass2; - - private String serverPrefix = System.getProperty("user.name") + ".cs"; + protected Map keyPair; private int serverId; private String adminPass; Map metadata = ImmutableMap.of("jclouds", "rackspace"); private int createdImageId; - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; - } - - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } - - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } - - - @BeforeGroups(groups = {"live"}) + @BeforeTest public void setupClient() throws IOException { - Properties overrides = setupProperties(); - setupCredentials(overrides); - updateProperties(overrides); + Properties properties = setupOverrides(setupProperties(this.getClass())); - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; -// ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); -// ComputeServiceContext context = contextFactory.createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides); - - Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, - ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) + Injector injector = new RestContextFactory().createContextBuilder(provider, + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), properties) .buildInjector(); client = injector.getInstance(NovaClient.class); @@ -138,16 +88,16 @@ public class NovaClientLiveTest { SocketOpen socketOpen = injector.getInstance(SocketOpen.class); socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); injector.injectMembers(socketOpen); // add logger + + keyPair = setupKeyPair(properties); } @Test public void testListServers() throws Exception { - Set response = client.listServers(); assert null != response; long initialContainerCount = response.size(); assertTrue(initialContainerCount >= 0); - } @Test @@ -216,6 +166,14 @@ public class NovaClientLiveTest { Set response = client.listServers(withDetails()); assert null != response; assertTrue(response.size() >= 0); + for (Server server : response) { + Server newDetails = client.getServer(server.getId()); + System.out.println("===="); + + System.out.println(server); + System.out.println(newDetails); + System.out.println("===="); + } for (Server server : response) { Server newDetails = client.getServer(server.getId()); assertEquals(server, newDetails); @@ -269,7 +227,7 @@ public class NovaClientLiveTest { @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = client.getImage(13).getURI().toASCIIString(); + String imageRef = client.getImage(95).getURI().toASCIIString(); String flavorRef = client.getFlavor(1).getURI().toASCIIString(); String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", @@ -280,10 +238,17 @@ public class NovaClientLiveTest { serverId = server.getId(); adminPass = server.getAdminPass(); blockUntilServerActive(serverId); - Thread.sleep(2000); + blockUntilPublicAddress(serverId); client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); } + private void blockUntilPublicAddress(int serverId) throws InterruptedException { + while (client.getServer(serverId).getAddresses().getPublicAddresses().isEmpty()) { + System.out.println("Awaiting public address"); + Thread.sleep(1000); + } + } + private void blockUntilServerActive(int serverId) throws InterruptedException { Server currentDetails; for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client @@ -313,7 +278,7 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 300000) public void testServerDetails() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); Server server = client.getServer(serverId); assertNotNull(server.getHostId(), "Host id: "); @@ -324,7 +289,7 @@ public class NovaClientLiveTest { assertEquals(server.getMetadata(), metadata); - assertEquals(server.getImageRef(), endpoint + "/v1.1/images/13"); + assertEquals(server.getImageRef(), "endpoint" + "/v1.1/images/95"); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); @@ -332,7 +297,7 @@ public class NovaClientLiveTest { assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); assertPassword(server, adminPass); - assertEquals(server.getFlavorRef(), endpoint + "/v1.1/flavors/1"); + assertEquals(server.getFlavorRef(), "endpoint" + "/v1.1/flavors/1"); assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); } @@ -341,7 +306,7 @@ public class NovaClientLiveTest { IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0).getAddress(), 22); socketTester.apply(socket); - SshClient client = sshFactory.create(socket, new Credentials("root", pass)); + SshClient client = sshFactory.create(socket, new Credentials("root", keyPair.get("private"))); try { client.connect(); Payload etcPasswd = client.get("/etc/jclouds.txt"); @@ -355,7 +320,7 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testRenameServer() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); Server server = client.getServer(serverId); String oldName = server.getName(); client.renameServer(serverId, oldName + "new"); @@ -365,7 +330,7 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testChangePassword() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); blockUntilServerActive(serverId); client.changeAdminPass(serverId, "elmo"); assertPassword(client.getServer(serverId), "elmo"); @@ -374,7 +339,7 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 10 * 600 * 1000) public void testCreateImage() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); Image image = client.createImageFromServer("hoofie", serverId); assertEquals("hoofie", image.getName()); assertEquals(serverId, image.getServerRef()); @@ -384,7 +349,7 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebuildServer() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); client.rebuildServer(serverId, new RebuildServerOptions().withImage(String.valueOf(createdImageId))); blockUntilServerActive(serverId); // issue Web Hosting #119580 createdImageId comes back incorrect after rebuild @@ -393,21 +358,21 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootHard() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); client.rebootServer(serverId, RebootType.HARD); blockUntilServerActive(serverId); } @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootSoft() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); client.rebootServer(serverId, RebootType.SOFT); blockUntilServerActive(serverId); } @Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft") public void testRevertResize() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); client.resizeServer(serverId, 2); blockUntilServerVerifyResize(serverId); client.revertResizeServer(serverId); @@ -417,7 +382,7 @@ public class NovaClientLiveTest { @Test(enabled = false, timeOut = 10 * 60 * 1000) public void testConfirmResize() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); client.resizeServer(serverId, 2); blockUntilServerVerifyResize(serverId); client.confirmResizeServer(serverId); @@ -427,11 +392,12 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 60000) void deleteServer2() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); if (serverId > 0) { client.deleteServer(serverId); waitServerDeleted(serverId); } + serverId = 0; } @Test(enabled = true, timeOut = 60000) @@ -443,25 +409,43 @@ public class NovaClientLiveTest { client.deleteImage(createdImageId); assert client.getImage(createdImageId) == null; } + //TODO all servers created from the image should be deleted } @Test(enabled = true, timeOut = 60000) void deleteServer1() throws Exception { - if (serverId <= 0) testCreateServer(); + if (!isServerExist(serverId)) testCreateServer(); if (serverId > 0) { client.deleteServer(serverId); waitServerDeleted(serverId); } + serverId = 0; + } + + private boolean isServerExist(int serverId) { + return client.getServer(serverId) != null; } private void waitServerDeleted(int serverId) throws InterruptedException { - while (null != client.getServer(serverId)) Thread.sleep(1000); + while (null != client.getServer(serverId)) { + System.out.println("Await deleted server" + serverId); + Thread.sleep(1000); + } + } + + @Test + public void testDeleteAllCreatedServers() { + for (Server server : client.listServers()) { + if (server.getName().startsWith(serverPrefix)) { + client.deleteServer(server.getId()); + System.out.println("Deleted server: " + server); + } + } } @AfterTest void deleteServersOnEnd() { - if (serverId > 0) { - client.deleteServer(serverId); - } + testDeleteAllCreatedServers(); } + } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java index 8d24ec5102..b7d9aea50d 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java @@ -1,5 +1,14 @@ package org.jclouds.openstack.nova; +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableMap; +import com.google.common.io.Files; +import org.jclouds.Constants; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.Map; import java.util.Properties; /** @@ -8,10 +17,40 @@ import java.util.Properties; public class PropertyHelper { + public static String provider = "nova"; + public static void overridePropertyFromSystemProperty(final Properties properties, String propertyName) { if ((System.getProperty(propertyName) != null) && !System.getProperty(propertyName).equals("${" + propertyName + "}")) properties.setProperty(propertyName, System.getProperty(propertyName)); } + public static Map setupKeyPair(Properties properties) throws FileNotFoundException, IOException { + return ImmutableMap.of( + "private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8), + "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); + } + + public static Properties setupProperties(Class clazz) throws IOException { + Properties properties = new Properties(); + + properties.load(clazz.getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(properties, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(properties, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(properties, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(properties, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(properties, "test.initializer"); + return properties; + } + + public static Properties setupOverrides(final Properties properties) { + properties.setProperty(provider + ".identity", properties.getProperty("test." + provider + ".identity")); + properties.setProperty(provider + ".credential", properties.getProperty("test." + provider + ".credential")); + properties.setProperty(provider + ".endpoint", properties.getProperty("test." + provider + ".endpoint")); + properties.setProperty(provider + ".apiversion", "test." + provider + ".apiversion"); + properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + return properties; + } + } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java index 66ef4325ce..bd9faf6c11 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java @@ -18,63 +18,15 @@ */ package org.jclouds.openstack.nova.compute; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.not; -import static com.google.common.base.Throwables.getRootCause; -import static com.google.common.collect.Iterables.concat; -import static com.google.common.collect.Iterables.get; -import static com.google.common.collect.Iterables.getOnlyElement; -import static com.google.common.collect.Maps.newLinkedHashMap; -import static com.google.common.collect.Maps.uniqueIndex; -import static com.google.common.collect.Sets.filter; -import static com.google.common.collect.Sets.newTreeSet; -import static org.jclouds.compute.ComputeTestUtils.buildScript; -import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; -import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; -import static org.jclouds.compute.predicates.NodePredicates.TERMINATED; -import static org.jclouds.compute.predicates.NodePredicates.all; -import static org.jclouds.compute.predicates.NodePredicates.inGroup; -import static org.jclouds.compute.predicates.NodePredicates.runningInGroup; -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Module; import org.jclouds.Constants; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.ComputeTestUtils; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.RunScriptData; -import org.jclouds.compute.RunScriptOnNodesException; -import org.jclouds.compute.domain.ComputeMetadata; -import org.jclouds.compute.domain.ComputeType; -import org.jclouds.compute.domain.ExecResponse; -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.domain.TemplateBuilder; +import org.jclouds.compute.*; +import org.jclouds.compute.domain.*; import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; @@ -96,15 +48,31 @@ import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.io.Files; -import com.google.inject.Guice; -import com.google.inject.Module; +import java.io.IOException; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.and; +import static com.google.common.base.Predicates.not; +import static com.google.common.base.Throwables.getRootCause; +import static com.google.common.collect.Iterables.*; +import static com.google.common.collect.Maps.newLinkedHashMap; +import static com.google.common.collect.Maps.uniqueIndex; +import static com.google.common.collect.Sets.filter; +import static com.google.common.collect.Sets.newTreeSet; +import static org.jclouds.compute.ComputeTestUtils.buildScript; +import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; +import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; +import static org.jclouds.compute.predicates.NodePredicates.*; +import static org.jclouds.compute.predicates.NodePredicates.all; +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.PropertyHelper.setupKeyPair; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; /** * Generally disabled, as it incurs higher fees. @@ -119,7 +87,7 @@ public class NovaComputeServiceLiveTest { protected RetryablePredicate socketTester; protected SortedSet nodes; protected ComputeServiceContext context; - protected ComputeService client; + protected ComputeService computeService; protected Template template; protected Map keyPair; @@ -181,13 +149,7 @@ public class NovaComputeServiceLiveTest { context.close(); context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( new SLF4JLoggingModule(), getSshModule()), properties); - client = context.getComputeService(); - } - - public static Map setupKeyPair(Properties properties) throws FileNotFoundException, IOException { - return ImmutableMap.of( - "private", Files.toString(new File(properties.getProperty("test.ssh.keyfile.private")), Charsets.UTF_8), - "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); + computeService = context.getComputeService(); } @@ -270,33 +232,33 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true) public void testImagesCache() throws Exception { - client.listImages(); + computeService.listImages(); long time = System.currentTimeMillis(); - client.listImages(); + computeService.listImages(); long duration = System.currentTimeMillis() - time; assert duration < 1000 : String.format("%dms to get images", duration); } @Test(enabled = true, expectedExceptions = NoSuchElementException.class) public void testCorrectExceptionRunningNodesNotFound() throws Exception { - client.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() + computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() .family(OsFamily.UBUNTU).description("ffoo").build())); } // since surefire and eclipse don't otherwise guarantee the order, we are // starting this one alphabetically before create2nodes.. - @Test(enabled = true, dependsOnMethods = {"testCompareSizes"}) + @Test(enabled = true) public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { String group = this.group + "r"; try { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } catch (Exception e) { } - TemplateOptions options = client.templateOptions().blockOnPort(22, 120); + Template template = getDefaultTemplateBuilder().options(computeService.templateOptions().blockOnPort(22, 120)).build(); try { - Set nodes = client.createNodesInGroup(group, 1, options); + Set nodes = computeService.createNodesInGroup(group, 1, template); Credentials good = nodes.iterator().next().getCredentials(); assert good.identity != null : nodes; assert good.credential != null : nodes; @@ -310,7 +272,7 @@ public class NovaComputeServiceLiveTest { assert getRootCause(e).getMessage().contains("Auth fail") : e; } - for (Map.Entry response : client.runScriptOnNodesMatching( + for (Map.Entry response : computeService.runScriptOnNodesMatching( runningInGroup(group), Statements.exec("echo hello"), overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " @@ -321,14 +283,14 @@ public class NovaComputeServiceLiveTest { checkNodes(nodes, group); } finally { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } } @Test(enabled = true, dependsOnMethods = {"testImagesCache"}) public void testTemplateMatch() throws Exception { - template = buildTemplate(client.templateBuilder()); - Template toMatch = client.templateBuilder().imageId(template.getImage().getId()).build(); + template = buildTemplate(computeService.templateBuilder()); + Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build(); assertEquals(toMatch.getImage(), template.getImage()); } @@ -339,13 +301,13 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = "testCompareSizes") public void testCreateTwoNodesWithRunScript() throws Exception { try { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } catch (NoSuchElementException e) { } refreshTemplate(); try { - nodes = newTreeSet(client.createNodesInGroup(group, 2, template)); + nodes = newTreeSet(computeService.createNodesInGroup(group, 2, template)); } catch (RunNodesException e) { nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); throw e; @@ -366,7 +328,7 @@ public class NovaComputeServiceLiveTest { } private void refreshTemplate() { - template = buildTemplate(client.templateBuilder()); + template = buildTemplate(computeService.templateBuilder()); template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) .runScript(buildScript(template.getImage().getOperatingSystem())); @@ -396,7 +358,7 @@ public class NovaComputeServiceLiveTest { public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { initializeContextAndClient(overrides); refreshTemplate(); - TreeSet nodes = newTreeSet(client.createNodesInGroup(group, 1, template)); + TreeSet nodes = newTreeSet(computeService.createNodesInGroup(group, 1, template)); checkNodes(nodes, group); NodeMetadata node = nodes.first(); this.nodes.add(node); @@ -415,7 +377,7 @@ public class NovaComputeServiceLiveTest { protected Map runScriptWithCreds(final String group, OperatingSystem os, Credentials creds) throws RunScriptOnNodesException { try { - return client.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) .nameTask("runScriptWithCreds")); } catch (SshException e) { throw e; @@ -429,7 +391,7 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") public void testGet() throws Exception { - Map metadataMap = newLinkedHashMap(uniqueIndex(filter(client + Map metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), new Function() { @@ -441,7 +403,7 @@ public class NovaComputeServiceLiveTest { })); for (NodeMetadata node : nodes) { metadataMap.remove(node.getId()); - NodeMetadata metadata = client.getNodeMetadata(node.getId()); + NodeMetadata metadata = computeService.getNodeMetadata(node.getId()); assertEquals(metadata.getProviderId(), node.getProviderId()); assertEquals(metadata.getGroup(), node.getGroup()); assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); @@ -462,14 +424,14 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = "testGet") public void testReboot() throws Exception { - client.rebootNodesMatching(inGroup(group));// TODO test + computeService.rebootNodesMatching(inGroup(group));// TODO test // validation testGet(); } @Test(enabled = true, dependsOnMethods = "testReboot") public void testSuspendResume() throws Exception { - client.suspendNodesMatching(inGroup(group)); + computeService.suspendNodesMatching(inGroup(group)); Set stoppedNodes = refreshNodes(); @@ -485,13 +447,13 @@ public class NovaComputeServiceLiveTest { }) : stoppedNodes; - client.resumeNodesMatching(inGroup(group)); + computeService.resumeNodesMatching(inGroup(group)); testGet(); } @Test(enabled = true, dependsOnMethods = "testSuspendResume") public void testListNodes() throws Exception { - for (ComputeMetadata node : client.listNodes()) { + for (ComputeMetadata node : computeService.listNodes()) { assert node.getProviderId() != null; assert node.getLocation() != null; assertEquals(node.getType(), ComputeType.NODE); @@ -500,7 +462,7 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = "testSuspendResume") public void testGetNodesWithDetails() throws Exception { - for (NodeMetadata node : client.listNodesDetailsMatching(all())) { + for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) { assert node.getProviderId() != null : node; assert node.getLocation() != null : node; assertEquals(node.getType(), ComputeType.NODE); @@ -522,16 +484,16 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"}) public void testDestroyNodes() { int toDestroy = refreshNodes().size(); - Set destroyed = client.destroyNodesMatching(inGroup(group)); + Set destroyed = computeService.destroyNodesMatching(inGroup(group)); assertEquals(toDestroy, destroyed.size()); - for (NodeMetadata node : filter(client.listNodesDetailsMatching(all()), inGroup(group))) { + for (NodeMetadata node : filter(computeService.listNodesDetailsMatching(all()), inGroup(group))) { assert node.getState() == NodeState.TERMINATED : node; assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); } } private Set refreshNodes() { - return filter(client.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); + return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); } @Test(enabled = true) @@ -539,12 +501,12 @@ public class NovaComputeServiceLiveTest { String group = this.group + "s"; try { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } catch (Exception e) { } - template = client.templateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) + template = getDefaultTemplateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) .build(); // note this is a dependency on the template resolution @@ -552,11 +514,11 @@ public class NovaComputeServiceLiveTest { RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() .getOperatingSystem())); try { - NodeMetadata node = getOnlyElement(client.createNodesInGroup(group, 1, template)); + NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, template)); checkHttpGet(node); } finally { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } } @@ -564,12 +526,12 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */) public void testTemplateOptions() throws Exception { TemplateOptions options = new TemplateOptions().withMetadata(); - Template t = client.templateBuilder().smallest().options(options).build(); + Template t = computeService.templateBuilder().smallest().options(options).build(); assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; } public void testListImages() throws Exception { - for (Image image : client.listImages()) { + for (Image image : computeService.listImages()) { assert image.getProviderId() != null : image; // image.getLocationId() can be null, if it is a location-free image assertEquals(image.getType(), ComputeType.IMAGE); @@ -578,7 +540,7 @@ public class NovaComputeServiceLiveTest { @Test(groups = {"integration", "live"}) public void testGetAssignableLocations() throws Exception { - for (Location location : client.listAssignableLocations()) { + for (Location location : computeService.listAssignableLocations()) { System.err.printf("location %s%n", location); assert location.getId() != null : location; assert location != location.getParent() : location; @@ -611,21 +573,21 @@ public class NovaComputeServiceLiveTest { public void testOptionToNotBlock() throws Exception { String group = this.group + "block"; try { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } catch (Exception e) { } // no inbound ports - TemplateOptions options = client.templateOptions().blockUntilRunning(false).inboundPorts(); + TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); try { long time = System.currentTimeMillis(); - Set nodes = client.createNodesInGroup(group, 1, options); + Set nodes = computeService.createNodesInGroup(group, 1, options); NodeMetadata node = getOnlyElement(nodes); assert node.getState() != NodeState.RUNNING; long duration = System.currentTimeMillis() - time; assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; } finally { - client.destroyNodesMatching(inGroup(group)); + computeService.destroyNodesMatching(inGroup(group)); } } @@ -635,7 +597,7 @@ public class NovaComputeServiceLiveTest { } public void testListSizes() throws Exception { - for (Hardware hardware : client.listHardwareProfiles()) { + for (Hardware hardware : computeService.listHardwareProfiles()) { assert hardware.getProviderId() != null; assert getCores(hardware) > 0; assert hardware.getVolumes().size() >= 0; @@ -644,13 +606,19 @@ public class NovaComputeServiceLiveTest { } } + private TemplateBuilder getDefaultTemplateBuilder() { + return computeService.templateBuilder().imageId("95"); + } + @Test(enabled = true) public void testCompareSizes() throws Exception { - Hardware defaultSize = client.templateBuilder().build().getHardware(); + TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); - Hardware smallest = client.templateBuilder().smallest().build().getHardware(); - Hardware fastest = client.templateBuilder().fastest().build().getHardware(); - Hardware biggest = client.templateBuilder().biggest().build().getHardware(); + Hardware defaultSize = templateBuilder.build().getHardware(); + + Hardware smallest = templateBuilder.smallest().build().getHardware(); + Hardware fastest = templateBuilder.fastest().build().getHardware(); + Hardware biggest = templateBuilder.biggest().build().getHardware(); System.out.printf("smallest %s%n", smallest); System.out.printf("fastest %s%n", fastest); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java new file mode 100644 index 0000000000..3c6e3f80e5 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java @@ -0,0 +1,143 @@ +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova.live; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import org.jclouds.Constants; +import org.jclouds.http.HttpResponseException; +import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.NovaClient; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.jclouds.ssh.SshClient; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Map; +import java.util.Properties; + +import static com.google.common.base.Preconditions.checkNotNull; +import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; + +/** + * @author Victor Galkin + */ + +@Test(groups = "live", sequential = true) +public class DeleteServersInVariousStatesLiveTest { + + protected NovaClient client; + protected SshClient.Factory sshFactory; + private Predicate socketTester; + protected String provider = "nova"; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + Server server = null; + + + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } + + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } + + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } + + + @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") + public void testCreateServerWithUnknownImage() throws Exception { + try { + server = client.createServer("serverName", String.valueOf(88888888), "1", withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + } catch (HttpResponseException e) { + throw e; + } + } + + @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") + public void testCreateServerWithUnknownFlavor() throws Exception { + try { + server = client.createServer("serverName", String.valueOf(13), "88888888", withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + } catch (HttpResponseException e) { + throw e; + } + } + + @AfterMethod + public void after() { + if (server != null) client.deleteServer(server.getId()); + } + + @Test(enabled = true) + public void testCreateServer() throws Exception { +// String imageRef = client.getImage(13).getURI().toASCIIString(); +// String flavorRef = client.getFlavor(1).getURI().toASCIIString(); +// String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); +// Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", +// "rackspace".getBytes()).withMetadata(metadata)); +// +// assertNotNull(server.getAdminPass()); +// assertEquals(server.getStatus(), ServerStatus.BUILD); +// serverId = server.getId(); +// adminPass = server.getAdminPass(); +// blockUntilServerActive(serverId); +// client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); + } + + private void blockUntilServerActive(int serverId) throws InterruptedException { + Server currentDetails; + for (currentDetails = client.getServer(serverId); currentDetails.getStatus() != ServerStatus.ACTIVE; currentDetails = client + .getServer(serverId)) { + System.out.printf("blocking on status active%n%s%n", currentDetails); + Thread.sleep(5 * 1000); + } + } +} From d065f61b92248030fb8232ac934972029456cee6 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Wed, 20 Apr 2011 22:56:50 +0400 Subject: [PATCH 40/95] Fixes in live tests --- .../jclouds/openstack/nova/_NovaClient.java | 60 --------- .../DeleteServersInVariousStatesLiveTest.java | 38 ------ .../nova/{ => live}/NovaClientLiveTest.java | 5 +- .../NovaComputeServiceLiveTest.java | 127 +++++++++++------- .../nova/{ => live}/PropertyHelper.java | 4 +- .../nova/live/ServerCreateLiveTest.java | 56 ++------ .../nonmaven/SimpleCreateServerCheck.java | 54 ++++++++ .../nova/live/nonmaven/SimpleListCheck.java | 49 +++++++ 8 files changed, 193 insertions(+), 200 deletions(-) delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/{ => live}/NovaClientLiveTest.java (99%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/{compute => live}/NovaComputeServiceLiveTest.java (87%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/{ => live}/PropertyHelper.java (91%) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java deleted file mode 100644 index b160536b6f..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/_NovaClient.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.jclouds.openstack.nova; - -import com.google.common.collect.ImmutableSet; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.compute.RunNodesException; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.Template; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; -import org.jclouds.ssh.jsch.config.JschSshClientModule; - -import java.util.Properties; -import java.util.Set; - -import static org.jclouds.Constants.PROPERTY_ENDPOINT; - -public class _NovaClient { - @SuppressWarnings("unused") - static public void main(String[] args) { - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ - //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json - - String identity = "admin"; - String credential = "d744752f-20d3-4d75-979f-f62f16033b07"; - String endpoint = "http://dragon004.hw.griddynamics.net:8774"; - - ComputeServiceContextFactory contextFactory = new ComputeServiceContextFactory(); - - Properties overrides = new Properties(); - overrides.setProperty(PROPERTY_ENDPOINT, endpoint); - ComputeServiceContext context = contextFactory.createContext("nova", identity, credential, - ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), overrides); - - ComputeService cs = context.getComputeService(); - - System.out.println(cs.listImages()); - System.out.println(cs.listHardwareProfiles()); - System.out.println(cs.listAssignableLocations()); - System.out.println(cs.listNodes()); - - if (false) { - TemplateOptions options = new TemplateOptions().blockUntilRunning(false); - Template template = cs.templateBuilder().imageId("95").hardwareId("2").options(options).build(); - try { - Set metedata = cs.createNodesInGroup("test", 1, template); - System.out.println(metedata); - } catch (RunNodesException e) { - e.printStackTrace(); - } - } - - //System.out.println(cs.getNodeMetadata("64")); - - //cs.destroyNode("64"); - - context.close(); - } -} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java index 3c6e3f80e5..815a36ed5f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java @@ -21,7 +21,6 @@ package org.jclouds.openstack.nova.live; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; -import org.jclouds.Constants; import org.jclouds.http.HttpResponseException; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaClient; @@ -31,12 +30,8 @@ import org.jclouds.ssh.SshClient; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; -import java.io.IOException; import java.util.Map; -import java.util.Properties; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; /** @@ -58,39 +53,6 @@ public class DeleteServersInVariousStatesLiveTest { Map metadata = ImmutableMap.of("jclouds", "rackspace"); Server server = null; - - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; - } - - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } - - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } - - @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") public void testCreateServerWithUnknownImage() throws Exception { try { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java similarity index 99% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java index e48640c586..cab458cb34 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.openstack.nova; +package org.jclouds.openstack.nova.live; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; @@ -30,6 +30,7 @@ import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.NovaClient; import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.RebuildServerOptions; import org.jclouds.predicates.RetryablePredicate; @@ -49,7 +50,7 @@ import java.util.Properties; import java.util.Set; import java.util.concurrent.TimeUnit; -import static org.jclouds.openstack.nova.PropertyHelper.*; +import static org.jclouds.openstack.nova.live.PropertyHelper.*; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java similarity index 87% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java index bd9faf6c11..06002b45da 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java @@ -16,7 +16,7 @@ * limitations under the License. * ==================================================================== */ -package org.jclouds.openstack.nova.compute; +package org.jclouds.openstack.nova.live; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -31,6 +31,7 @@ import org.jclouds.compute.options.TemplateOptions; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; +import org.jclouds.http.handlers.BackoffLimitedRetryHandler; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaAsyncClient; @@ -43,12 +44,14 @@ import org.jclouds.rest.RestContextFactory; import org.jclouds.scriptbuilder.domain.Statements; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.SshException; +import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeGroups; import org.testng.annotations.Test; import java.io.IOException; +import java.net.URISyntaxException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; @@ -69,8 +72,8 @@ import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCreden import static org.jclouds.compute.predicates.NodePredicates.*; import static org.jclouds.compute.predicates.NodePredicates.all; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; -import static org.jclouds.openstack.nova.PropertyHelper.setupKeyPair; +import static org.jclouds.openstack.nova.live.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotNull; @@ -188,6 +191,7 @@ public class NovaComputeServiceLiveTest { protected void checkNodes(Iterable nodes, String tag) throws IOException { _checkNodes(nodes, tag); + for (NodeMetadata node : nodes) { assertEquals(node.getLocation().getScope(), LocationScope.HOST); } @@ -202,12 +206,12 @@ public class NovaComputeServiceLiveTest { Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); assertEquals(fromStore, node.getCredentials()); assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; - assertNotNull(node.getCredentials()); - if (node.getCredentials().identity != null) { - assertNotNull(node.getCredentials().identity); - assertNotNull(node.getCredentials().credential); - sshPing(node); - } +// assertNotNull(node.getCredentials()); +// if (node.getCredentials().identity != null) { +// assertNotNull(node.getCredentials().identity); +// assertNotNull(node.getCredentials().credential); +// doCheckJavaIsInstalledViaSsh(node); +// } } } @@ -219,11 +223,6 @@ public class NovaComputeServiceLiveTest { context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet .of(new SLF4JLoggingModule()), overrides); context.getComputeService().listNodes(); - } catch (AuthorizationException e) { - throw e; - } catch (RuntimeException e) { - e.printStackTrace(); - throw e; } finally { if (context != null) context.close(); @@ -247,41 +246,83 @@ public class NovaComputeServiceLiveTest { // since surefire and eclipse don't otherwise guarantee the order, we are // starting this one alphabetically before create2nodes.. + private String awaitForPublicAddressAssigned(String nodeId) throws InterruptedException { + while (true) { + Set addresses = computeService.getNodeMetadata(nodeId).getPublicAddresses(); + System.out.println(addresses); + if (addresses != null) + if (!addresses.isEmpty()) return addresses.iterator().next(); + Thread.sleep(1000); + } + } + + private void awaitForSshPort(String address, Credentials credentials) throws URISyntaxException { + IPSocket socket = new IPSocket(address, 22); + + JschSshClient ssh = new JschSshClient( + new BackoffLimitedRetryHandler(), socket, 10000, credentials.identity, null, credentials.credential.getBytes()); + while (true) { + try { + System.out.println("ping: " + socket); + ssh.connect(); + return; + } catch (SshException ignore) { + } + } + } + + @Test(enabled = true) public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { String group = this.group + "r"; - try { - computeService.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { - } + computeService.destroyNodesMatching(inGroup(group)); + + Template template = getDefaultTemplateBuilder().options( + computeService.templateOptions() + .overrideCredentialsWith(new Credentials("root", keyPair.get("private"))) + .blockUntilRunning(true)) + .build(); - Template template = getDefaultTemplateBuilder().options(computeService.templateOptions().blockOnPort(22, 120)).build(); try { Set nodes = computeService.createNodesInGroup(group, 1, template); - Credentials good = nodes.iterator().next().getCredentials(); - assert good.identity != null : nodes; - assert good.credential != null : nodes; + + System.out.println("=================================================="); + System.out.println("================ Created ==================="); + + String address = awaitForPublicAddressAssigned(get(nodes, nodes.size() - 1).getId()); + awaitForSshPort(address, new Credentials("root", keyPair.get("private"))); OperatingSystem os = get(nodes, 0).getOperatingSystem(); try { - Map responses = runScriptWithCreds(group, os, new Credentials( - good.identity, "romeo")); + Map responses = runJavaInstallationScriptWithCreds(group, os, new Credentials( + "root", "romeo")); assert false : "shouldn't pass with a bad password\n" + responses; - } catch (RunScriptOnNodesException e) { - assert getRootCause(e).getMessage().contains("Auth fail") : e; + } catch (RunScriptOnNodesException ignore) { + if (!getRootCause(ignore).getMessage().contains("Auth fail")) throw ignore; } + System.out.println("=================================================="); + System.out.println("================ Auth failed ==================="); + for (Map.Entry response : computeService.runScriptOnNodesMatching( runningInGroup(group), Statements.exec("echo hello"), - overrideCredentialsWith(good).wrapInInitScript(false).runAsRoot(false)).entrySet()) + overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet()) assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + response.getValue(); - runScriptWithCreds(group, os, good); + System.out.println("=================================================="); + System.out.println("================ Script ==================="); + + //TODO runJavaInstallationScriptWithCreds(group, os, new Credentials("root", keyPair.get("private"))); + //no response? if os is null (ZYPPER) checkNodes(nodes, group); + Credentials good = nodes.iterator().next().getCredentials(); + //TODO check good is being private key .overrideCredentialsWith + //TODO test for .blockOnPort + } finally { computeService.destroyNodesMatching(inGroup(group)); } @@ -374,14 +415,11 @@ public class NovaComputeServiceLiveTest { assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); } - protected Map runScriptWithCreds(final String group, OperatingSystem os, - Credentials creds) throws RunScriptOnNodesException { - try { - return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) - .nameTask("runScriptWithCreds")); - } catch (SshException e) { - throw e; - } + protected Map runJavaInstallationScriptWithCreds(final String group, OperatingSystem os, + Credentials creds) throws RunScriptOnNodesException { + return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + .nameTask("runJavaInstallationScriptWithCreds")); + } @@ -506,7 +544,7 @@ public class NovaComputeServiceLiveTest { } - template = getDefaultTemplateBuilder().options(blockOnComplete(false).blockOnPort(8080, 600).inboundPorts(22, 8080)) + template = getDefaultTemplateBuilder().options(blockOnComplete(false).inboundPorts(22, 8080)) .build(); // note this is a dependency on the template resolution @@ -636,22 +674,9 @@ public class NovaComputeServiceLiveTest { assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest); } - private void sshPing(NodeMetadata node) throws IOException { - for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate. - try { - doCheckJavaIsInstalledViaSsh(node); - return; - } catch (SshException e) { - try { - Thread.sleep(10 * 1000); - } catch (InterruptedException e1) { - } - continue; - } - } - } protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { + SshClient ssh = context.utils().sshForNode().apply(node); try { ssh.connect(); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java similarity index 91% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java index b7d9aea50d..45e23ac013 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/PropertyHelper.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java @@ -1,4 +1,4 @@ -package org.jclouds.openstack.nova; +package org.jclouds.openstack.nova.live; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableMap; @@ -46,7 +46,7 @@ public class PropertyHelper { properties.setProperty(provider + ".identity", properties.getProperty("test." + provider + ".identity")); properties.setProperty(provider + ".credential", properties.getProperty("test." + provider + ".credential")); properties.setProperty(provider + ".endpoint", properties.getProperty("test." + provider + ".endpoint")); - properties.setProperty(provider + ".apiversion", "test." + provider + ".apiversion"); + properties.setProperty(provider + ".apiversion", properties.getProperty("test." + provider + ".apiversion")); properties.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); properties.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); return properties; diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java index b653ff3aa0..8e672b1087 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java @@ -24,7 +24,6 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.inject.Injector; import com.google.inject.Module; -import org.jclouds.Constants; import org.jclouds.http.HttpResponseException; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; @@ -37,7 +36,7 @@ import org.jclouds.rest.RestContextFactory; import org.jclouds.ssh.SshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.testng.annotations.AfterMethod; -import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; @@ -45,8 +44,7 @@ import java.util.Map; import java.util.Properties; import java.util.concurrent.TimeUnit; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.jclouds.openstack.nova.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.live.PropertyHelper.*; import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; /** @@ -60,55 +58,17 @@ public class ServerCreateLiveTest { protected SshClient.Factory sshFactory; private Predicate socketTester; protected String provider = "nova"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; Map metadata = ImmutableMap.of("jclouds", "rackspace"); Server server = null; + Map keyPair; - - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; - } - - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } - - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } - - - @BeforeGroups(groups = {"live"}) + @BeforeTest public void setupClient() throws IOException { - Properties overrides = setupProperties(); - setupCredentials(overrides); - updateProperties(overrides); + Properties properties = setupOverrides(setupProperties(this.getClass())); - Injector injector = new RestContextFactory().createContextBuilder(provider, identity, credential, - ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), overrides) + Injector injector = new RestContextFactory().createContextBuilder(provider, + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), properties) .buildInjector(); client = injector.getInstance(NovaClient.class); @@ -117,6 +77,8 @@ public class ServerCreateLiveTest { SocketOpen socketOpen = injector.getInstance(SocketOpen.class); socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); injector.injectMembers(socketOpen); // add logger + + keyPair = setupKeyPair(properties); } @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java new file mode 100644 index 0000000000..afbb03ff11 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java @@ -0,0 +1,54 @@ +package org.jclouds.openstack.nova.live.nonmaven; + +import com.google.common.collect.ImmutableSet; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.compute.RunNodesException; +import org.jclouds.compute.domain.NodeMetadata; +import org.jclouds.compute.domain.Template; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Properties; +import java.util.Set; + +import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides; +import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties; + +public class SimpleCreateServerCheck { + private ComputeServiceContextFactory contextFactory; + private ComputeServiceContext context; + + @BeforeTest + public void setupClient() throws IOException { + contextFactory = new ComputeServiceContextFactory(); + Properties properties = setupOverrides(setupProperties(this.getClass())); + context = contextFactory.createContext("nova", + ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties); + } + + @Test + public void testCreateServer() throws RunNodesException { + ComputeService cs = context.getComputeService(); + + TemplateOptions options = new TemplateOptions().blockUntilRunning(false); + Template template = cs.templateBuilder().imageId("95").hardwareId("2").options(options).build(); + Set metedata = cs.createNodesInGroup("test", 1, template); + System.out.println(metedata); + } + + @AfterTest + public void after() { + context.close(); + } + + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json + +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java new file mode 100644 index 0000000000..c868a90c06 --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java @@ -0,0 +1,49 @@ +package org.jclouds.openstack.nova.live.nonmaven; + +import com.google.common.collect.ImmutableSet; +import org.jclouds.compute.ComputeService; +import org.jclouds.compute.ComputeServiceContext; +import org.jclouds.compute.ComputeServiceContextFactory; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.util.Properties; + +import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides; +import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties; + +public class SimpleListCheck { + private ComputeServiceContextFactory contextFactory; + private ComputeServiceContext context; + + @BeforeTest + public void setupClient() throws IOException { + contextFactory = new ComputeServiceContextFactory(); + Properties properties = setupOverrides(setupProperties(this.getClass())); + context = contextFactory.createContext("nova", + ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties); + } + + @Test + public void testLists() { + ComputeService cs = context.getComputeService(); + + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + System.out.println(cs.listAssignableLocations()); + System.out.println(cs.listNodes()); + } + + @AfterTest + public void after() { + context.close(); + } + + //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ + //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json + +} From 78db8f1bfce71c717eb0868e5927a39a463af161 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Thu, 21 Apr 2011 20:12:31 +0400 Subject: [PATCH 41/95] Fixes in live tests --- .../functions/NovaImageToImageTest.java | 15 ++- .../functions/ServerToNodeMetadataTest.java | 105 ++++++++---------- .../nova/domain/ServerStatusTest.java | 19 ++-- .../ParseServerFromJsonResponseTest.java | 40 +++---- .../DeleteServersInVariousStatesLiveTest.java | 23 ---- .../nova/live/NovaClientLiveTest.java | 8 +- .../nova/live/NovaComputeServiceLiveTest.java | 62 +++++------ 7 files changed, 118 insertions(+), 154 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index c4e3e594ae..bbb9eb316e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -18,12 +18,7 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static org.testng.Assert.assertEquals; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; - +import com.google.inject.Guice; import org.jclouds.compute.config.BaseComputeServiceContextModule; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.ImageBuilder; @@ -36,7 +31,11 @@ import org.jclouds.json.config.GsonModule; import org.jclouds.openstack.nova.functions.ParseImageFromJsonResponseTest; import org.testng.annotations.Test; -import com.google.inject.Guice; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; + +import static org.testng.Assert.assertEquals; /** * @author Adrian Cole @@ -53,7 +52,7 @@ public class NovaImageToImageTest { .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) .ids("1").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); Image parsedImage = convertImage(); - + assertEquals(parsedImage, image); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index cdc5a13838..1d6ffd45c3 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -18,25 +18,11 @@ */ package org.jclouds.openstack.nova.compute.functions; -import static org.testng.Assert.assertEquals; - -import java.net.URI; -import java.net.URISyntaxException; -import java.net.UnknownHostException; -import java.util.Map; -import java.util.Set; - -import org.jclouds.compute.domain.Hardware; -import org.jclouds.compute.domain.HardwareBuilder; -import org.jclouds.compute.domain.Image; -import org.jclouds.compute.domain.NodeMetadata; -import org.jclouds.compute.domain.NodeMetadataBuilder; -import org.jclouds.compute.domain.NodeState; -import org.jclouds.compute.domain.OperatingSystem; -import org.jclouds.compute.domain.OsFamily; -import org.jclouds.compute.domain.Processor; -import org.jclouds.compute.domain.Volume; -import org.jclouds.compute.domain.VolumeBuilder; +import com.google.common.base.Suppliers; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import org.jclouds.compute.domain.*; import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationBuilder; @@ -47,10 +33,13 @@ import org.jclouds.openstack.nova.domain.ServerStatus; import org.jclouds.openstack.nova.functions.ParseServerFromJsonResponseTest; import org.testng.annotations.Test; -import com.google.common.base.Suppliers; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.UnknownHostException; +import java.util.Map; +import java.util.Set; + +import static org.testng.Assert.assertEquals; /** * @author Adrian Cole @@ -93,26 +82,26 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); NodeMetadata constructedMetadata = newNodeMetadataBuilder().build(); - + assertEquals(metadata, constructedMetadata); } private NodeMetadataBuilder newNodeMetadataBuilder() throws URISyntaxException { return new NodeMetadataBuilder() - .state(NodeState.PENDING) - .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) - .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) - .id("1234") - .providerId("1234") - .name("sample-server") - .location(new LocationBuilder() - .scope(LocationScope.HOST) - .id("e4d909c290d0fb1ca068ffaddf22cbd0") - .description("e4d909c290d0fb1ca068ffaddf22cbd0") - .parent(provider).build()) - .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) - .uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); + .state(NodeState.PENDING) + .publicAddresses(ImmutableSet.of("67.23.10.132", "::babe:67.23.10.132", "67.23.10.131", "::babe:4317:0A83")) + .privateAddresses(ImmutableSet.of("10.176.42.16", "::babe:10.176.42.16")) + .id("1234") + .providerId("1234") + .name("sample-server") + .location(new LocationBuilder() + .scope(LocationScope.HOST) + .id("e4d909c290d0fb1ca068ffaddf22cbd0") + .description("e4d909c290d0fb1ca068ffaddf22cbd0") + .parent(provider).build()) + .userMetadata(ImmutableMap.of("Server Label", "Web Head 1", "Image Version", "2.1")) + .uri(new URI("http://servers.api.openstack.org/1234/servers/1234")); } @Test @@ -137,7 +126,7 @@ public class ServerToNodeMetadataTest { .version("5.2") .is64Bit(true).build()) .build(); - + assertEquals(metadata, constructedMetadata); } @@ -154,27 +143,27 @@ public class ServerToNodeMetadataTest { .ofInstance(provider), Suppliers.>ofInstance(hardwares)); NodeMetadata metadata = parser.apply(server); - + NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .imageId("1") - .operatingSystem(new OperatingSystem.Builder() - .family(OsFamily.CENTOS) - .description("CentOS 5.2") - .version("5.2") - .is64Bit(true).build()) - .hardware(new HardwareBuilder() - .ids("1") - .name("256 MB Server") - .processors(ImmutableList.of(new Processor(1.0, 1.0))) - .ram(256) - .volumes(ImmutableList.of(new VolumeBuilder() - .type(Volume.Type.LOCAL) - .size(10.0f) - .durable(true) - .bootDevice(true).build())) - .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) - .build()) - .build(); + .imageId("1") + .operatingSystem(new OperatingSystem.Builder() + .family(OsFamily.CENTOS) + .description("CentOS 5.2") + .version("5.2") + .is64Bit(true).build()) + .hardware(new HardwareBuilder() + .ids("1") + .name("256 MB Server") + .processors(ImmutableList.of(new Processor(1.0, 1.0))) + .ram(256) + .volumes(ImmutableList.of(new VolumeBuilder() + .type(Volume.Type.LOCAL) + .size(10.0f) + .durable(true) + .bootDevice(true).build())) + .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) + .build()) + .build(); assertEquals(metadata, constructedMetadata); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java index b01e46fb35..76d54f2d37 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/domain/ServerStatusTest.java @@ -19,18 +19,17 @@ package org.jclouds.openstack.nova.domain; -import static junit.framework.Assert.assertTrue; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import org.testng.annotations.Test; import java.util.Arrays; import java.util.List; import java.util.Set; -import org.testng.annotations.Test; - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; +import static junit.framework.Assert.assertTrue; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; /** * Tests behavior of {@code CreateImageBinder} @@ -53,11 +52,11 @@ public class ServerStatusTest { List allStatuses = Lists.newArrayList(knownStatuses); allStatuses.add("UNRECOGNIZED"); - + Set enumValues = Sets.newHashSet(ServerStatus.values()); - + assertEquals(enumValues.size(), allStatuses.size()); - + for (String status : allStatuses) { assertTrue(enumValues.contains(ServerStatus.valueOf(status))); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 7be82417b7..1ff4c2d596 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -18,17 +18,13 @@ */ package org.jclouds.openstack.nova.functions; -import static org.testng.Assert.assertEquals; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.SimpleTimeZone; - +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpResponse; import org.jclouds.http.functions.UnwrapOnlyJsonValue; import org.jclouds.io.Payloads; @@ -39,13 +35,16 @@ import org.jclouds.openstack.nova.domain.Server; import org.jclouds.openstack.nova.domain.ServerStatus; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; +import java.io.InputStream; +import java.net.UnknownHostException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.SimpleTimeZone; + +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code ParseServerFromJsonResponse} @@ -99,8 +98,9 @@ public class ParseServerFromJsonResponseTest { InputStream is = ParseServerFromJsonResponseTest.class.getResourceAsStream("/test_get_server_detail.json"); - UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() {})); - + UnwrapOnlyJsonValue parser = i.getInstance(Key.get(new TypeLiteral>() { + })); + return (Server) parser.apply(new HttpResponse(200, "ok", Payloads.newInputStreamPayload(is))); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java index 815a36ed5f..c0809def1d 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java @@ -21,7 +21,6 @@ package org.jclouds.openstack.nova.live; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; -import org.jclouds.http.HttpResponseException; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaClient; import org.jclouds.openstack.nova.domain.Server; @@ -32,8 +31,6 @@ import org.testng.annotations.Test; import java.util.Map; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; - /** * @author Victor Galkin */ @@ -53,26 +50,6 @@ public class DeleteServersInVariousStatesLiveTest { Map metadata = ImmutableMap.of("jclouds", "rackspace"); Server server = null; - @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") - public void testCreateServerWithUnknownImage() throws Exception { - try { - server = client.createServer("serverName", String.valueOf(88888888), "1", withFile("/etc/jclouds.txt", - "rackspace".getBytes()).withMetadata(metadata)); - } catch (HttpResponseException e) { - throw e; - } - } - - @Test(expectedExceptions = HttpResponseException.class, expectedExceptionsMessageRegExp = ".*Internal Server Error.*") - public void testCreateServerWithUnknownFlavor() throws Exception { - try { - server = client.createServer("serverName", String.valueOf(13), "88888888", withFile("/etc/jclouds.txt", - "rackspace".getBytes()).withMetadata(metadata)); - } catch (HttpResponseException e) { - throw e; - } - } - @AfterMethod public void after() { if (server != null) client.deleteServer(server.getId()); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java index cab458cb34..e21623074e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java @@ -64,6 +64,7 @@ import static org.testng.Assert.*; @Test(groups = "live", sequential = true) public class NovaClientLiveTest { + private int testImageId = 95; protected NovaClient client; protected SshClient.Factory sshFactory; private Predicate socketTester; @@ -75,6 +76,7 @@ public class NovaClientLiveTest { Map metadata = ImmutableMap.of("jclouds", "rackspace"); private int createdImageId; + @BeforeTest public void setupClient() throws IOException { Properties properties = setupOverrides(setupProperties(this.getClass())); @@ -228,7 +230,7 @@ public class NovaClientLiveTest { @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = client.getImage(95).getURI().toASCIIString(); + String imageRef = client.getImage(testImageId).getURI().toASCIIString(); String flavorRef = client.getFlavor(1).getURI().toASCIIString(); String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", @@ -290,7 +292,7 @@ public class NovaClientLiveTest { assertEquals(server.getMetadata(), metadata); - assertEquals(server.getImageRef(), "endpoint" + "/v1.1/images/95"); + assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId))); // listAddresses tests.. assertEquals(client.getAddresses(serverId), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); @@ -298,7 +300,7 @@ public class NovaClientLiveTest { assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); assertPassword(server, adminPass); - assertEquals(server.getFlavorRef(), "endpoint" + "/v1.1/flavors/1"); + assertTrue(server.getFlavorRef().endsWith("1")); assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java index 06002b45da..76599ad707 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java @@ -92,7 +92,7 @@ public class NovaComputeServiceLiveTest { protected ComputeServiceContext context; protected ComputeService computeService; - protected Template template; + protected Map keyPair; protected String provider; @@ -218,10 +218,13 @@ public class NovaComputeServiceLiveTest { @Test(enabled = true, expectedExceptions = AuthorizationException.class) public void testCorrectAuthException() throws Exception { + Properties properties = new Properties(); + properties.putAll(overrides); + properties.remove(provider + ".identity"); ComputeServiceContext context = null; try { context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet - .of(new SLF4JLoggingModule()), overrides); + .of(new SLF4JLoggingModule()), properties); context.getComputeService().listNodes(); } finally { if (context != null) @@ -328,16 +331,16 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true, dependsOnMethods = {"testImagesCache"}) + @Test(enabled = true) public void testTemplateMatch() throws Exception { - template = buildTemplate(computeService.templateBuilder()); + Template template = buildTemplate(getDefaultTemplateBuilder()); Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build(); assertEquals(toMatch.getImage(), template.getImage()); } - protected void checkHttpGet(NodeMetadata node) { - ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); - } +// protected void checkHttpGet(NodeMetadata node) { +// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); +// } @Test(enabled = true, dependsOnMethods = "testCompareSizes") public void testCreateTwoNodesWithRunScript() throws Exception { @@ -346,9 +349,9 @@ public class NovaComputeServiceLiveTest { } catch (NoSuchElementException e) { } - refreshTemplate(); + try { - nodes = newTreeSet(computeService.createNodesInGroup(group, 2, template)); + nodes = newTreeSet(computeService.createNodesInGroup(group, 2, getDefaultTemplateBuilder().build())); } catch (RunNodesException e) { nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); throw e; @@ -360,30 +363,23 @@ public class NovaComputeServiceLiveTest { // credentials aren't always the same // assertEquals(node1.getCredentials(), node2.getCredentials()); - assertLocationSameOrChild(node1.getLocation(), template.getLocation()); - assertLocationSameOrChild(node2.getLocation(), template.getLocation()); + assertLocationSameOrChild(node1.getLocation(), getDefaultTemplateBuilder().build().getLocation()); + assertLocationSameOrChild(node2.getLocation(), getDefaultTemplateBuilder().build().getLocation()); checkImageIdMatchesTemplate(node1); checkImageIdMatchesTemplate(node2); checkOsMatchesTemplate(node1); checkOsMatchesTemplate(node2); } - private void refreshTemplate() { - template = buildTemplate(computeService.templateBuilder()); - - template.getOptions().installPrivateKey(keyPair.get("private")).authorizePublicKey(keyPair.get("public")) - .runScript(buildScript(template.getImage().getOperatingSystem())); - } - protected void checkImageIdMatchesTemplate(NodeMetadata node) { if (node.getImageId() != null) - assertEquals(node.getImageId(), template.getImage().getId()); + assertEquals(node.getImageId(), getDefaultTemplateBuilder().build().getImage().getId()); } protected void checkOsMatchesTemplate(NodeMetadata node) { if (node.getOperatingSystem() != null) - assert node.getOperatingSystem().getFamily().equals(template.getImage().getOperatingSystem().getFamily()) : String - .format("expecting family %s but got %s", template.getImage().getOperatingSystem().getFamily(), node + assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String + .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node .getOperatingSystem()); } @@ -395,16 +391,17 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true, dependsOnMethods = "testCreateTwoNodesWithRunScript") + @Test(enabled = true) public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { + testCreateTwoNodesWithRunScript(); initializeContextAndClient(overrides); - refreshTemplate(); - TreeSet nodes = newTreeSet(computeService.createNodesInGroup(group, 1, template)); + + TreeSet nodes = newTreeSet(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build())); checkNodes(nodes, group); NodeMetadata node = nodes.first(); this.nodes.add(node); assertEquals(nodes.size(), 1); - assertLocationSameOrChild(node.getLocation(), template.getLocation()); + assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation()); checkOsMatchesTemplate(node); } @@ -444,7 +441,7 @@ public class NovaComputeServiceLiveTest { NodeMetadata metadata = computeService.getNodeMetadata(node.getId()); assertEquals(metadata.getProviderId(), node.getProviderId()); assertEquals(metadata.getGroup(), node.getGroup()); - assertLocationSameOrChild(metadata.getLocation(), template.getLocation()); + assertLocationSameOrChild(metadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); checkImageIdMatchesTemplate(metadata); checkOsMatchesTemplate(metadata); assert (metadata.getState() == NodeState.RUNNING) : metadata; @@ -544,24 +541,25 @@ public class NovaComputeServiceLiveTest { } - template = getDefaultTemplateBuilder().options(blockOnComplete(false).inboundPorts(22, 8080)) + Template template = getDefaultTemplateBuilder().options(blockOnComplete(false).inboundPorts(22, 8080)) .build(); // note this is a dependency on the template resolution - template.getOptions().runScript( - RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() - .getOperatingSystem())); +// template.getOptions().runScript( +// RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() +// .getOperatingSystem())); + try { NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, template)); - checkHttpGet(node); + //checkHttpGet(node); } finally { computeService.destroyNodesMatching(inGroup(group)); } } - @Test(enabled = true/* , dependsOnMethods = "testCompareSizes" */) + @Test(enabled = true) public void testTemplateOptions() throws Exception { TemplateOptions options = new TemplateOptions().withMetadata(); Template t = computeService.templateBuilder().smallest().options(options).build(); From 4198f23f4b1352631eb832de2269d0f3eae20f7b Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 22 Apr 2011 13:26:31 +0400 Subject: [PATCH 42/95] test classes for development --- ...rverCheck.java => ComputeSericeCheck.java} | 18 ++++++- .../openstack/nova/live/PropertyHelper.java | 8 +-- .../nova/live/nonmaven/SimpleListCheck.java | 49 ------------------- .../nova/src/test/resources/.gitignore | 1 + 4 files changed, 22 insertions(+), 54 deletions(-) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{nonmaven/SimpleCreateServerCheck.java => ComputeSericeCheck.java} (79%) delete mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java create mode 100644 sandbox-apis/nova/src/test/resources/.gitignore diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java similarity index 79% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java index afbb03ff11..d99854eb36 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleCreateServerCheck.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java @@ -1,4 +1,4 @@ -package org.jclouds.openstack.nova.live.nonmaven; +package org.jclouds.openstack.nova.live; import com.google.common.collect.ImmutableSet; import org.jclouds.compute.ComputeService; @@ -21,7 +21,11 @@ import java.util.Set; import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides; import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties; -public class SimpleCreateServerCheck { +/** + * Not intended to be run with maven and does not performs a cleanup after tests + * @author Dmitri Babaev + */ +public class ComputeSericeCheck { private ComputeServiceContextFactory contextFactory; private ComputeServiceContext context; @@ -32,6 +36,16 @@ public class SimpleCreateServerCheck { context = contextFactory.createContext("nova", ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties); } + + @Test + public void testLists() { + ComputeService cs = context.getComputeService(); + + System.out.println(cs.listImages()); + System.out.println(cs.listHardwareProfiles()); + System.out.println(cs.listAssignableLocations()); + System.out.println(cs.listNodes()); + } @Test public void testCreateServer() throws RunNodesException { diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java index 45e23ac013..b12950470f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/PropertyHelper.java @@ -8,13 +8,13 @@ import org.jclouds.Constants; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.util.Map; import java.util.Properties; /** * @author Victor Galkin */ - public class PropertyHelper { public static String provider = "nova"; @@ -30,10 +30,12 @@ public class PropertyHelper { "public", Files.toString(new File(properties.getProperty("test.ssh.keyfile.public")), Charsets.UTF_8)); } - public static Properties setupProperties(Class clazz) throws IOException { + public static Properties setupProperties(Class clazz) throws IOException { Properties properties = new Properties(); - properties.load(clazz.getResourceAsStream("/test.properties")); + InputStream propertiesStream = clazz.getResourceAsStream("/test.properties"); + if (propertiesStream != null) + properties.load(propertiesStream); overridePropertyFromSystemProperty(properties, "test." + provider + ".endpoint"); overridePropertyFromSystemProperty(properties, "test." + provider + ".apiversion"); overridePropertyFromSystemProperty(properties, "test." + provider + ".identity"); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java deleted file mode 100644 index c868a90c06..0000000000 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/nonmaven/SimpleListCheck.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.jclouds.openstack.nova.live.nonmaven; - -import com.google.common.collect.ImmutableSet; -import org.jclouds.compute.ComputeService; -import org.jclouds.compute.ComputeServiceContext; -import org.jclouds.compute.ComputeServiceContextFactory; -import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; -import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.util.Properties; - -import static org.jclouds.openstack.nova.live.PropertyHelper.setupOverrides; -import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties; - -public class SimpleListCheck { - private ComputeServiceContextFactory contextFactory; - private ComputeServiceContext context; - - @BeforeTest - public void setupClient() throws IOException { - contextFactory = new ComputeServiceContextFactory(); - Properties properties = setupOverrides(setupProperties(this.getClass())); - context = contextFactory.createContext("nova", - ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties); - } - - @Test - public void testLists() { - ComputeService cs = context.getComputeService(); - - System.out.println(cs.listImages()); - System.out.println(cs.listHardwareProfiles()); - System.out.println(cs.listAssignableLocations()); - System.out.println(cs.listNodes()); - } - - @AfterTest - public void after() { - context.close(); - } - - //curl -v -H "X-Auth-User:admin" -H "X-Auth-Key: d744752f-20d3-4d75-979f-f62f16033b07" http://dragon004.hw.griddynamics.net:8774/v1.0/ - //curl -v -H "X-Auth-Token: c97b10659008d5a9ce91462f8c6a5c2c80439762" http://dragon004.hw.griddynamics.net:8774/v1.0/images/detail?format=json - -} diff --git a/sandbox-apis/nova/src/test/resources/.gitignore b/sandbox-apis/nova/src/test/resources/.gitignore new file mode 100644 index 0000000000..c6e479480a --- /dev/null +++ b/sandbox-apis/nova/src/test/resources/.gitignore @@ -0,0 +1 @@ +/test.properties From 27c1162eaf201dd21ee300df39109b25dd62dc08 Mon Sep 17 00:00:00 2001 From: Dmitri Babaev Date: Fri, 22 Apr 2011 18:01:59 +0400 Subject: [PATCH 43/95] unit test fixes --- .../java/org/jclouds/openstack/nova/NovaAsyncClientTest.java | 4 ++-- .../nova/compute/functions/NovaImageToImageTest.java | 2 +- .../nova/compute/functions/ServerToNodeMetadataTest.java | 4 ++-- .../openstack/nova/options/CreateServerOptionsTest.java | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 9ba20c56e6..953dfcc98f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -387,9 +387,9 @@ public class NovaAsyncClientTest extends RestClientTest { Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); HttpRequest request = processor.createRequest(method, 2, "foo"); - assertRequestLineEquals(request, "PUT http://endpoint/vapiversion/servers/2 HTTP/1.1"); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); - assertPayloadEquals(request, "{\"server\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); + assertPayloadEquals(request, "{\"changePassword\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); assertResponseParserClassEquals(method, request, ReleasePayloadAndReturn.class); assertSaxResponseParserClassEquals(method, null); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java index bbb9eb316e..9d1ae36b4b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/NovaImageToImageTest.java @@ -50,7 +50,7 @@ public class NovaImageToImageTest { .operatingSystem( new OperatingSystem.Builder().family(OsFamily.CENTOS).version("5.2").description("CentOS 5.2").is64Bit(true) .build()).description("CentOS 5.2").defaultCredentials(new Credentials("root", null)) - .ids("1").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); + .ids("2").version("1286712000000").uri(new URI("https://servers.api.rackspacecloud.com/v1.1/1234/images/1")).build(); Image parsedImage = convertImage(); assertEquals(parsedImage, image); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index 1d6ffd45c3..a27634074b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -119,7 +119,7 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .imageId("1") + .imageId("2") .operatingSystem(new OperatingSystem.Builder() .family(OsFamily.CENTOS) .description("CentOS 5.2") @@ -145,7 +145,7 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .imageId("1") + .imageId("2") .operatingSystem(new OperatingSystem.Builder() .family(OsFamily.CENTOS) .description("CentOS 5.2") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java index 11ace1d635..0facf5b16e 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/options/CreateServerOptionsTest.java @@ -45,7 +45,7 @@ public class CreateServerOptionsTest { public void testAddPayloadToRequestMapOfStringStringHttpRequest() { CreateServerOptions options = new CreateServerOptions(); HttpRequest request = buildRequest(options); - assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2}}", request.getPayload().getRawContent()); + assertEquals("{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\"}}", request.getPayload().getRawContent()); } private HttpRequest buildRequest(CreateServerOptions options) { @@ -72,7 +72,7 @@ public class CreateServerOptionsTest { private void assertFile(HttpRequest request) { assertEquals(request.getPayload().getRawContent(), - "{\"server\":{\"name\":\"foo\",\"imageRef\":1,\"flavorRef\":2,\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); + "{\"server\":{\"name\":\"foo\",\"imageRef\":\"1\",\"flavorRef\":\"2\",\"personality\":[{\"path\":\"/tmp/rhubarb\",\"contents\":\"Zm9v\"}]}}"); } @Test From b9a5397a45b1b8a19a508a11032fd087f709bf3d Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 22 Apr 2011 20:19:29 +0400 Subject: [PATCH 44/95] Fixes in live tests --- .../openstack/nova/NovaAsyncClientTest.java | 36 +++---- .../functions/ServerToNodeMetadataTest.java | 38 +++---- .../openstack/nova/live/ClientBase.java | 100 ++++++++++++++++++ .../DeleteServersInVariousStatesLiveTest.java | 21 +--- .../nova/src/test/resources/keys/rhelimg.pem | 15 +++ 5 files changed, 155 insertions(+), 55 deletions(-) create mode 100644 sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java create mode 100644 sandbox-apis/nova/src/test/resources/keys/rhelimg.pem diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 953dfcc98f..6bb67d04f8 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -18,22 +18,9 @@ */ package org.jclouds.openstack.nova; -import static org.jclouds.Constants.PROPERTY_API_VERSION; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; -import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; -import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; -import static org.testng.Assert.assertEquals; - -import java.io.IOException; -import java.lang.reflect.Method; -import java.net.URI; -import java.util.Date; -import java.util.Properties; - -import javax.ws.rs.core.MediaType; - +import com.google.common.collect.ImmutableMap; +import com.google.inject.Module; +import com.google.inject.TypeLiteral; import org.jclouds.http.HttpRequest; import org.jclouds.http.RequiresHttp; import org.jclouds.http.functions.ReleasePayloadAndReturn; @@ -58,9 +45,20 @@ import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.internal.RestAnnotationProcessor; import org.testng.annotations.Test; -import com.google.common.collect.ImmutableMap; -import com.google.inject.Module; -import com.google.inject.TypeLiteral; +import javax.ws.rs.core.MediaType; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.URI; +import java.util.Date; +import java.util.Properties; + +import static org.jclouds.Constants.PROPERTY_API_VERSION; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withMetadata; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.changesSince; +import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; +import static org.jclouds.openstack.nova.options.RebuildServerOptions.Builder.withImage; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code NovaAsyncClient} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java index a27634074b..33e55af97a 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/compute/functions/ServerToNodeMetadataTest.java @@ -145,25 +145,25 @@ public class ServerToNodeMetadataTest { NodeMetadata metadata = parser.apply(server); NodeMetadata constructedMetadata = newNodeMetadataBuilder() - .imageId("2") - .operatingSystem(new OperatingSystem.Builder() - .family(OsFamily.CENTOS) - .description("CentOS 5.2") - .version("5.2") - .is64Bit(true).build()) - .hardware(new HardwareBuilder() - .ids("1") - .name("256 MB Server") - .processors(ImmutableList.of(new Processor(1.0, 1.0))) - .ram(256) - .volumes(ImmutableList.of(new VolumeBuilder() - .type(Volume.Type.LOCAL) - .size(10.0f) - .durable(true) - .bootDevice(true).build())) - .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) - .build()) - .build(); + .imageId("2") + .operatingSystem(new OperatingSystem.Builder() + .family(OsFamily.CENTOS) + .description("CentOS 5.2") + .version("5.2") + .is64Bit(true).build()) + .hardware(new HardwareBuilder() + .ids("1") + .name("256 MB Server") + .processors(ImmutableList.of(new Processor(1.0, 1.0))) + .ram(256) + .volumes(ImmutableList.of(new VolumeBuilder() + .type(Volume.Type.LOCAL) + .size(10.0f) + .durable(true) + .bootDevice(true).build())) + .uri(new URI("http://servers.api.openstack.org/1234/flavors/1")) + .build()) + .build(); assertEquals(metadata, constructedMetadata); } diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java new file mode 100644 index 0000000000..77a9fc3fea --- /dev/null +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java @@ -0,0 +1,100 @@ +package org.jclouds.openstack.nova.live; + +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.inject.Injector; +import com.google.inject.Module; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.NovaClient; +import org.jclouds.openstack.nova.domain.Image; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.predicates.RetryablePredicate; +import org.jclouds.predicates.SocketOpen; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.ssh.SshClient; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.BeforeTest; + +import java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.concurrent.TimeUnit; + +import static org.jclouds.openstack.nova.live.PropertyHelper.*; +import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; + +/** + * @author Victor Galkin + */ +public class ClientBase { + protected int testImageId = 95; + protected NovaClient client; + protected SshClient.Factory sshFactory; + private Predicate socketTester; + protected String provider = "nova"; + protected String serverPrefix = System.getProperty("user.name") + ".cs"; + protected Map keyPair; + private int serverId; + private String adminPass; + Map metadata = ImmutableMap.of("jclouds", "rackspace"); + private int createdImageId; + + + @BeforeTest + public void before() throws IOException { + Properties properties = setupOverrides(setupProperties(this.getClass())); + + Injector injector = new RestContextFactory().createContextBuilder(provider, + ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), properties) + .buildInjector(); + + client = injector.getInstance(NovaClient.class); + + sshFactory = injector.getInstance(SshClient.Factory.class); + SocketOpen socketOpen = injector.getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); + injector.injectMembers(socketOpen); // add logger + + keyPair = setupKeyPair(properties); + } + + protected Server getDefaultServerImmediately() { + String defaultName = serverPrefix + "default"; + for (Server server : client.listServers()) { + if (server.getName().equals(defaultName)) + return server; + } + return createDefaultServer(defaultName); + } + + private Server createDefaultServer(String serverName) { + String imageRef = client.getImage(testImageId).getURI().toASCIIString(); + String flavorRef = client.getFlavor(1).getURI().toASCIIString(); + + return client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", + "rackspace".getBytes()).withMetadata(metadata)); + } + + protected Image getDefaultImageImmediately(Server server) { + String defaultName = "hoofie"; + for (Image image : client.listImages()) { + if (image.getName() != null) + if (image.getName().equals(defaultName)) + return image; + } + return createDefaultImage("hoofie", server); + } + + private Image createDefaultImage(String name, Server server) { + return client.createImageFromServer("hoofie", server.getId()); + } + + protected void waitServerDeleted(int serverId) throws InterruptedException { + while (null != client.getServer(serverId)) { + System.out.println("Await deleted server" + serverId); + Thread.sleep(1000); + } + } +} diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java index c0809def1d..3098c1f34b 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java @@ -42,10 +42,8 @@ public class DeleteServersInVariousStatesLiveTest { protected SshClient.Factory sshFactory; private Predicate socketTester; protected String provider = "nova"; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; + + private int testImageId = 95; Map metadata = ImmutableMap.of("jclouds", "rackspace"); Server server = null; @@ -56,19 +54,8 @@ public class DeleteServersInVariousStatesLiveTest { } @Test(enabled = true) - public void testCreateServer() throws Exception { -// String imageRef = client.getImage(13).getURI().toASCIIString(); -// String flavorRef = client.getFlavor(1).getURI().toASCIIString(); -// String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); -// Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", -// "rackspace".getBytes()).withMetadata(metadata)); -// -// assertNotNull(server.getAdminPass()); -// assertEquals(server.getStatus(), ServerStatus.BUILD); -// serverId = server.getId(); -// adminPass = server.getAdminPass(); -// blockUntilServerActive(serverId); -// client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); + public void testDeleteAfterCreate() throws Exception { + } private void blockUntilServerActive(int serverId) throws InterruptedException { diff --git a/sandbox-apis/nova/src/test/resources/keys/rhelimg.pem b/sandbox-apis/nova/src/test/resources/keys/rhelimg.pem new file mode 100644 index 0000000000..f6bc72b83c --- /dev/null +++ b/sandbox-apis/nova/src/test/resources/keys/rhelimg.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICWgIBAAKBgQDItJzHxyFVPZwjE2Wl+17OLJotFruaMaoKLOH8yOr0WnKFYDCs +AiN88AvwH2YKaF6SQR3gmMTE8SbuKSXR/PVUZfWfhvDinVbAi8gn8A6P5xkym5A6 +uBnJn1Mb0rZAKCJT/nN62vomGGO/3VYkpQcKAWgfSpaB7F1BIebaWR/CgQIBIwKB +gQCa1Hjx4sHxTMjn28NxaiSQa4zg9EeUNPDjRzH9hQ0FpNwAfWdgHugtLjUYUrxu +bcVMQNyIsF1HeDP5jXTycq6e01EYDODnuPC3a06u6Drep0xm/8XuODwekApN811r +kfx9AsgRL9ZwkLqMY8E+OXUmsGVXzEM9jUO3iwA4CCBb/wJBAO0klCumLDm9rYXX +m3YHuwqcgFPnwSodTWX4tIzHKM0tn3PwajJ1x9kCVxsj9uFzz4LXNrxVrUKcYnVx +e/d7sksCQQDYqkr+vt9XaoQSio1M/OOkzc3ynmqtYrNrq9xM1M5IYY2/y5IVLAU3 +6tiyqXTObSTJT+iFd+OwQymi8FgeN77jAkBzLwYj1F6fs+aRd1ojYtcxCi+zubWY +HNxzW4rlSsqszQROQZKqy35TdipPAtb/yolczu6zP46rU0XEA+vBWVaZAkB1nkX4 +ATdp9/6NuO2e0mzzEKMADNrTJvOveo2Iy0tpHwPOhHPfm43N5eNZrHKb8htItlmn +ijnGFdTGKrN+HkMNAkAqh8ulNxVBAK5E0VzzzC2zAh2UFRe3J5K0SgzFkR8W9aM1 +Vb+iZvj4tVlbFtFLGv0ssty8Q0jS7+Hy75XMatry +-----END RSA PRIVATE KEY----- From 8c8161ec7962d5765da697c380072981ea90a7fb Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 22 Apr 2011 20:30:16 +0400 Subject: [PATCH 45/95] Live tests fix --- .../openstack/nova/NovaAsyncClientTest.java | 2 +- .../ParseServerFromJsonResponseTest.java | 52 +- .../DeleteServersInVariousStatesLiveTest.java | 1 + .../nova/live/NovaClientLiveTest.java | 150 +- .../nova/live/NovaComputeServiceLiveTest.java | 1403 +++++++++-------- 5 files changed, 793 insertions(+), 815 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java index 6bb67d04f8..6728c0acf1 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/NovaAsyncClientTest.java @@ -385,7 +385,7 @@ public class NovaAsyncClientTest extends RestClientTest { Method method = NovaAsyncClient.class.getMethod("changeAdminPass", int.class, String.class); HttpRequest request = processor.createRequest(method, 2, "foo"); - assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action HTTP/1.1"); + assertRequestLineEquals(request, "POST http://endpoint/vapiversion/servers/2/action HTTP/1.1"); assertNonPayloadHeadersEqual(request, ""); assertPayloadEquals(request, "{\"changePassword\":{\"adminPass\":\"foo\"}}", MediaType.APPLICATION_JSON, false); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java index 1ff4c2d596..1d862030bc 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/functions/ParseServerFromJsonResponseTest.java @@ -18,31 +18,33 @@ */ package org.jclouds.openstack.nova.functions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.TypeLiteral; -import org.jclouds.http.HttpResponse; -import org.jclouds.http.functions.UnwrapOnlyJsonValue; -import org.jclouds.io.Payloads; -import org.jclouds.json.config.GsonModule; -import org.jclouds.openstack.nova.domain.Address; -import org.jclouds.openstack.nova.domain.Addresses; -import org.jclouds.openstack.nova.domain.Server; -import org.jclouds.openstack.nova.domain.ServerStatus; -import org.testng.annotations.Test; - -import java.io.InputStream; -import java.net.UnknownHostException; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.SimpleTimeZone; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Iterables; +import com.google.inject.Guice; +import com.google.inject.Injector; +import com.google.inject.Key; +import com.google.inject.TypeLiteral; +import org.jclouds.http.HttpResponse; +import org.jclouds.http.functions.UnwrapOnlyJsonValue; +import org.jclouds.io.Payloads; +import org.jclouds.json.config.GsonModule; +import org.jclouds.openstack.nova.domain.Address; +import org.jclouds.openstack.nova.domain.Addresses; +import org.jclouds.openstack.nova.domain.Server; +import org.jclouds.openstack.nova.domain.ServerStatus; +import org.testng.annotations.Test; + +import java.io.InputStream; +import java.net.UnknownHostException; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.SimpleTimeZone; + +import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals; diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java index 3098c1f34b..280688e794 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java @@ -29,6 +29,7 @@ import org.jclouds.ssh.SshClient; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; +import java.security.SecureRandom; import java.util.Map; /** diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java index e21623074e..5207c3a609 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java @@ -19,41 +19,24 @@ package org.jclouds.openstack.nova.live; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; -import com.google.inject.Injector; -import com.google.inject.Module; import org.jclouds.domain.Credentials; import org.jclouds.http.HttpResponseException; import org.jclouds.io.Payload; -import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; -import org.jclouds.openstack.nova.NovaClient; import org.jclouds.openstack.nova.domain.*; import org.jclouds.openstack.nova.options.RebuildServerOptions; -import org.jclouds.predicates.RetryablePredicate; -import org.jclouds.predicates.SocketOpen; -import org.jclouds.rest.RestContextFactory; import org.jclouds.ssh.SshClient; -import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.jclouds.util.Strings2; import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import java.io.IOException; -import java.security.SecureRandom; -import java.util.Map; -import java.util.Properties; import java.util.Set; -import java.util.concurrent.TimeUnit; -import static org.jclouds.openstack.nova.live.PropertyHelper.*; -import static org.jclouds.openstack.nova.options.CreateServerOptions.Builder.withFile; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; +import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code NovaClient} @@ -62,9 +45,9 @@ import static org.testng.Assert.*; */ // disabled [Web Hosting #129069 @Test(groups = "live", sequential = true) -public class NovaClientLiveTest { +public class NovaClientLiveTest extends ClientBase{ - private int testImageId = 95; +<<<<<<< .mine private int testImageId = 95; protected NovaClient client; protected SshClient.Factory sshFactory; private Predicate socketTester; @@ -75,8 +58,8 @@ public class NovaClientLiveTest { private String adminPass; Map metadata = ImmutableMap.of("jclouds", "rackspace"); private int createdImageId; - - +=======>>>>>>> .theirs +<<<<<<< .mine @BeforeTest public void setupClient() throws IOException { Properties properties = setupOverrides(setupProperties(this.getClass())); @@ -95,7 +78,7 @@ public class NovaClientLiveTest { keyPair = setupKeyPair(properties); } - @Test +=======>>>>>>> .theirs @Test public void testListServers() throws Exception { Set response = client.listServers(); assert null != response; @@ -228,18 +211,21 @@ public class NovaClientLiveTest { } + + @Test(enabled = true) public void testCreateServer() throws Exception { - String imageRef = client.getImage(testImageId).getURI().toASCIIString(); +<<<<<<< .mine String imageRef = client.getImage(testImageId).getURI().toASCIIString(); String flavorRef = client.getFlavor(1).getURI().toASCIIString(); String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", "rackspace".getBytes()).withMetadata(metadata)); - assertNotNull(server.getAdminPass()); +======= Server server = getDefaultServerImmediately(); +>>>>>>> .theirs assertNotNull(server.getAdminPass()); assertEquals(server.getStatus(), ServerStatus.BUILD); - serverId = server.getId(); - adminPass = server.getAdminPass(); + int serverId = server.getId(); + String adminPass = server.getAdminPass(); blockUntilServerActive(serverId); blockUntilPublicAddress(serverId); client.getServer(serverId).getAddresses().getPublicAddresses().iterator().next().getAddress(); @@ -281,33 +267,34 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 300000) public void testServerDetails() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - Server server = client.getServer(serverId); - + Server server = getDefaultServerImmediately(); assertNotNull(server.getHostId(), "Host id: "); assertEquals(server.getStatus(), ServerStatus.ACTIVE); - assertNotNull(server.getAddresses()); // check metadata assertEquals(server.getMetadata(), metadata); - +<<<<<<< .mine assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId))); - // listAddresses tests.. - assertEquals(client.getAddresses(serverId), server.getAddresses()); +======= assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId))); +>>>>>>> .theirs // listAddresses tests.. + assertEquals(client.getAddresses(server.getId()), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); - assertEquals(client.listPublicAddresses(serverId), server.getAddresses().getPublicAddresses()); + assertEquals(client.listPublicAddresses(server.getId()), server.getAddresses().getPublicAddresses()); assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); - assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); +<<<<<<< .mine assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); assertPassword(server, adminPass); assertTrue(server.getFlavorRef().endsWith("1")); - assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); +======= assertEquals(client.listPrivateAddresses(server.getId()), server.getAddresses().getPrivateAddresses()); + assertPassword(server, server.getAdminPass()); + assertTrue(server.getFlavorRef().endsWith("1")); +>>>>>>> .theirs assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); } private void assertPassword(Server server, String pass) throws IOException { IPSocket socket = new IPSocket(Iterables.get(server.getAddresses().getPublicAddresses(), 0).getAddress(), 22); - socketTester.apply(socket); + //socketTester.apply(socket); SshClient client = sshFactory.create(socket, new Credentials("root", keyPair.get("private"))); try { @@ -323,8 +310,8 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testRenameServer() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - Server server = client.getServer(serverId); + Server server = getDefaultServerImmediately(); + int serverId = server.getId(); String oldName = server.getName(); client.renameServer(serverId, oldName + "new"); blockUntilServerActive(serverId); @@ -333,49 +320,51 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 5 * 60 * 1000) public void testChangePassword() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); + int serverId = getDefaultServerImmediately().getId(); blockUntilServerActive(serverId); client.changeAdminPass(serverId, "elmo"); assertPassword(client.getServer(serverId), "elmo"); - this.adminPass = "elmo"; + } @Test(enabled = true, timeOut = 10 * 600 * 1000) public void testCreateImage() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - Image image = client.createImageFromServer("hoofie", serverId); + Server server = getDefaultServerImmediately(); + Image image = getDefaultImageImmediately(server); + blockUntilImageActive(image.getId()); assertEquals("hoofie", image.getName()); - assertEquals(serverId, image.getServerRef()); - createdImageId = image.getId(); - blockUntilImageActive(createdImageId); + assertEquals(image.getServerRef(), ""); } + @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebuildServer() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - client.rebuildServer(serverId, new RebuildServerOptions().withImage(String.valueOf(createdImageId))); - blockUntilServerActive(serverId); + Server server = getDefaultServerImmediately(); + Image image = getDefaultImageImmediately(server); + client.rebuildServer(server.getId(), new RebuildServerOptions().withImage(String.valueOf(image.getId()))); + blockUntilServerActive(server.getId()); // issue Web Hosting #119580 createdImageId comes back incorrect after rebuild - assertEquals(createdImageId, client.getServer(serverId).getImageRef()); + assertEquals(image.getURI(), client.getServer(server.getId()).getImageRef()); } @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootHard() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - client.rebootServer(serverId, RebootType.HARD); - blockUntilServerActive(serverId); + Server server = getDefaultServerImmediately(); + client.rebootServer(server.getId(), RebootType.HARD); + blockUntilServerActive(server.getId()); } @Test(enabled = true, timeOut = 10 * 60 * 1000) public void testRebootSoft() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - client.rebootServer(serverId, RebootType.SOFT); - blockUntilServerActive(serverId); + Server server = getDefaultServerImmediately(); + client.rebootServer(server.getId(), RebootType.SOFT); + blockUntilServerActive(server.getId()); } @Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft") public void testRevertResize() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); + Server server = getDefaultServerImmediately(); + int serverId = server.getId(); client.resizeServer(serverId, 2); blockUntilServerVerifyResize(serverId); client.revertResizeServer(serverId); @@ -385,7 +374,8 @@ public class NovaClientLiveTest { @Test(enabled = false, timeOut = 10 * 60 * 1000) public void testConfirmResize() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); + Server server = getDefaultServerImmediately(); + int serverId = server.getId(); client.resizeServer(serverId, 2); blockUntilServerVerifyResize(serverId); client.confirmResizeServer(serverId); @@ -395,45 +385,25 @@ public class NovaClientLiveTest { @Test(enabled = true, timeOut = 60000) void deleteServer2() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - if (serverId > 0) { - client.deleteServer(serverId); - waitServerDeleted(serverId); - } - serverId = 0; + Server server = getDefaultServerImmediately(); + int serverId = server.getId(); + client.deleteServer(serverId); + waitServerDeleted(serverId); } @Test(enabled = true, timeOut = 60000) void testDeleteImage() throws Exception { - if (createdImageId <= 0) { - testCreateImage(); - } - if (createdImageId > 0) { - client.deleteImage(createdImageId); - assert client.getImage(createdImageId) == null; - } - //TODO all servers created from the image should be deleted + Image image = getDefaultImageImmediately(getDefaultServerImmediately()); + client.deleteImage(image.getId()); + assert client.getImage(image.getId()) == null; } @Test(enabled = true, timeOut = 60000) void deleteServer1() throws Exception { - if (!isServerExist(serverId)) testCreateServer(); - if (serverId > 0) { - client.deleteServer(serverId); - waitServerDeleted(serverId); - } - serverId = 0; - } - - private boolean isServerExist(int serverId) { - return client.getServer(serverId) != null; - } - - private void waitServerDeleted(int serverId) throws InterruptedException { - while (null != client.getServer(serverId)) { - System.out.println("Await deleted server" + serverId); - Thread.sleep(1000); - } + Server server = getDefaultServerImmediately(); + int serverId = server.getId(); + client.deleteServer(serverId); + waitServerDeleted(serverId); } @Test diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java index 76599ad707..40fddcb043 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java @@ -1,699 +1,704 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.openstack.nova.live; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.inject.Guice; -import com.google.inject.Module; -import org.jclouds.Constants; -import org.jclouds.compute.*; -import org.jclouds.compute.domain.*; -import org.jclouds.compute.options.TemplateOptions; -import org.jclouds.domain.Credentials; -import org.jclouds.domain.Location; -import org.jclouds.domain.LocationScope; -import org.jclouds.http.handlers.BackoffLimitedRetryHandler; -import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; -import org.jclouds.net.IPSocket; -import org.jclouds.openstack.nova.NovaAsyncClient; -import org.jclouds.openstack.nova.NovaClient; -import org.jclouds.predicates.RetryablePredicate; -import org.jclouds.predicates.SocketOpen; -import org.jclouds.rest.AuthorizationException; -import org.jclouds.rest.RestContext; -import org.jclouds.rest.RestContextFactory; -import org.jclouds.scriptbuilder.domain.Statements; -import org.jclouds.ssh.SshClient; -import org.jclouds.ssh.SshException; -import org.jclouds.ssh.jsch.JschSshClient; -import org.jclouds.ssh.jsch.config.JschSshClientModule; -import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeGroups; -import org.testng.annotations.Test; - -import java.io.IOException; -import java.net.URISyntaxException; -import java.util.*; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.not; -import static com.google.common.base.Throwables.getRootCause; -import static com.google.common.collect.Iterables.*; -import static com.google.common.collect.Maps.newLinkedHashMap; -import static com.google.common.collect.Maps.uniqueIndex; -import static com.google.common.collect.Sets.filter; -import static com.google.common.collect.Sets.newTreeSet; -import static org.jclouds.compute.ComputeTestUtils.buildScript; -import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; -import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; -import static org.jclouds.compute.predicates.NodePredicates.*; -import static org.jclouds.compute.predicates.NodePredicates.all; -import static org.jclouds.compute.util.ComputeServiceUtils.getCores; -import static org.jclouds.openstack.nova.live.PropertyHelper.overridePropertyFromSystemProperty; -import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertNotNull; - -/** - * Generally disabled, as it incurs higher fees. - * - * @author Adrian Cole - */ -@Test(groups = "novalive", enabled = true, sequential = true) -public class NovaComputeServiceLiveTest { - - protected String group; - - protected RetryablePredicate socketTester; - protected SortedSet nodes; - protected ComputeServiceContext context; - protected ComputeService computeService; - - - protected Map keyPair; - - protected String provider; - protected String identity; - protected String credential; - protected String endpoint; - protected String apiversion; - - private Properties overrides; - - public NovaComputeServiceLiveTest() { - provider = "nova"; - } - - - protected void setupCredentials(Properties properties) { - identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); - credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider - + ".credential"); - endpoint = properties.getProperty("test." + provider + ".endpoint"); - apiversion = properties.getProperty("test." + provider + ".apiversion"); - } - - protected void updateProperties(final Properties properties) { - properties.setProperty(provider + ".identity", identity); - properties.setProperty(provider + ".credential", credential); - if (endpoint != null) - properties.setProperty(provider + ".endpoint", endpoint); - if (apiversion != null) - properties.setProperty(provider + ".apiversion", apiversion); - } - - - protected Properties setupProperties() throws IOException { - Properties overrides = new Properties(); - overrides.load(this.getClass().getResourceAsStream("/test.properties")); - - overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); - overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); - overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.public"); - overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.private"); - overridePropertyFromSystemProperty(overrides, "test.initializer"); - overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); - overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); - - return overrides; - } - - protected Properties setupRestProperties() { - return RestContextFactory.getPropertiesFromResource("/rest.properties"); - } - - private void initializeContextAndClient(Properties properties) throws IOException { - if (context != null) - context.close(); - context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( - new SLF4JLoggingModule(), getSshModule()), properties); - computeService = context.getComputeService(); - } - - - @BeforeGroups(groups = {"novalive"}) - public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException { - if (group == null) - group = checkNotNull(provider, "provider"); - if (group.indexOf('-') == -1) - group = group + "-"; - Properties properties = setupProperties(); - setupCredentials(properties); - updateProperties(properties); - overrides = properties; - keyPair = setupKeyPair(properties); - initializeContextAndClient(properties); - buildSocketTester(); - } - - protected void buildSocketTester() { - SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); - socketTester = new RetryablePredicate(socketOpen, 60, 1, TimeUnit.SECONDS); - } - - - protected JschSshClientModule getSshModule() { - return new JschSshClientModule(); - } - - @Test - public void testAssignability() throws Exception { - @SuppressWarnings("unused") - RestContext tmContext = new ComputeServiceContextFactory() - .createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides).getProviderSpecificContext(); - } - - - protected void checkNodes(Iterable nodes, String tag) throws IOException { - _checkNodes(nodes, tag); - - for (NodeMetadata node : nodes) { - assertEquals(node.getLocation().getScope(), LocationScope.HOST); - } - } - - protected void _checkNodes(Iterable nodes, String group) throws IOException { - for (NodeMetadata node : nodes) { - assertNotNull(node.getProviderId()); - assertNotNull(node.getGroup()); - assertEquals(node.getGroup(), group); - assertEquals(node.getState(), NodeState.RUNNING); - Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); - assertEquals(fromStore, node.getCredentials()); - assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; -// assertNotNull(node.getCredentials()); -// if (node.getCredentials().identity != null) { -// assertNotNull(node.getCredentials().identity); -// assertNotNull(node.getCredentials().credential); -// doCheckJavaIsInstalledViaSsh(node); -// } - } - } - - - @Test(enabled = true, expectedExceptions = AuthorizationException.class) - public void testCorrectAuthException() throws Exception { - Properties properties = new Properties(); - properties.putAll(overrides); - properties.remove(provider + ".identity"); - ComputeServiceContext context = null; - try { - context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet - .of(new SLF4JLoggingModule()), properties); - context.getComputeService().listNodes(); - } finally { - if (context != null) - context.close(); - } - } - - @Test(enabled = true) - public void testImagesCache() throws Exception { - computeService.listImages(); - long time = System.currentTimeMillis(); - computeService.listImages(); - long duration = System.currentTimeMillis() - time; - assert duration < 1000 : String.format("%dms to get images", duration); - } - - @Test(enabled = true, expectedExceptions = NoSuchElementException.class) - public void testCorrectExceptionRunningNodesNotFound() throws Exception { - computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() - .family(OsFamily.UBUNTU).description("ffoo").build())); - } - - // since surefire and eclipse don't otherwise guarantee the order, we are - // starting this one alphabetically before create2nodes.. - private String awaitForPublicAddressAssigned(String nodeId) throws InterruptedException { - while (true) { - Set addresses = computeService.getNodeMetadata(nodeId).getPublicAddresses(); - System.out.println(addresses); - if (addresses != null) - if (!addresses.isEmpty()) return addresses.iterator().next(); - Thread.sleep(1000); - } - } - - private void awaitForSshPort(String address, Credentials credentials) throws URISyntaxException { - IPSocket socket = new IPSocket(address, 22); - - JschSshClient ssh = new JschSshClient( - new BackoffLimitedRetryHandler(), socket, 10000, credentials.identity, null, credentials.credential.getBytes()); - while (true) { - try { - System.out.println("ping: " + socket); - ssh.connect(); - return; - } catch (SshException ignore) { - } - } - } - - - @Test(enabled = true) - public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { - String group = this.group + "r"; - - computeService.destroyNodesMatching(inGroup(group)); - - Template template = getDefaultTemplateBuilder().options( - computeService.templateOptions() - .overrideCredentialsWith(new Credentials("root", keyPair.get("private"))) - .blockUntilRunning(true)) - .build(); - - try { - Set nodes = computeService.createNodesInGroup(group, 1, template); - - System.out.println("=================================================="); - System.out.println("================ Created ==================="); - - String address = awaitForPublicAddressAssigned(get(nodes, nodes.size() - 1).getId()); - awaitForSshPort(address, new Credentials("root", keyPair.get("private"))); - - OperatingSystem os = get(nodes, 0).getOperatingSystem(); - try { - Map responses = runJavaInstallationScriptWithCreds(group, os, new Credentials( - "root", "romeo")); - assert false : "shouldn't pass with a bad password\n" + responses; - } catch (RunScriptOnNodesException ignore) { - if (!getRootCause(ignore).getMessage().contains("Auth fail")) throw ignore; - } - - System.out.println("=================================================="); - System.out.println("================ Auth failed ==================="); - - for (Map.Entry response : computeService.runScriptOnNodesMatching( - runningInGroup(group), Statements.exec("echo hello"), - overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet()) - assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " - + response.getValue(); - - System.out.println("=================================================="); - System.out.println("================ Script ==================="); - - //TODO runJavaInstallationScriptWithCreds(group, os, new Credentials("root", keyPair.get("private"))); - //no response? if os is null (ZYPPER) - - checkNodes(nodes, group); - - Credentials good = nodes.iterator().next().getCredentials(); - //TODO check good is being private key .overrideCredentialsWith - //TODO test for .blockOnPort - - } finally { - computeService.destroyNodesMatching(inGroup(group)); - } - } - - @Test(enabled = true) - public void testTemplateMatch() throws Exception { - Template template = buildTemplate(getDefaultTemplateBuilder()); - Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build(); - assertEquals(toMatch.getImage(), template.getImage()); - } - -// protected void checkHttpGet(NodeMetadata node) { -// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); -// } - - @Test(enabled = true, dependsOnMethods = "testCompareSizes") - public void testCreateTwoNodesWithRunScript() throws Exception { - try { - computeService.destroyNodesMatching(inGroup(group)); - } catch (NoSuchElementException e) { - - } - - try { - nodes = newTreeSet(computeService.createNodesInGroup(group, 2, getDefaultTemplateBuilder().build())); - } catch (RunNodesException e) { - nodes = newTreeSet(concat(e.getSuccessfulNodes(), e.getNodeErrors().keySet())); - throw e; - } - assertEquals(nodes.size(), 2); - checkNodes(nodes, group); - NodeMetadata node1 = nodes.first(); - NodeMetadata node2 = nodes.last(); - // credentials aren't always the same - // assertEquals(node1.getCredentials(), node2.getCredentials()); - - assertLocationSameOrChild(node1.getLocation(), getDefaultTemplateBuilder().build().getLocation()); - assertLocationSameOrChild(node2.getLocation(), getDefaultTemplateBuilder().build().getLocation()); - checkImageIdMatchesTemplate(node1); - checkImageIdMatchesTemplate(node2); - checkOsMatchesTemplate(node1); - checkOsMatchesTemplate(node2); - } - - protected void checkImageIdMatchesTemplate(NodeMetadata node) { - if (node.getImageId() != null) - assertEquals(node.getImageId(), getDefaultTemplateBuilder().build().getImage().getId()); - } - - protected void checkOsMatchesTemplate(NodeMetadata node) { - if (node.getOperatingSystem() != null) - assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String - .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node - .getOperatingSystem()); - } - - void assertLocationSameOrChild(Location test, Location expected) { - if (!test.equals(expected)) { - assertEquals(test.getParent().getId(), expected.getId()); - } else { - assertEquals(test, expected); - } - } - - @Test(enabled = true) - public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { - testCreateTwoNodesWithRunScript(); - initializeContextAndClient(overrides); - - TreeSet nodes = newTreeSet(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build())); - checkNodes(nodes, group); - NodeMetadata node = nodes.first(); - this.nodes.add(node); - assertEquals(nodes.size(), 1); - assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation()); - checkOsMatchesTemplate(node); - } - - @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") - public void testCredentialsCache() throws Exception { - initializeContextAndClient(overrides); - for (NodeMetadata node : nodes) - assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); - } - - protected Map runJavaInstallationScriptWithCreds(final String group, OperatingSystem os, - Credentials creds) throws RunScriptOnNodesException { - return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) - .nameTask("runJavaInstallationScriptWithCreds")); - - } - - - protected Template buildTemplate(TemplateBuilder templateBuilder) { - return templateBuilder.build(); - } - - @Test(enabled = true, dependsOnMethods = "testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired") - public void testGet() throws Exception { - Map metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService - .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), - new Function() { - - @Override - public String apply(NodeMetadata from) { - return from.getId(); - } - - })); - for (NodeMetadata node : nodes) { - metadataMap.remove(node.getId()); - NodeMetadata metadata = computeService.getNodeMetadata(node.getId()); - assertEquals(metadata.getProviderId(), node.getProviderId()); - assertEquals(metadata.getGroup(), node.getGroup()); - assertLocationSameOrChild(metadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); - checkImageIdMatchesTemplate(metadata); - checkOsMatchesTemplate(metadata); - assert (metadata.getState() == NodeState.RUNNING) : metadata; - // due to DHCP the addresses can actually change in-between runs. - assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size()); - assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size()); - } - assertNodeZero(metadataMap.values()); - } - - protected void assertNodeZero(Collection metadataSet) { - assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", - metadataSet, nodes); - } - - @Test(enabled = true, dependsOnMethods = "testGet") - public void testReboot() throws Exception { - computeService.rebootNodesMatching(inGroup(group));// TODO test - // validation - testGet(); - } - - @Test(enabled = true, dependsOnMethods = "testReboot") - public void testSuspendResume() throws Exception { - computeService.suspendNodesMatching(inGroup(group)); - - Set stoppedNodes = refreshNodes(); - - assert Iterables.all(stoppedNodes, new Predicate() { - - @Override - public boolean apply(NodeMetadata input) { - boolean returnVal = input.getState() == NodeState.SUSPENDED; - if (!returnVal) - System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState()); - return returnVal; - } - - }) : stoppedNodes; - - computeService.resumeNodesMatching(inGroup(group)); - testGet(); - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - public void testListNodes() throws Exception { - for (ComputeMetadata node : computeService.listNodes()) { - assert node.getProviderId() != null; - assert node.getLocation() != null; - assertEquals(node.getType(), ComputeType.NODE); - } - } - - @Test(enabled = true, dependsOnMethods = "testSuspendResume") - public void testGetNodesWithDetails() throws Exception { - for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) { - assert node.getProviderId() != null : node; - assert node.getLocation() != null : node; - assertEquals(node.getType(), ComputeType.NODE); - assert node instanceof NodeMetadata; - NodeMetadata nodeMetadata = (NodeMetadata) node; - assert nodeMetadata.getProviderId() != null : nodeMetadata; - // nullable - // assert nodeMetadata.getImage() != null : node; - // user specified name is not always supported - // assert nodeMetadata.getName() != null : nodeMetadata; - if (nodeMetadata.getState() == NodeState.RUNNING) { - assert nodeMetadata.getPublicAddresses() != null : nodeMetadata; - assert nodeMetadata.getPublicAddresses().size() > 0 || nodeMetadata.getPrivateAddresses().size() > 0 : nodeMetadata; - assertNotNull(nodeMetadata.getPrivateAddresses()); - } - } - } - - @Test(enabled = true, dependsOnMethods = {"testListNodes", "testGetNodesWithDetails"}) - public void testDestroyNodes() { - int toDestroy = refreshNodes().size(); - Set destroyed = computeService.destroyNodesMatching(inGroup(group)); - assertEquals(toDestroy, destroyed.size()); - for (NodeMetadata node : filter(computeService.listNodesDetailsMatching(all()), inGroup(group))) { - assert node.getState() == NodeState.TERMINATED : node; - assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); - } - } - - private Set refreshNodes() { - return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); - } - - @Test(enabled = true) - public void testCreateAndRunAService() throws Exception { - - String group = this.group + "s"; - try { - computeService.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { - - } - - Template template = getDefaultTemplateBuilder().options(blockOnComplete(false).inboundPorts(22, 8080)) - .build(); - - // note this is a dependency on the template resolution -// template.getOptions().runScript( -// RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() -// .getOperatingSystem())); - - try { - NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, template)); - - //checkHttpGet(node); - } finally { - computeService.destroyNodesMatching(inGroup(group)); - } - - } - - @Test(enabled = true) - public void testTemplateOptions() throws Exception { - TemplateOptions options = new TemplateOptions().withMetadata(); - Template t = computeService.templateBuilder().smallest().options(options).build(); - assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; - } - - public void testListImages() throws Exception { - for (Image image : computeService.listImages()) { - assert image.getProviderId() != null : image; - // image.getLocationId() can be null, if it is a location-free image - assertEquals(image.getType(), ComputeType.IMAGE); - } - } - - @Test(groups = {"integration", "live"}) - public void testGetAssignableLocations() throws Exception { - for (Location location : computeService.listAssignableLocations()) { - System.err.printf("location %s%n", location); - assert location.getId() != null : location; - assert location != location.getParent() : location; - assert location.getScope() != null : location; - switch (location.getScope()) { - case PROVIDER: - assertProvider(location); - break; - case REGION: - assertProvider(location.getParent()); - break; - case ZONE: - Location provider = location.getParent().getParent(); - // zone can be a direct descendant of provider - if (provider == null) - provider = location.getParent(); - assertProvider(provider); - break; - case HOST: - Location provider2 = location.getParent().getParent().getParent(); - // zone can be a direct descendant of provider - if (provider2 == null) - provider2 = location.getParent().getParent(); - assertProvider(provider2); - break; - } - } - } - - public void testOptionToNotBlock() throws Exception { - String group = this.group + "block"; - try { - computeService.destroyNodesMatching(inGroup(group)); - } catch (Exception e) { - - } - // no inbound ports - TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); - try { - long time = System.currentTimeMillis(); - Set nodes = computeService.createNodesInGroup(group, 1, options); - NodeMetadata node = getOnlyElement(nodes); - assert node.getState() != NodeState.RUNNING; - long duration = System.currentTimeMillis() - time; - assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; - } finally { - computeService.destroyNodesMatching(inGroup(group)); - } - } - - private void assertProvider(Location provider) { - assertEquals(provider.getScope(), LocationScope.PROVIDER); - assertEquals(provider.getParent(), null); - } - - public void testListSizes() throws Exception { - for (Hardware hardware : computeService.listHardwareProfiles()) { - assert hardware.getProviderId() != null; - assert getCores(hardware) > 0; - assert hardware.getVolumes().size() >= 0; - assert hardware.getRam() > 0; - assertEquals(hardware.getType(), ComputeType.HARDWARE); - } - } - - private TemplateBuilder getDefaultTemplateBuilder() { - return computeService.templateBuilder().imageId("95"); - } - - @Test(enabled = true) - public void testCompareSizes() throws Exception { - TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); - - Hardware defaultSize = templateBuilder.build().getHardware(); - - Hardware smallest = templateBuilder.smallest().build().getHardware(); - Hardware fastest = templateBuilder.fastest().build().getHardware(); - Hardware biggest = templateBuilder.biggest().build().getHardware(); - - System.out.printf("smallest %s%n", smallest); - System.out.printf("fastest %s%n", fastest); - System.out.printf("biggest %s%n", biggest); - - assertEquals(defaultSize, smallest); - - assert getCores(smallest) <= getCores(fastest) : String.format("%d ! <= %d", smallest, fastest); - assert getCores(biggest) <= getCores(fastest) : String.format("%d ! <= %d", biggest, fastest); - - assert biggest.getRam() >= fastest.getRam() : String.format("%d ! >= %d", biggest, fastest); - assert biggest.getRam() >= smallest.getRam() : String.format("%d ! >= %d", biggest, smallest); - - assert getCores(fastest) >= getCores(biggest) : String.format("%d ! >= %d", fastest, biggest); - assert getCores(fastest) >= getCores(smallest) : String.format("%d ! >= %d", fastest, smallest); - } - - - protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { - - SshClient ssh = context.utils().sshForNode().apply(node); - try { - ssh.connect(); - ExecResponse hello = ssh.exec("echo hello"); - assertEquals(hello.getOutput().trim(), "hello"); - ExecResponse exec = ssh.exec("java -version"); - assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" - + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); - } finally { - if (ssh != null) - ssh.disconnect(); - } - } - - @AfterTest - protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException { - if (nodes != null) { - testDestroyNodes(); - } - context.close(); - } -} +/** + * + * Copyright (C) 2010 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.openstack.nova.live; + +import com.google.common.base.Function; +import com.google.common.base.Predicate; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; +import com.google.inject.Guice; +import com.google.inject.Module; +import org.jclouds.Constants; +import org.jclouds.compute.*; +import org.jclouds.compute.domain.*; +import org.jclouds.compute.options.TemplateOptions; +import org.jclouds.domain.Credentials; +import org.jclouds.domain.Location; +import org.jclouds.domain.LocationScope; +import org.jclouds.http.handlers.BackoffLimitedRetryHandler; +import org.jclouds.io.Payload; +import org.jclouds.io.Payloads; +import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; +import org.jclouds.net.IPSocket; +import org.jclouds.openstack.nova.NovaAsyncClient; +import org.jclouds.openstack.nova.NovaClient; +import org.jclouds.predicates.RetryablePredicate; +import org.jclouds.predicates.SocketOpen; +import org.jclouds.rest.AuthorizationException; +import org.jclouds.rest.RestContext; +import org.jclouds.rest.RestContextFactory; +import org.jclouds.scriptbuilder.domain.Statements; +import org.jclouds.ssh.SshClient; +import org.jclouds.ssh.SshException; +import org.jclouds.ssh.jsch.JschSshClient; +import org.jclouds.ssh.jsch.config.JschSshClientModule; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeGroups; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.*; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import static com.google.common.base.Preconditions.checkNotNull; +import static com.google.common.base.Predicates.and; +import static com.google.common.base.Predicates.not; +import static com.google.common.base.Throwables.getRootCause; +import static com.google.common.collect.Iterables.*; +import static com.google.common.collect.Maps.newLinkedHashMap; +import static com.google.common.collect.Maps.uniqueIndex; +import static com.google.common.collect.Sets.filter; +import static com.google.common.collect.Sets.newTreeSet; +import static org.jclouds.compute.ComputeTestUtils.buildScript; +import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; +import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; +import static org.jclouds.compute.predicates.NodePredicates.*; +import static org.jclouds.compute.predicates.NodePredicates.all; +import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.openstack.nova.live.PropertyHelper.overridePropertyFromSystemProperty; +import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; + +/** + * Generally disabled, as it incurs higher fees. + * + * @author Adrian Cole + */ +@Test(groups = "novalive", enabled = true, sequential = true) +public class NovaComputeServiceLiveTest { + + protected String group; + + protected RetryablePredicate socketTester; + protected ComputeServiceContext context; + protected ComputeService computeService; + + + protected Map keyPair; + + protected String provider; + protected String identity; + protected String credential; + protected String endpoint; + protected String apiversion; + + private Properties overrides; + + public NovaComputeServiceLiveTest() { + provider = "nova"; + } + + + protected void setupCredentials(Properties properties) { + identity = checkNotNull(properties.getProperty("test." + provider + ".identity"), "test." + provider + ".identity"); + credential = checkNotNull(properties.getProperty("test." + provider + ".credential"), "test." + provider + + ".credential"); + endpoint = properties.getProperty("test." + provider + ".endpoint"); + apiversion = properties.getProperty("test." + provider + ".apiversion"); + } + + protected void updateProperties(final Properties properties) { + properties.setProperty(provider + ".identity", identity); + properties.setProperty(provider + ".credential", credential); + if (endpoint != null) + properties.setProperty(provider + ".endpoint", endpoint); + if (apiversion != null) + properties.setProperty(provider + ".apiversion", apiversion); + } + + + protected Properties setupProperties() throws IOException { + Properties overrides = new Properties(); + overrides.load(this.getClass().getResourceAsStream("/test.properties")); + + overridePropertyFromSystemProperty(overrides, "test." + provider + ".endpoint"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".apiversion"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".identity"); + overridePropertyFromSystemProperty(overrides, "test." + provider + ".credential"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.public"); + overridePropertyFromSystemProperty(overrides, "test.ssh.keyfile.private"); + overridePropertyFromSystemProperty(overrides, "test.initializer"); + overrides.setProperty(Constants.PROPERTY_TRUST_ALL_CERTS, "true"); + overrides.setProperty(Constants.PROPERTY_RELAX_HOSTNAME, "true"); + + return overrides; + } + + protected Properties setupRestProperties() { + return RestContextFactory.getPropertiesFromResource("/rest.properties"); + } + + private void initializeContextAndClient(Properties properties) throws IOException { + if (context != null) + context.close(); + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, ImmutableSet.of( + new SLF4JLoggingModule(), getSshModule()), properties); + computeService = context.getComputeService(); + } + + + @BeforeTest + public void setupClient() throws InterruptedException, ExecutionException, TimeoutException, IOException { + group = "compute service test group"; + Properties properties = setupProperties(); + setupCredentials(properties); + updateProperties(properties); + overrides = properties; + keyPair = setupKeyPair(properties); + initializeContextAndClient(properties); + buildSocketTester(); + } + + protected void buildSocketTester() { + SocketOpen socketOpen = Guice.createInjector(getSshModule()).getInstance(SocketOpen.class); + socketTester = new RetryablePredicate(socketOpen, 60, 1, TimeUnit.SECONDS); + } + + + protected JschSshClientModule getSshModule() { + return new JschSshClientModule(); + } + + @Test + public void testAssignability() throws Exception { + @SuppressWarnings("unused") + RestContext tmContext = new ComputeServiceContextFactory() + .createContext(provider, identity, credential, Collections.singleton(new JschSshClientModule()), overrides).getProviderSpecificContext(); + } + + + protected void checkNodes(Iterable nodes, String tag) throws IOException { + _checkNodes(nodes, tag); + + for (NodeMetadata node : nodes) { + assertEquals(node.getLocation().getScope(), LocationScope.HOST); + } + } + + protected void _checkNodes(Iterable nodes, String group) throws IOException { + for (NodeMetadata node : nodes) { + assertNotNull(node.getProviderId()); + assertNotNull(node.getGroup()); + assertEquals(node.getGroup(), group); + assertEquals(node.getState(), NodeState.RUNNING); + Credentials fromStore = context.getCredentialStore().get("node#" + node.getId()); + assertEquals(fromStore, node.getCredentials()); + assert node.getPublicAddresses().size() >= 1 || node.getPrivateAddresses().size() >= 1 : "no ips in" + node; +// assertNotNull(node.getCredentials()); +// if (node.getCredentials().identity != null) { +// assertNotNull(node.getCredentials().identity); +// assertNotNull(node.getCredentials().credential); +// doCheckJavaIsInstalledViaSsh(node); +// } + } + } + + + @Test(enabled = true, expectedExceptions = AuthorizationException.class) + public void testCorrectAuthException() throws Exception { + Properties properties = new Properties(); + properties.putAll(overrides); + properties.remove(provider + ".identity"); + ComputeServiceContext context = null; + try { + context = new ComputeServiceContextFactory(setupRestProperties()).createContext(provider, "MOMMA", "MIA", ImmutableSet + .of(new SLF4JLoggingModule()), properties); + context.getComputeService().listNodes(); + } finally { + if (context != null) + context.close(); + } + } + + @Test(enabled = true) + public void testImagesCache() throws Exception { + computeService.listImages(); + long time = System.currentTimeMillis(); + computeService.listImages(); + long duration = System.currentTimeMillis() - time; + assert duration < 1000 : String.format("%dms to get images", duration); + } + + @Test(enabled = true, expectedExceptions = NoSuchElementException.class) + public void testCorrectExceptionRunningNodesNotFound() throws Exception { + computeService.runScriptOnNodesMatching(runningInGroup("zebras-are-awesome"), buildScript(new OperatingSystem.Builder() + .family(OsFamily.UBUNTU).description("ffoo").build())); + } + + // since surefire and eclipse don't otherwise guarantee the order, we are + // starting this one alphabetically before create2nodes.. + private String awaitForPublicAddressAssigned(String nodeId) throws InterruptedException { + while (true) { + Set addresses = computeService.getNodeMetadata(nodeId).getPublicAddresses(); + System.out.println(addresses); + if (addresses != null) + if (!addresses.isEmpty()) return addresses.iterator().next(); + Thread.sleep(1000); + } + } + + private void awaitForSshPort(String address, Credentials credentials) throws URISyntaxException { + IPSocket socket = new IPSocket(address, 22); + + JschSshClient ssh = new JschSshClient( + new BackoffLimitedRetryHandler(), socket, 10000, credentials.identity, null, credentials.credential.getBytes()); + while (true) { + try { + System.out.println("ping: " + socket); + ssh.connect(); + return; + } catch (SshException ignore) { + } + } + } + + + @Test(enabled = true) + public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { + String group = this.group; + + computeService.destroyNodesMatching(inGroup(group)); + + Template template = getDefaultTemplateBuilder().options( + computeService.templateOptions() + .overrideCredentialsWith(new Credentials("root", keyPair.get("private"))) + .blockUntilRunning(true)) + .build(); + + try { + Set nodes = computeService.createNodesInGroup(group, 1, template); + + System.out.println("=================================================="); + System.out.println("================ Created ==================="); + + String address = awaitForPublicAddressAssigned(get(nodes, nodes.size() - 1).getId()); + awaitForSshPort(address, new Credentials("root", keyPair.get("private"))); + + OperatingSystem os = get(nodes, 0).getOperatingSystem(); + try { + Map responses = runJavaInstallationScriptWithCreds(group, os, new Credentials( + "root", "romeo")); + assert false : "shouldn't pass with a bad password\n" + responses; + } catch (RunScriptOnNodesException ignore) { + if (!getRootCause(ignore).getMessage().contains("Auth fail")) throw ignore; + } + + System.out.println("=================================================="); + System.out.println("================ Auth failed ==================="); + + for (Map.Entry response : computeService.runScriptOnNodesMatching( + runningInGroup(group), Statements.exec("echo hello"), + overrideCredentialsWith(new Credentials("root", keyPair.get("private"))).wrapInInitScript(false).runAsRoot(false)).entrySet()) + assert response.getValue().getOutput().trim().equals("hello") : response.getKey() + ": " + + response.getValue(); + + System.out.println("=================================================="); + System.out.println("================ Script ==================="); + + //TODO runJavaInstallationScriptWithCreds(group, os, new Credentials("root", keyPair.get("private"))); + //TODO no response? if os is null (ZYPPER) + + checkNodes(nodes, group); + + Credentials good = nodes.iterator().next().getCredentials(); + //TODO check good is being private key .overrideCredentialsWith + //TODO test for .blockOnPort + + } finally { + computeService.destroyNodesMatching(inGroup(group)); + } + } + + @Test(enabled = true) + public void testTemplateMatch() throws Exception { + Template template = buildTemplate(getDefaultTemplateBuilder()); + Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build(); + assertEquals(toMatch.getImage(), template.getImage()); + } + +// protected void checkHttpGet(NodeMetadata node) { +// ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); +// } + + @Test(enabled = true) + public void testCreateTwoNodesWithRunScript() throws Exception { + computeService.destroyNodesMatching(inGroup(group)); + + SortedSet nodes = newTreeSet(computeService.createNodesInGroup(group, 2, getDefaultTemplateBuilder().build())); + assertEquals(nodes.size(), 2); + checkNodes(nodes, group); + NodeMetadata node1 = nodes.first(); + NodeMetadata node2 = nodes.last(); + // credentials aren't always the same + // assertEquals(node1.getCredentials(), node2.getCredentials()); + + assertLocationSameOrChild(node1.getLocation(), getDefaultTemplateBuilder().build().getLocation()); + assertLocationSameOrChild(node2.getLocation(), getDefaultTemplateBuilder().build().getLocation()); + checkImageIdMatchesTemplate(node1); + checkImageIdMatchesTemplate(node2); +// checkOsMatchesTemplate(node1); +// checkOsMatchesTemplate(node2); + } + + protected void checkImageIdMatchesTemplate(NodeMetadata node) { + if (node.getImageId() != null) + assertEquals(node.getImageId(), getDefaultTemplateBuilder().build().getImage().getId()); + } + +// protected void checkOsMatchesTemplate(NodeMetadata node) { +// if (node.getOperatingSystem() != null) +// assert node.getOperatingSystem().getFamily().equals(getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily()) : String +// .format("expecting family %s but got %s", getDefaultTemplateBuilder().build().getImage().getOperatingSystem().getFamily(), node +// .getOperatingSystem()); +// } + + void assertLocationSameOrChild(Location test, Location expected) { + if (!test.equals(expected)) { + assertEquals(test.getParent().getId(), expected.getId()); + } else { + assertEquals(test, expected); + } + } + + private NodeMetadata createDefaultNode() throws RunNodesException { + return computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build()) + .iterator().next(); + } + + @Test(enabled = true) + public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { + testCreateTwoNodesWithRunScript(); + initializeContextAndClient(overrides); + + TreeSet nodes = newTreeSet(computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build())); + checkNodes(nodes, group); + NodeMetadata node = nodes.first(); + assertEquals(nodes.size(), 1); + assertLocationSameOrChild(node.getLocation(), getDefaultTemplateBuilder().build().getLocation()); +// checkOsMatchesTemplate(node); + } + + @Test(enabled = true) + public void testCredentialsCache() throws Exception { + LinkedList nodes = new LinkedList(); + nodes.add(createDefaultNode()); + initializeContextAndClient(overrides); + nodes.add(createDefaultNode()); + initializeContextAndClient(overrides); + for (NodeMetadata node : nodes) + assert (context.getCredentialStore().get("node#" + node.getId()) != null) : "credentials for " + node.getId(); + } + + protected Map runJavaInstallationScriptWithCreds(final String group, OperatingSystem os, + Credentials creds) throws RunScriptOnNodesException { + return computeService.runScriptOnNodesMatching(runningInGroup(group), buildScript(os), overrideCredentialsWith(creds) + .nameTask("runJavaInstallationScriptWithCreds")); + + } + + + protected Template buildTemplate(TemplateBuilder templateBuilder) { + return templateBuilder.build(); + } + + @Test(enabled = true) + public void testGet() throws Exception { + Set nodes = Sets.newHashSet(createDefaultNode()); + Map metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService + .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), + new Function() { + + @Override + public String apply(NodeMetadata from) { + return from.getId(); + } + + })); + for (NodeMetadata node : nodes) { + metadataMap.remove(node.getId()); + NodeMetadata metadata = computeService.getNodeMetadata(node.getId()); + assertEquals(metadata.getProviderId(), node.getProviderId()); + assertEquals(metadata.getGroup(), node.getGroup()); + assertLocationSameOrChild(metadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); + checkImageIdMatchesTemplate(metadata); +// checkOsMatchesTemplate(metadata); + assert (metadata.getState() == NodeState.RUNNING) : metadata; + // due to DHCP the addresses can actually change in-between runs. + assertEquals(metadata.getPrivateAddresses().size(), node.getPrivateAddresses().size()); + assertEquals(metadata.getPublicAddresses().size(), node.getPublicAddresses().size()); + } + assertNodeZero(metadataMap.values(), nodes); + } + + protected void assertNodeZero(Collection metadataSet, Set nodes) { + assert metadataSet.size() == 0 : String.format("nodes left in set: [%s] which didn't match set: [%s]", + metadataSet, nodes); + } + + @Test(enabled = true) + public void testReboot() throws Exception { + computeService.rebootNodesMatching(inGroup(group));// TODO test + // validation + testGet(); + } + + @Test(enabled = true) + public void testSuspendResume() throws Exception { + computeService.suspendNodesMatching(inGroup(group)); + + Set stoppedNodes = refreshNodes(); + + assert Iterables.all(stoppedNodes, new Predicate() { + + @Override + public boolean apply(NodeMetadata input) { + boolean returnVal = input.getState() == NodeState.SUSPENDED; + if (!returnVal) + System.err.printf("warning: node %s in state %s%n", input.getId(), input.getState()); + return returnVal; + } + + }) : stoppedNodes; + + computeService.resumeNodesMatching(inGroup(group)); + testGet(); + } + + @Test(enabled = true) + public void testListNodes() throws Exception { + for (ComputeMetadata node : computeService.listNodes()) { + assert node.getProviderId() != null; + assert node.getLocation() != null; + assertEquals(node.getType(), ComputeType.NODE); + } + } + + @Test(enabled = true) + public void testGetNodesWithDetails() throws Exception { + for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) { + assert node.getProviderId() != null : node; + assert node.getLocation() != null : node; + assertEquals(node.getType(), ComputeType.NODE); + assert node.getProviderId() != null : node; + // nullable + // assert nodeMetadata.getImage() != null : node; + // user specified name is not always supported + // assert nodeMetadata.getName() != null : nodeMetadata; + if (node.getState() == NodeState.RUNNING) { + assert node.getPublicAddresses() != null : node; + assert node.getPublicAddresses().size() > 0 || node.getPrivateAddresses().size() > 0 : node; + assertNotNull(node.getPrivateAddresses()); + } + } + } + + @Test(enabled = true) + public void testDestroyNodes() { + int toDestroy = refreshNodes().size(); + Set destroyed = computeService.destroyNodesMatching(inGroup(group)); + assertEquals(toDestroy, destroyed.size()); + for (NodeMetadata node : filter(computeService.listNodesDetailsMatching(all()), inGroup(group))) { + assert node.getState() == NodeState.TERMINATED : node; + assertEquals(context.getCredentialStore().get("node#" + node.getId()), null); + } + } + + private Set refreshNodes() { + return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); + } + + @Test(enabled = true) + public void testCreateAndRunAService() throws Exception { + + String group = this.group; + try { + computeService.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + + Template template = getDefaultTemplateBuilder().options(blockOnComplete(false).inboundPorts(22, 8080)) + .build(); + + // note this is a dependency on the template resolution +// template.getOptions().runScript( +// RunScriptData.createScriptInstallAndStartJBoss(keyPair.get("public"), template.getImage() +// .getOperatingSystem())); + + try { + NodeMetadata node = getOnlyElement(computeService.createNodesInGroup(group, 1, template)); + + //checkHttpGet(node); + } finally { + computeService.destroyNodesMatching(inGroup(group)); + } + + } + + @Test(enabled = true) + public void testTemplateOptions() throws Exception { + TemplateOptions options = new TemplateOptions().withMetadata(); + Template t = computeService.templateBuilder().smallest().options(options).build(); + assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; + } + + public void testListImages() throws Exception { + for (Image image : computeService.listImages()) { + assert image.getProviderId() != null : image; + // image.getLocationId() can be null, if it is a location-free image + assertEquals(image.getType(), ComputeType.IMAGE); + } + } + + @Test + public void testGetAssignableLocations() throws Exception { + for (Location location : computeService.listAssignableLocations()) { + System.err.printf("location %s%n", location); + assert location.getId() != null : location; + assert location != location.getParent() : location; + assert location.getScope() != null : location; + switch (location.getScope()) { + case PROVIDER: + assertProvider(location); + break; + case REGION: + assertProvider(location.getParent()); + break; + case ZONE: + Location provider = location.getParent().getParent(); + // zone can be a direct descendant of provider + if (provider == null) + provider = location.getParent(); + assertProvider(provider); + break; + case HOST: + Location provider2 = location.getParent().getParent().getParent(); + // zone can be a direct descendant of provider + if (provider2 == null) + provider2 = location.getParent().getParent(); + assertProvider(provider2); + break; + } + } + } + + public void testOptionToNotBlock() throws Exception { + String group = this.group; + try { + computeService.destroyNodesMatching(inGroup(group)); + } catch (Exception e) { + + } + // no inbound ports + TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); + try { + long time = System.currentTimeMillis(); + Set nodes = computeService.createNodesInGroup(group, 1, options); + NodeMetadata node = getOnlyElement(nodes); + assert node.getState() != NodeState.RUNNING; + long duration = System.currentTimeMillis() - time; + assert duration < 30 * 1000 : "duration longer than 30 seconds!: " + duration / 1000; + } finally { + computeService.destroyNodesMatching(inGroup(group)); + } + } + + private void assertProvider(Location provider) { + assertEquals(provider.getScope(), LocationScope.PROVIDER); + assertEquals(provider.getParent(), null); + } + + public void testListSizes() throws Exception { + for (Hardware hardware : computeService.listHardwareProfiles()) { + assert hardware.getProviderId() != null; + assert getCores(hardware) > 0; + assert hardware.getVolumes().size() >= 0; + assert hardware.getRam() > 0; + assertEquals(hardware.getType(), ComputeType.HARDWARE); + } + } + + private TemplateBuilder getDefaultTemplateBuilder() { + return computeService.templateBuilder().imageId("95").options(getDefaultTemplateOptions()); + } + + private TemplateOptions getDefaultTemplateOptions() { + return TemplateOptions.Builder.installPrivateKey(Payloads.newStringPayload(keyPair.get("private"))); + } + + + + + + @Test(enabled = true) + public void testCompareSizes() throws Exception { + TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); + + Hardware defaultSize = templateBuilder.build().getHardware(); + + Hardware smallest = templateBuilder.smallest().build().getHardware(); + Hardware fastest = templateBuilder.fastest().build().getHardware(); + Hardware biggest = templateBuilder.biggest().build().getHardware(); + + System.out.printf("smallest %s%n", smallest); + System.out.printf("fastest %s%n", fastest); + System.out.printf("biggest %s%n", biggest); + + assertEquals(defaultSize, smallest); + + assert getCores(smallest) <= getCores(fastest); + assert getCores(biggest) <= getCores(fastest); + + assert biggest.getRam() >= fastest.getRam(); + assert biggest.getRam() >= smallest.getRam(); + + assert getCores(fastest) >= getCores(biggest); + assert getCores(fastest) >= getCores(smallest); + } + + + protected void doCheckJavaIsInstalledViaSsh(NodeMetadata node) throws IOException { + + SshClient ssh = context.utils().sshForNode().apply(node); + try { + ssh.connect(); + ExecResponse hello = ssh.exec("echo hello"); + assertEquals(hello.getOutput().trim(), "hello"); + ExecResponse exec = ssh.exec("java -version"); + assert exec.getError().indexOf("1.6") != -1 || exec.getOutput().indexOf("1.6") != -1 : exec + "\n" + + ssh.exec("cat /tmp/bootstrap/stdout.log /tmp/bootstrap/stderr.log"); + } finally { + if (ssh != null) + ssh.disconnect(); + } + } + + @AfterTest + protected void cleanup() throws InterruptedException, ExecutionException, TimeoutException { + testDestroyNodes(); + context.close(); + } +} From 59c4ae8ede991b68128153d1efebc99f1405ca39 Mon Sep 17 00:00:00 2001 From: vicglarson Date: Fri, 22 Apr 2011 20:34:13 +0400 Subject: [PATCH 46/95] Fix after merge --- .../nova/live/NovaClientLiveTest.java | 59 +++---------------- 1 file changed, 7 insertions(+), 52 deletions(-) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java index 5207c3a609..9bb8d42380 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java @@ -36,7 +36,6 @@ import java.util.Set; import static org.jclouds.openstack.nova.options.ListOptions.Builder.withDetails; import static org.testng.Assert.*; -import static org.testng.Assert.assertEquals; /** * Tests behavior of {@code NovaClient} @@ -45,40 +44,10 @@ import static org.testng.Assert.assertEquals; */ // disabled [Web Hosting #129069 @Test(groups = "live", sequential = true) -public class NovaClientLiveTest extends ClientBase{ +public class NovaClientLiveTest extends ClientBase { -<<<<<<< .mine private int testImageId = 95; - protected NovaClient client; - protected SshClient.Factory sshFactory; - private Predicate socketTester; - protected String provider = "nova"; - private String serverPrefix = System.getProperty("user.name") + ".cs"; - protected Map keyPair; - private int serverId; - private String adminPass; - Map metadata = ImmutableMap.of("jclouds", "rackspace"); - private int createdImageId; -=======>>>>>>> .theirs -<<<<<<< .mine - @BeforeTest - public void setupClient() throws IOException { - Properties properties = setupOverrides(setupProperties(this.getClass())); - Injector injector = new RestContextFactory().createContextBuilder(provider, - ImmutableSet.of(new SLF4JLoggingModule(), new JschSshClientModule()), properties) - .buildInjector(); - - client = injector.getInstance(NovaClient.class); - - sshFactory = injector.getInstance(SshClient.Factory.class); - SocketOpen socketOpen = injector.getInstance(SocketOpen.class); - socketTester = new RetryablePredicate(socketOpen, 120, 1, TimeUnit.SECONDS); - injector.injectMembers(socketOpen); // add logger - - keyPair = setupKeyPair(properties); - } - -=======>>>>>>> .theirs @Test + @Test public void testListServers() throws Exception { Set response = client.listServers(); assert null != response; @@ -211,18 +180,10 @@ public class NovaClientLiveTest extends ClientBase{ } - - @Test(enabled = true) public void testCreateServer() throws Exception { -<<<<<<< .mine String imageRef = client.getImage(testImageId).getURI().toASCIIString(); - String flavorRef = client.getFlavor(1).getURI().toASCIIString(); - String serverName = serverPrefix + "createserver" + new SecureRandom().nextInt(); - Server server = client.createServer(serverName, imageRef, flavorRef, withFile("/etc/jclouds.txt", - "rackspace".getBytes()).withMetadata(metadata)); - -======= Server server = getDefaultServerImmediately(); ->>>>>>> .theirs assertNotNull(server.getAdminPass()); + Server server = getDefaultServerImmediately(); + assertNotNull(server.getAdminPass()); assertEquals(server.getStatus(), ServerStatus.BUILD); int serverId = server.getId(); String adminPass = server.getAdminPass(); @@ -273,22 +234,16 @@ public class NovaClientLiveTest extends ClientBase{ assertNotNull(server.getAddresses()); // check metadata assertEquals(server.getMetadata(), metadata); -<<<<<<< .mine - assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId))); -======= assertTrue(server.getImageRef().endsWith(String.valueOf(testImageId))); ->>>>>>> .theirs // listAddresses tests.. + // listAddresses tests.. assertEquals(client.getAddresses(server.getId()), server.getAddresses()); assertEquals(server.getAddresses().getPublicAddresses().size(), 1); assertEquals(client.listPublicAddresses(server.getId()), server.getAddresses().getPublicAddresses()); assertEquals(server.getAddresses().getPrivateAddresses().size(), 1); -<<<<<<< .mine assertEquals(client.listPrivateAddresses(serverId), server.getAddresses().getPrivateAddresses()); - assertPassword(server, adminPass); - assertTrue(server.getFlavorRef().endsWith("1")); -======= assertEquals(client.listPrivateAddresses(server.getId()), server.getAddresses().getPrivateAddresses()); + assertEquals(client.listPrivateAddresses(server.getId()), server.getAddresses().getPrivateAddresses()); assertPassword(server, server.getAdminPass()); assertTrue(server.getFlavorRef().endsWith("1")); ->>>>>>> .theirs assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); + assert server.getProgress() >= 0 : "newDetails.getProgress()" + server.getProgress(); } From a452ca086e4cf0b05100c95c7acaf55ba66cc679 Mon Sep 17 00:00:00 2001 From: Victor Galkin Date: Fri, 22 Apr 2011 23:23:26 +0400 Subject: [PATCH 47/95] Fixes in live tests --- .../ComputeServiceCheck.java} | 7 +- .../NovaComputeServiceLiveTest.java | 79 ++++++++++--------- .../live/{ => novaclient}/ClientBase.java | 2 +- .../DeleteServersInVariousStatesLiveTest.java | 3 +- .../{ => novaclient}/NovaClientLiveTest.java | 4 +- .../ServerCreateLiveTest.java | 2 +- 6 files changed, 52 insertions(+), 45 deletions(-) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ComputeSericeCheck.java => compute/ComputeServiceCheck.java} (94%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ => compute}/NovaComputeServiceLiveTest.java (92%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ => novaclient}/ClientBase.java (95%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ => novaclient}/DeleteServersInVariousStatesLiveTest.java (96%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ => novaclient}/NovaClientLiveTest.java (99%) rename sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/{ => novaclient}/ServerCreateLiveTest.java (99%) diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/ComputeServiceCheck.java similarity index 94% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/ComputeServiceCheck.java index d99854eb36..57a87ce231 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ComputeSericeCheck.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/ComputeServiceCheck.java @@ -1,4 +1,4 @@ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.compute; import com.google.common.collect.ImmutableSet; import org.jclouds.compute.ComputeService; @@ -23,9 +23,10 @@ import static org.jclouds.openstack.nova.live.PropertyHelper.setupProperties; /** * Not intended to be run with maven and does not performs a cleanup after tests + * * @author Dmitri Babaev */ -public class ComputeSericeCheck { +public class ComputeServiceCheck { private ComputeServiceContextFactory contextFactory; private ComputeServiceContext context; @@ -36,7 +37,7 @@ public class ComputeSericeCheck { context = contextFactory.createContext("nova", ImmutableSet.of(new JschSshClientModule(), new SLF4JLoggingModule()), properties); } - + @Test public void testLists() { ComputeService cs = context.getComputeService(); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java similarity index 92% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java index 40fddcb043..b95cc0d8b4 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaComputeServiceLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/compute/NovaComputeServiceLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.compute; import com.google.common.base.Function; import com.google.common.base.Predicate; @@ -34,8 +34,6 @@ import org.jclouds.domain.Credentials; import org.jclouds.domain.Location; import org.jclouds.domain.LocationScope; import org.jclouds.http.handlers.BackoffLimitedRetryHandler; -import org.jclouds.io.Payload; -import org.jclouds.io.Payloads; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.net.IPSocket; import org.jclouds.openstack.nova.NovaAsyncClient; @@ -51,7 +49,6 @@ import org.jclouds.ssh.SshException; import org.jclouds.ssh.jsch.JschSshClient; import org.jclouds.ssh.jsch.config.JschSshClientModule; import org.testng.annotations.AfterTest; -import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -66,7 +63,8 @@ import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.and; import static com.google.common.base.Predicates.not; import static com.google.common.base.Throwables.getRootCause; -import static com.google.common.collect.Iterables.*; +import static com.google.common.collect.Iterables.get; +import static com.google.common.collect.Iterables.getOnlyElement; import static com.google.common.collect.Maps.newLinkedHashMap; import static com.google.common.collect.Maps.uniqueIndex; import static com.google.common.collect.Sets.filter; @@ -75,8 +73,8 @@ import static org.jclouds.compute.ComputeTestUtils.buildScript; import static org.jclouds.compute.options.TemplateOptions.Builder.blockOnComplete; import static org.jclouds.compute.options.TemplateOptions.Builder.overrideCredentialsWith; import static org.jclouds.compute.predicates.NodePredicates.*; -import static org.jclouds.compute.predicates.NodePredicates.all; import static org.jclouds.compute.util.ComputeServiceUtils.getCores; +import static org.jclouds.compute.util.ComputeServiceUtils.parseGroupFromName; import static org.jclouds.openstack.nova.live.PropertyHelper.overridePropertyFromSystemProperty; import static org.jclouds.openstack.nova.live.PropertyHelper.setupKeyPair; import static org.testng.Assert.assertEquals; @@ -233,7 +231,7 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true) + @Test public void testImagesCache() throws Exception { computeService.listImages(); long time = System.currentTimeMillis(); @@ -276,7 +274,7 @@ public class NovaComputeServiceLiveTest { } - @Test(enabled = true) + @Test public void testAScriptExecutionAfterBootWithBasicTemplate() throws Exception { String group = this.group; @@ -332,7 +330,7 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true) + @Test public void testTemplateMatch() throws Exception { Template template = buildTemplate(getDefaultTemplateBuilder()); Template toMatch = computeService.templateBuilder().imageId(template.getImage().getId()).build(); @@ -343,11 +341,12 @@ public class NovaComputeServiceLiveTest { // ComputeTestUtils.checkHttpGet(context.utils().http(), node, 8080); // } - @Test(enabled = true) + @Test public void testCreateTwoNodesWithRunScript() throws Exception { computeService.destroyNodesMatching(inGroup(group)); SortedSet nodes = newTreeSet(computeService.createNodesInGroup(group, 2, getDefaultTemplateBuilder().build())); + awaitForPublicAddressAssigned(nodes.iterator().next().getId()); assertEquals(nodes.size(), 2); checkNodes(nodes, group); NodeMetadata node1 = nodes.first(); @@ -383,12 +382,16 @@ public class NovaComputeServiceLiveTest { } } - private NodeMetadata createDefaultNode() throws RunNodesException { - return computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build()) - .iterator().next(); + private NodeMetadata createDefaultNode(TemplateOptions options) throws RunNodesException { + return computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().options(options).build()) + .iterator().next(); } - @Test(enabled = true) + private NodeMetadata createDefaultNode() throws RunNodesException { + return createDefaultNode(getDefaultTemplateOptions()); + } + + @Test public void testCreateAnotherNodeWithANewContextToEnsureSharedMemIsntRequired() throws Exception { testCreateTwoNodesWithRunScript(); initializeContextAndClient(overrides); @@ -401,7 +404,7 @@ public class NovaComputeServiceLiveTest { // checkOsMatchesTemplate(node); } - @Test(enabled = true) + @Test public void testCredentialsCache() throws Exception { LinkedList nodes = new LinkedList(); nodes.add(createDefaultNode()); @@ -424,8 +427,8 @@ public class NovaComputeServiceLiveTest { return templateBuilder.build(); } - @Test(enabled = true) - public void testGet() throws Exception { + @Test + public void testGetNodeMetadata() throws Exception { Set nodes = Sets.newHashSet(createDefaultNode()); Map metadataMap = newLinkedHashMap(uniqueIndex(filter(computeService .listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))), @@ -440,6 +443,7 @@ public class NovaComputeServiceLiveTest { for (NodeMetadata node : nodes) { metadataMap.remove(node.getId()); NodeMetadata metadata = computeService.getNodeMetadata(node.getId()); + assertEquals(parseGroupFromName(metadata.getName()), group); assertEquals(metadata.getProviderId(), node.getProviderId()); assertEquals(metadata.getGroup(), node.getGroup()); assertLocationSameOrChild(metadata.getLocation(), getDefaultTemplateBuilder().build().getLocation()); @@ -458,15 +462,17 @@ public class NovaComputeServiceLiveTest { metadataSet, nodes); } - @Test(enabled = true) + @Test public void testReboot() throws Exception { + createDefaultNode(); computeService.rebootNodesMatching(inGroup(group));// TODO test // validation - testGet(); + testGetNodeMetadata(); } - @Test(enabled = true) + @Test public void testSuspendResume() throws Exception { + createDefaultNode(); computeService.suspendNodesMatching(inGroup(group)); Set stoppedNodes = refreshNodes(); @@ -484,10 +490,10 @@ public class NovaComputeServiceLiveTest { }) : stoppedNodes; computeService.resumeNodesMatching(inGroup(group)); - testGet(); + testGetNodeMetadata(); } - @Test(enabled = true) + @Test public void testListNodes() throws Exception { for (ComputeMetadata node : computeService.listNodes()) { assert node.getProviderId() != null; @@ -496,7 +502,7 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true) + @Test public void testGetNodesWithDetails() throws Exception { for (NodeMetadata node : computeService.listNodesDetailsMatching(all())) { assert node.getProviderId() != null : node; @@ -506,7 +512,8 @@ public class NovaComputeServiceLiveTest { // nullable // assert nodeMetadata.getImage() != null : node; // user specified name is not always supported - // assert nodeMetadata.getName() != null : nodeMetadata; + // assert nodeMetadata.getName().parseGroupFromName() != null : nodeMetadata; + if (node.getState() == NodeState.RUNNING) { assert node.getPublicAddresses() != null : node; assert node.getPublicAddresses().size() > 0 || node.getPrivateAddresses().size() > 0 : node; @@ -515,7 +522,7 @@ public class NovaComputeServiceLiveTest { } } - @Test(enabled = true) + @Test public void testDestroyNodes() { int toDestroy = refreshNodes().size(); Set destroyed = computeService.destroyNodesMatching(inGroup(group)); @@ -530,7 +537,7 @@ public class NovaComputeServiceLiveTest { return filter(computeService.listNodesDetailsMatching(all()), and(inGroup(group), not(TERMINATED))); } - @Test(enabled = true) + @Test public void testCreateAndRunAService() throws Exception { String group = this.group; @@ -558,10 +565,10 @@ public class NovaComputeServiceLiveTest { } - @Test(enabled = true) + @Test public void testTemplateOptions() throws Exception { TemplateOptions options = new TemplateOptions().withMetadata(); - Template t = computeService.templateBuilder().smallest().options(options).build(); + Template t = getDefaultTemplateBuilder().smallest().options(options).build(); assert t.getOptions().isIncludeMetadata() : "The metadata option should be 'true' " + "for the created template"; } @@ -612,11 +619,11 @@ public class NovaComputeServiceLiveTest { } catch (Exception e) { } - // no inbound ports - TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); + //TODO no inbound ports + //TemplateOptions options = computeService.templateOptions().blockUntilRunning(false).inboundPorts(); try { long time = System.currentTimeMillis(); - Set nodes = computeService.createNodesInGroup(group, 1, options); + Set nodes = computeService.createNodesInGroup(group, 1, getDefaultTemplateBuilder().build()); NodeMetadata node = getOnlyElement(nodes); assert node.getState() != NodeState.RUNNING; long duration = System.currentTimeMillis() - time; @@ -631,7 +638,7 @@ public class NovaComputeServiceLiveTest { assertEquals(provider.getParent(), null); } - public void testListSizes() throws Exception { + public void testListHardwareProfiles() throws Exception { for (Hardware hardware : computeService.listHardwareProfiles()) { assert hardware.getProviderId() != null; assert getCores(hardware) > 0; @@ -646,14 +653,12 @@ public class NovaComputeServiceLiveTest { } private TemplateOptions getDefaultTemplateOptions() { - return TemplateOptions.Builder.installPrivateKey(Payloads.newStringPayload(keyPair.get("private"))); + return TemplateOptions.Builder.blockUntilRunning(false); + //.installPrivateKey(Payloads.newStringPayload(keyPair.get("private"))); } - - - - @Test(enabled = true) + @Test public void testCompareSizes() throws Exception { TemplateBuilder templateBuilder = getDefaultTemplateBuilder(); diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ClientBase.java similarity index 95% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ClientBase.java index 77a9fc3fea..50dd54931f 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ClientBase.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ClientBase.java @@ -1,4 +1,4 @@ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.novaclient; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/DeleteServersInVariousStatesLiveTest.java similarity index 96% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/DeleteServersInVariousStatesLiveTest.java index 280688e794..0ffa338d22 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/DeleteServersInVariousStatesLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/DeleteServersInVariousStatesLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.novaclient; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; @@ -29,7 +29,6 @@ import org.jclouds.ssh.SshClient; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; -import java.security.SecureRandom; import java.util.Map; /** diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java similarity index 99% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java index 9bb8d42380..5fdfd68221 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/NovaClientLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/NovaClientLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.novaclient; import com.google.common.collect.Iterables; import org.jclouds.domain.Credentials; @@ -307,6 +307,7 @@ public class NovaClientLiveTest extends ClientBase { Server server = getDefaultServerImmediately(); client.rebootServer(server.getId(), RebootType.HARD); blockUntilServerActive(server.getId()); + //TODO check } @Test(enabled = true, timeOut = 10 * 60 * 1000) @@ -314,6 +315,7 @@ public class NovaClientLiveTest extends ClientBase { Server server = getDefaultServerImmediately(); client.rebootServer(server.getId(), RebootType.SOFT); blockUntilServerActive(server.getId()); + //TODO check } @Test(enabled = false, timeOut = 60000, dependsOnMethods = "testRebootSoft") diff --git a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ServerCreateLiveTest.java similarity index 99% rename from sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java rename to sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ServerCreateLiveTest.java index 8e672b1087..30a9ba7b06 100644 --- a/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/ServerCreateLiveTest.java +++ b/sandbox-apis/nova/src/test/java/org/jclouds/openstack/nova/live/novaclient/ServerCreateLiveTest.java @@ -17,7 +17,7 @@ * ==================================================================== */ -package org.jclouds.openstack.nova.live; +package org.jclouds.openstack.nova.live.novaclient; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableMap; From f0629cd72639586c53688923ac862508157949ef Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Sat, 23 Apr 2011 17:21:08 +0100 Subject: [PATCH 48/95] Merge branch 'master', remote branch 'origin' From 10aec3b6038b14b589355c2dc54de3be929620ef Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Sat, 23 Apr 2011 17:21:26 +0100 Subject: [PATCH 49/95] Changed project description to match extension -> driver change --- drivers/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/drivers/pom.xml b/drivers/pom.xml index 977babb3a0..a624a8ceb6 100644 --- a/drivers/pom.xml +++ b/drivers/pom.xml @@ -30,7 +30,7 @@ jclouds-drivers-project pom - jclouds extensions project + jclouds drivers project gae apachehc From 4bcc6a753bb42e185e37d1676b1f435dcca1cd9b Mon Sep 17 00:00:00 2001 From: Andrew Phillips Date: Sat, 23 Apr 2011 18:33:38 +0100 Subject: [PATCH 50/95] Changed Maven site URL to the jclouds Google Code site. Also using a fork of the WebDAV wagon to work around http://code.google.com/p/support/issues/detail?id=4786 --- project/pom.xml | 40 +++++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/project/pom.xml b/project/pom.xml index 3892467151..3a659cdbcc 100644 --- a/project/pom.xml +++ b/project/pom.xml @@ -100,9 +100,8 @@ https://oss.sonatype.org/content/repositories/snapshots - website - website - file://${basedir}/target/dist/site/jclouds-testing/ + jclouds-googlecode-site + dav+https://jclouds.googlecode.com/svn/maven-sites/${project.version} @@ -501,7 +500,17 @@ pageTracker._trackPageview(); maven-site-plugin - 2.2 + + ${project.distributionManagement.site.id} + ${project.distributionManagement.site.url} + + + + org.apache.maven.wagon + wagon-webdav-jackrabbit + 1.0-beta-8-WAGON-319 + + maven-deploy-plugin @@ -681,6 +690,16 @@ pageTracker._trackPageview(); ${basedir} + + + + + maven-site-plugin + 2.2 + + + + @@ -766,19 +785,6 @@ pageTracker._trackPageview(); - - - maven-site-plugin - - - attach-descriptor - - attach-descriptor - - - - - From 4e114e9b2b4a9cf91d18ac0c5fd18f36a2602ef8 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 23 Apr 2011 11:45:10 -0700 Subject: [PATCH 51/95] Issue 537: changed to bounded thread pool executor --- core/src/test/java/org/jclouds/PerformanceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/src/test/java/org/jclouds/PerformanceTest.java b/core/src/test/java/org/jclouds/PerformanceTest.java index 067a7a4256..f9e8c506cf 100644 --- a/core/src/test/java/org/jclouds/PerformanceTest.java +++ b/core/src/test/java/org/jclouds/PerformanceTest.java @@ -25,8 +25,8 @@ import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; +import org.jclouds.concurrent.DynamicExecutors; import org.jclouds.date.DateService; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; @@ -44,7 +44,7 @@ public abstract class PerformanceTest { @BeforeTest public void setupExecutorService() { - exec = Executors.newCachedThreadPool(); + exec = DynamicExecutors.newScalingThreadPool(1, THREAD_COUNT, 1000); } @AfterTest From 5752cf5426679b9f55101cbe2ad615795afea366 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 23 Apr 2011 11:45:32 -0700 Subject: [PATCH 52/95] loosened up thresholds on syncproxytest --- .../concurrent/internal/SyncProxyTest.java | 27 +++++++++---------- 1 file changed, 13 insertions(+), 14 deletions(-) diff --git a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java index c8771ab749..2e1f68171c 100644 --- a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java +++ b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java @@ -46,15 +46,15 @@ import com.google.inject.Provides; * * @author Adrian Cole */ -@Test(groups = "unit", sequential = true) +@Test(groups = "unit", singleThreaded = true) public class SyncProxyTest { @Test void testConvertNanos() { - assertEquals(SyncProxy.convertToNanos(Sync.class.getAnnotation(Timeout.class)), 30000000); + assertEquals(SyncProxy.convertToNanos(Sync.class.getAnnotation(Timeout.class)), 40000000); } - @Timeout(duration = 30, timeUnit = TimeUnit.MILLISECONDS) + @Timeout(duration = 40, timeUnit = TimeUnit.MILLISECONDS) private static interface Sync { String getString(); @@ -69,10 +69,10 @@ public class SyncProxyTest { String take20Milliseconds(); - String take100MillisecondsAndTimeout(); + String take200MillisecondsAndTimeout(); @Timeout(duration = 300, timeUnit = TimeUnit.MILLISECONDS) - String take100MillisecondsAndOverride(); + String take200MillisecondsAndOverride(); } @@ -137,12 +137,12 @@ public class SyncProxyTest { }), executorService); } - public ListenableFuture take100MillisecondsAndTimeout() { + public ListenableFuture take200MillisecondsAndTimeout() { return Futures.makeListenable(executorService.submit(new Callable() { public String call() { try { - Thread.sleep(100); + Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } @@ -152,8 +152,8 @@ public class SyncProxyTest { }), executorService); } - public ListenableFuture take100MillisecondsAndOverride() { - return take100MillisecondsAndTimeout(); + public ListenableFuture take200MillisecondsAndOverride() { + return take200MillisecondsAndTimeout(); } } @@ -184,14 +184,13 @@ public class SyncProxyTest { } @Test(expectedExceptions = RuntimeException.class) - public void testTake100MillisecondsAndTimeout() { - assertEquals(sync.take100MillisecondsAndTimeout(), "foo"); - + public void testTake200MillisecondsAndTimeout() { + assertEquals(sync.take200MillisecondsAndTimeout(), "foo"); } @Test - public void testTake100MillisecondsAndOverride() { - assertEquals(sync.take100MillisecondsAndOverride(), "foo"); + public void testTake200MillisecondsAndOverride() { + assertEquals(sync.take200MillisecondsAndOverride(), "foo"); } @Test From b37e00fffe3720569dfe45806b075d5591e23f75 Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sat, 23 Apr 2011 16:56:09 -0700 Subject: [PATCH 53/95] Issue 538: removed redundant http tests which are not working due to test classpath issues --- .../EnterpriseConfigurationModuleTest.java | 51 ------------------ .../enterprise/src/test/resources/test.jks | Bin 1365 -> 0 bytes 2 files changed, 51 deletions(-) delete mode 100644 drivers/enterprise/src/test/java/org/jclouds/enterprise/config/EnterpriseConfigurationModuleTest.java delete mode 100644 drivers/enterprise/src/test/resources/test.jks diff --git a/drivers/enterprise/src/test/java/org/jclouds/enterprise/config/EnterpriseConfigurationModuleTest.java b/drivers/enterprise/src/test/java/org/jclouds/enterprise/config/EnterpriseConfigurationModuleTest.java deleted file mode 100644 index 9711a76aa5..0000000000 --- a/drivers/enterprise/src/test/java/org/jclouds/enterprise/config/EnterpriseConfigurationModuleTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * - * Copyright (C) 2011 Cloud Conscious, LLC. - * - * ==================================================================== - * 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.enterprise.config; - -import static org.jclouds.Constants.PROPERTY_IO_WORKER_THREADS; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_CONTEXT; -import static org.jclouds.Constants.PROPERTY_MAX_CONNECTIONS_PER_HOST; -import static org.jclouds.Constants.PROPERTY_USER_THREADS; - -import java.util.Properties; - -import org.jclouds.http.BaseHttpCommandExecutorServiceIntegrationTest; - -import com.google.inject.Module; - -/** - * Tests the functionality of the {@link EnterpriseConfigurationModule} - * - * @author Adrian Cole - */ -public class EnterpriseConfigurationModuleTest extends BaseHttpCommandExecutorServiceIntegrationTest { - - protected Module createConnectionModule() { - return new EnterpriseConfigurationModule(); - } - - protected void addConnectionProperties(Properties props) { - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_CONTEXT, 50 + ""); - props.setProperty(PROPERTY_MAX_CONNECTIONS_PER_HOST, 50 + ""); - // IO workers not used in this executor - props.setProperty(PROPERTY_IO_WORKER_THREADS, 0 + ""); - props.setProperty(PROPERTY_USER_THREADS, 5 + ""); - } - -} \ No newline at end of file diff --git a/drivers/enterprise/src/test/resources/test.jks b/drivers/enterprise/src/test/resources/test.jks deleted file mode 100644 index e641fb5470345f3ca35830613ed9b69262d216ab..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 1365 zcmezO_TO6u1_mY|W&~sQtmK^h(v)H#U+ewrt4%<;T?S1|+YI>FxU|_ASs1mL1Q{7w z8CaT_7X4Ljus&bM7w`G3R_(3u29fEzncQv)@!bD*c;iN|OyTaCv^yWbc>Mtj+(M{S-Vu20q*N)zqn_q`-X2 z8hMY*DUKKKZLNRXqHy-o*+{QNUpNXEurK%ZdFeV;*;k{=(Y{epu43Yo>AdUzt`Yk? zXWzDY78{gIO1x&Us2P_5b0D|`Qf~~ z56`1Z+rKVJQfT4&_ObWmKFt{p2U|5~->!Pel3)0dTXjiMN}|#;Cl)piCOP2dj)x3phObz8#Z{0-6N8|8mZvNl!Z;0Jv1*nFTXqw zCc=Rs!j2)rg(1R?A;Jt7F_07IH8e1=G_Wu*H8nRei2`zs3@nT+p*%u-MYn|K*vQGYLixsM| z56?Rk;-2c;(0P8(SLZqLiyj1Nsm3XYJUO*wd&7(w)4sUeYm}a1$i&RZz=-TTU}P}^ z-6ayRd0+pHZ##sz^PHWVg{8N?YfD*p@=y6r^9{%Ex+Dc~UUQ0zvukGjy7Sfd#6#iI zw?k@n)x4ERs&1;<{#*P+>;39$0aNG2@=iMNX5GbaetBlU`EGu-Haf&mV=2AJ;OAY9 zE;II>@59yw-#@nW_=iOu3#_hod~mte^}Wok#o Date: Sat, 23 Apr 2011 16:56:34 -0700 Subject: [PATCH 54/95] added more tests to Throwables --- .../org/jclouds/concurrent/internal/SyncProxyTest.java | 2 ++ core/src/test/java/org/jclouds/util/Throwables2Test.java | 7 +++++++ 2 files changed, 9 insertions(+) diff --git a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java index 2e1f68171c..ebdefbc122 100644 --- a/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java +++ b/core/src/test/java/org/jclouds/concurrent/internal/SyncProxyTest.java @@ -164,6 +164,8 @@ public class SyncProxyTest { public void setUp() throws IllegalArgumentException, SecurityException, NoSuchMethodException { sync = SyncProxy.proxy(Sync.class, new SyncProxy(Sync.class, new Async(), new ConcurrentHashMap(), ImmutableMap., Class> of())); + // just to warm up + sync.string(); } @Test diff --git a/core/src/test/java/org/jclouds/util/Throwables2Test.java b/core/src/test/java/org/jclouds/util/Throwables2Test.java index 8e06f6ec03..4acd527ae2 100644 --- a/core/src/test/java/org/jclouds/util/Throwables2Test.java +++ b/core/src/test/java/org/jclouds/util/Throwables2Test.java @@ -24,6 +24,8 @@ import static org.jclouds.util.Throwables2.getFirstThrowableOfType; import static org.jclouds.util.Throwables2.returnFirstExceptionIfInListOrThrowStandardExceptionOrCause; import static org.testng.Assert.assertEquals; +import java.io.IOException; +import java.net.SocketException; import java.util.concurrent.TimeoutException; import org.jclouds.http.HttpCommand; @@ -51,6 +53,11 @@ public class Throwables2Test { assertEquals(getFirstThrowableOfType(pex, AuthorizationException.class), aex); } + public void testGetFirstThrowableOfTypeSubclass() { + SocketException aex = createMock(SocketException.class); + assertEquals(getFirstThrowableOfType(aex, IOException.class), aex); + } + public void testGetFirstThrowableOfTypeOuter() { AuthorizationException aex = createMock(AuthorizationException.class); assertEquals(getFirstThrowableOfType(aex, AuthorizationException.class), aex); From bd5da6104d270ed6a9fafc36bcfe6f2ef2f1e10c Mon Sep 17 00:00:00 2001 From: Adrian Cole Date: Sun, 24 Apr 2011 01:02:20 -0700 Subject: [PATCH 55/95] added account features to cloudstack --- .../cloudstack/CloudStackAsyncClient.java | 7 + .../jclouds/cloudstack/CloudStackClient.java | 7 + .../config/CloudStackRestClientModule.java | 105 +++ .../jclouds/cloudstack/domain/Account.java | 643 ++++++++++++++++++ .../jclouds/cloudstack/domain/Template.java | 18 - .../org/jclouds/cloudstack/domain/User.java | 336 +++++++++ .../features/AccountAsyncClient.java | 71 ++ .../cloudstack/features/AccountClient.java | 54 ++ .../options/ListAccountsOptions.java | 153 +++++ .../cloudstack/predicates/UserPredicates.java | 82 +++ .../cloudstack/CloudStackAsyncClientTest.java | 14 +- .../cloudstack/CloudStackClientLiveTest.java | 2 +- .../features/AccountAsyncClientTest.java | 101 +++ .../features/AccountClientLiveTest.java | 84 +++ .../features/AddressClientLiveTest.java | 5 +- .../features/AsyncJobClientLiveTest.java | 2 +- .../BaseCloudStackClientLiveTest.java | 15 +- .../features/ConfigurationClientLiveTest.java | 2 +- .../features/FirewallClientLiveTest.java | 2 +- .../features/GuestOSClientLiveTest.java | 2 +- .../features/HypervisorClientLiveTest.java | 2 +- .../features/LoadBalancerClientLiveTest.java | 2 +- .../features/NATClientLiveTest.java | 2 +- .../features/NetworkClientLiveTest.java | 2 +- .../features/OfferingClientLiveTest.java | 2 +- .../features/SecurityGroupClientLiveTest.java | 4 +- .../features/TemplateClientLiveTest.java | 2 +- .../VirtualMachineClientLiveTest.java | 34 +- .../features/ZoneClientLiveTest.java | 2 +- .../options/ListAccountsOptionsTest.java | 112 +++ 30 files changed, 1807 insertions(+), 62 deletions(-) create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Account.java create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/User.java create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/AccountAsyncClient.java create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/features/AccountClient.java create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/options/ListAccountsOptions.java create mode 100644 sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/predicates/UserPredicates.java create mode 100644 sandbox-apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AccountAsyncClientTest.java create mode 100644 sandbox-apis/cloudstack/src/test/java/org/jclouds/cloudstack/features/AccountClientLiveTest.java create mode 100644 sandbox-apis/cloudstack/src/test/java/org/jclouds/cloudstack/options/ListAccountsOptionsTest.java diff --git a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackAsyncClient.java b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackAsyncClient.java index 8c37b6a3e6..efd5c11d28 100644 --- a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackAsyncClient.java +++ b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackAsyncClient.java @@ -18,6 +18,7 @@ */ package org.jclouds.cloudstack; +import org.jclouds.cloudstack.features.AccountAsyncClient; import org.jclouds.cloudstack.features.AddressAsyncClient; import org.jclouds.cloudstack.features.AsyncJobAsyncClient; import org.jclouds.cloudstack.features.ConfigurationAsyncClient; @@ -127,4 +128,10 @@ public interface CloudStackAsyncClient { */ @Delegate ConfigurationAsyncClient getConfigurationClient(); + + /** + * Provides asynchronous access to Account features. + */ + @Delegate + AccountAsyncClient getAccountClient(); } diff --git a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackClient.java b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackClient.java index 6d6e91fefa..51fe909a5e 100644 --- a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackClient.java +++ b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/CloudStackClient.java @@ -20,6 +20,7 @@ package org.jclouds.cloudstack; import java.util.concurrent.TimeUnit; +import org.jclouds.cloudstack.features.AccountClient; import org.jclouds.cloudstack.features.AddressClient; import org.jclouds.cloudstack.features.AsyncJobClient; import org.jclouds.cloudstack.features.ConfigurationClient; @@ -130,4 +131,10 @@ public interface CloudStackClient { */ @Delegate ConfigurationClient getConfigurationClient(); + + /** + * Provides synchronous access to Account features. + */ + @Delegate + AccountClient getAccountClient(); } diff --git a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java index 33f7d30657..1d0f993691 100644 --- a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java +++ b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/config/CloudStackRestClientModule.java @@ -18,10 +18,19 @@ */ package org.jclouds.cloudstack.config; +import java.lang.reflect.Type; import java.util.Map; +import java.util.Set; + +import javax.inject.Singleton; import org.jclouds.cloudstack.CloudStackAsyncClient; import org.jclouds.cloudstack.CloudStackClient; +import org.jclouds.cloudstack.domain.Account; +import org.jclouds.cloudstack.domain.User; +import org.jclouds.cloudstack.domain.Account.State; +import org.jclouds.cloudstack.features.AccountAsyncClient; +import org.jclouds.cloudstack.features.AccountClient; import org.jclouds.cloudstack.features.AddressAsyncClient; import org.jclouds.cloudstack.features.AddressClient; import org.jclouds.cloudstack.features.AsyncJobAsyncClient; @@ -64,6 +73,14 @@ import org.jclouds.rest.ConfiguresRestClient; import org.jclouds.rest.config.RestClientModule; import com.google.common.collect.ImmutableMap; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonParseException; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.annotations.SerializedName; +import com.google.inject.TypeLiteral; /** * Configures the cloudstack connection. @@ -89,12 +106,98 @@ public class CloudStackRestClientModule extends RestClientModule, JsonDeserializer { + + public JsonElement serialize(Account src, Type typeOfSrc, JsonSerializationContext context) { + return context.serialize(src); + } + + public Account deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) + throws JsonParseException { + return apply(context. deserialize(json, AccountInternal.class)); + } + + public Account apply(AccountInternal in) { + return Account.builder().id(in.id).type(in.type).domain(in.domain).domainId(in.domainId).IPsAvailable( + nullIfUnlimited(in.IPsAvailable)).IPLimit(nullIfUnlimited(in.IPLimit)).IPs(in.IPs).cleanupRequired( + in.cleanupRequired).name(in.name).receivedBytes(in.receivedBytes).sentBytes(in.sentBytes) + .snapshotsAvailable(nullIfUnlimited(in.snapshotsAvailable)).snapshotLimit( + nullIfUnlimited(in.snapshotLimit)).snapshots(in.snapshots).state(in.state) + .templatesAvailable(nullIfUnlimited(in.templatesAvailable)).templateLimit( + nullIfUnlimited(in.templateLimit)).templates(in.templates).VMsAvailable( + nullIfUnlimited(in.VMsAvailable)).VMLimit(nullIfUnlimited(in.VMLimit)).VMsRunning( + in.VMsRunning).VMsStopped(in.VMsStopped).VMs(in.VMs).volumesAvailable( + nullIfUnlimited(in.volumesAvailable)).volumeLimit(nullIfUnlimited(in.volumeLimit)).volumes( + in.volumes).users(in.users).build(); + } + + static final class AccountInternal { + private long id; + @SerializedName("accounttype") + private Account.Type type; + private String domain; + @SerializedName("domainid") + private long domainId; + @SerializedName("ipavailable") + private String IPsAvailable; + @SerializedName("iplimit") + private String IPLimit; + @SerializedName("iptotal") + private long IPs; + @SerializedName("iscleanuprequired") + private boolean cleanupRequired; + private String name; + @SerializedName("receivedbytes") + private long receivedBytes; + @SerializedName("sentBytes") + private long sentBytes; + @SerializedName("snapshotavailable") + private String snapshotsAvailable; + @SerializedName("snapshotlimit") + private String snapshotLimit; + @SerializedName("snapshottotal") + private long snapshots; + @SerializedName("state") + private State state; + @SerializedName("templateavailable") + private String templatesAvailable; + @SerializedName("templatelimit") + private String templateLimit; + @SerializedName("templatetotal") + private long templates; + @SerializedName("vmavailable") + private String VMsAvailable; + @SerializedName("vmlimit") + private String VMLimit; + @SerializedName("vmrunning") + private long VMsRunning; + @SerializedName("vmstopped") + private long VMsStopped; + @SerializedName("vmtotal") + private long VMs; + @SerializedName("volumeavailable") + private String volumesAvailable; + @SerializedName("volumelimit") + private String volumeLimit; + @SerializedName("volumetotal") + private long volumes; + @SerializedName("user") + private Set users; + } + + private static Long nullIfUnlimited(String in) { + return in == null || "Unlimited".equals(in) ? null : new Long(in); + } + } + @Override protected void configure() { bind(DateAdapter.class).to(Iso8601DateAdapter.class); @@ -106,6 +209,8 @@ public class CloudStackRestClientModule extends RestClientModule>() { + }).toInstance(ImmutableMap. of(Account.class, new BreakGenericSetAdapter())); super.configure(); } diff --git a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Account.java b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Account.java new file mode 100644 index 0000000000..5e3ab1aa29 --- /dev/null +++ b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Account.java @@ -0,0 +1,643 @@ +/** + * + * Copyright (C) 2011 Cloud Conscious, LLC. + * + * ==================================================================== + * 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.cloudstack.domain; + +import static com.google.common.base.Preconditions.checkNotNull; + +import java.util.Map; +import java.util.Set; + +import javax.annotation.Nullable; + +import com.google.common.base.CaseFormat; +import com.google.common.base.Function; +import com.google.common.collect.ForwardingSet; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Maps; + +/** + * + * @author Adrian Cole + */ +public class Account extends ForwardingSet implements Comparable { + + public static Builder builder() { + return new Builder(); + } + + public static class Builder { + private long id; + private Type type; + private String domain; + private long domainId; + private Long IPsAvailable; + private Long IPLimit; + private long IPs; + private boolean cleanupRequired; + private String name; + private long receivedBytes; + private long sentBytes; + private Long snapshotsAvailable; + private Long snapshotLimit; + private long snapshots; + private State state; + private Long templatesAvailable; + private Long templateLimit; + private long templates; + private Long VMsAvailable; + private Long VMLimit; + private long VMsRunning; + private long VMsStopped; + private long VMs; + private Long volumesAvailable; + private Long volumeLimit; + private long volumes; + private Set users = ImmutableSet.of(); + + public Builder id(long id) { + this.id = id; + return this; + } + + public Builder type(Type type) { + this.type = type; + return this; + } + + public Builder domain(String domain) { + this.domain = domain; + return this; + } + + public Builder domainId(long domainId) { + this.domainId = domainId; + return this; + } + + public Builder IPsAvailable(Long IPsAvailable) { + this.IPsAvailable = IPsAvailable; + return this; + } + + public Builder IPLimit(Long IPLimit) { + this.IPLimit = IPLimit; + return this; + } + + public Builder IPs(long IPs) { + this.IPs = IPs; + return this; + } + + public Builder cleanupRequired(boolean cleanupRequired) { + this.cleanupRequired = cleanupRequired; + return this; + } + + public Builder name(String name) { + this.name = name; + return this; + } + + public Builder receivedBytes(long receivedBytes) { + this.receivedBytes = receivedBytes; + return this; + } + + public Builder sentBytes(long sentBytes) { + this.sentBytes = sentBytes; + return this; + } + + public Builder snapshotsAvailable(Long snapshotsAvailable) { + this.snapshotsAvailable = snapshotsAvailable; + return this; + } + + public Builder snapshotLimit(Long snapshotLimit) { + this.snapshotLimit = snapshotLimit; + return this; + } + + public Builder snapshots(long snapshots) { + this.snapshots = snapshots; + return this; + } + + public Builder state(State state) { + this.state = state; + return this; + } + + public Builder templatesAvailable(Long templatesAvailable) { + this.templatesAvailable = templatesAvailable; + return this; + } + + public Builder templateLimit(Long templateLimit) { + this.templateLimit = templateLimit; + return this; + } + + public Builder templates(long templates) { + this.templates = templates; + return this; + } + + public Builder VMsAvailable(Long VMsAvailable) { + this.VMsAvailable = VMsAvailable; + return this; + } + + public Builder VMLimit(Long VMLimit) { + this.VMLimit = VMLimit; + return this; + } + + public Builder VMsRunning(long VMsRunning) { + this.VMsRunning = VMsRunning; + return this; + } + + public Builder VMsStopped(long VMsStopped) { + this.VMsStopped = VMsStopped; + return this; + } + + public Builder VMs(long VMs) { + this.VMs = VMs; + return this; + } + + public Builder volumesAvailable(Long volumesAvailable) { + this.volumesAvailable = volumesAvailable; + return this; + } + + public Builder volumeLimit(Long volumeLimit) { + this.volumeLimit = volumeLimit; + return this; + } + + public Builder volumes(long volumes) { + this.volumes = volumes; + return this; + } + + public Builder users(Set users) { + this.users = ImmutableSet.copyOf(checkNotNull(users, "users")); + return this; + } + + public Account build() { + return new Account(id, type, domain, domainId, IPsAvailable, IPLimit, IPs, cleanupRequired, name, + receivedBytes, sentBytes, snapshotsAvailable, snapshotLimit, snapshots, state, templatesAvailable, + templateLimit, templates, VMsAvailable, VMLimit, VMsRunning, VMsStopped, VMs, volumesAvailable, + volumeLimit, volumes, users); + } + + } + + public static enum State { + ENABLED, DISABLED, LOCKED, UNRECOGNIZED; + @Override + public String toString() { + return CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_HYPHEN, name()); + } + + public static State fromValue(String state) { + try { + return valueOf(CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_UNDERSCORE, checkNotNull(state, "state"))); + } catch (IllegalArgumentException e) { + return UNRECOGNIZED; + } + } + + } + + public static enum Type { + + /** + * full API access. This is typically a service administrator or code that executes with + * complete trust in the service operator's environment. + */ + ADMIN(1), + /** + * full API access within a domain. This is the most privileged user that a given customer + * has. This may be a reseller for the service provider. + */ + DOMAIN_ADMIN(2), + // TODO get code for read-only user. + // /** + // * API access limited to viewing most entities. No access is given to create or update those + // * entities. This may be useful for monitoring programs in the service operator's + // environment. + // */ + // READ_ONLY_ADMIN(?) + /** + * API access for all the resources associated with their account. There may be many users in + * a domain, many domains in a deployment, and many users in a deployment. This is typically + * the end user + */ + USER(0), UNRECOGNIZED(Integer.MAX_VALUE); + + private int code; + + private static final Map INDEX = Maps.uniqueIndex(ImmutableSet.copyOf(Type.values()), + new Function() { + + @Override + public Integer apply(Type input) { + return input.code; + } + + }); + + Type(int code) { + this.code = code; + } + + @Override + public String toString() { + return name(); + } + + public static Type fromValue(String type) { + Integer code = new Integer(checkNotNull(type, "type")); + return INDEX.containsKey(code) ? INDEX.get(code) : UNRECOGNIZED; + } + + } + + private long id; + private Type type; + private String domain; + private long domainId; + private Long IPsAvailable; + private Long IPLimit; + private long IPs; + private boolean cleanupRequired; + private String name; + private long receivedBytes; + private long sentBytes; + private Long snapshotsAvailable; + private Long snapshotLimit; + private long snapshots; + private State state; + private Long templatesAvailable; + private Long templateLimit; + private long templates; + private Long VMsAvailable; + private Long VMLimit; + private long VMsRunning; + private long VMsStopped; + private long VMs; + private Long volumesAvailable; + private Long volumeLimit; + private long volumes; + private Set users; + + public Account(long id, Type type, String domain, long domainId, Long IPsAvailable, Long IPLimit, long iPs, + boolean cleanupRequired, String name, long receivedBytes, long sentBytes, Long snapshotsAvailable, + Long snapshotLimit, long snapshots, org.jclouds.cloudstack.domain.Account.State state, + Long templatesAvailable, Long templateLimit, long templates, Long VMsAvailable, Long VMLimit, + long vMsRunning, long vMsStopped, long vMs, Long volumesAvailable, Long volumeLimit, long volumes, + Set users) { + this.id = id; + this.type = type; + this.domain = domain; + this.domainId = domainId; + this.IPsAvailable = IPsAvailable; + this.IPLimit = IPLimit; + this.IPs = iPs; + this.cleanupRequired = cleanupRequired; + this.name = name; + this.receivedBytes = receivedBytes; + this.sentBytes = sentBytes; + this.snapshotsAvailable = snapshotsAvailable; + this.snapshotLimit = snapshotLimit; + this.snapshots = snapshots; + this.state = state; + this.templatesAvailable = templatesAvailable; + this.templateLimit = templateLimit; + this.templates = templates; + this.VMsAvailable = VMsAvailable; + this.VMLimit = VMLimit; + this.VMsRunning = vMsRunning; + this.VMsStopped = vMsStopped; + this.VMs = vMs; + this.volumesAvailable = volumesAvailable; + this.volumeLimit = volumeLimit; + this.volumes = volumes; + this.users = ImmutableSet.copyOf(checkNotNull(users, "users")); + } + + /** + * present only for serializer + * + */ + Account() { + + } + + /** + * + * @return the id of the account + */ + public long getId() { + return id; + } + + /** + * + * @return the name of the account + */ + + public String getName() { + return name; + } + + /** + * + * @return account type (admin, domain-admin, user) + */ + public Type getType() { + return type; + } + + /** + * + * @return name of the Domain the account belongs to + */ + public String getDomain() { + return domain; + } + + /** + * + * @return id of the Domain the account belongs to + */ + public long getDomainId() { + return domainId; + } + + /** + * + * @return true if the account requires cleanup + */ + public boolean isCleanupRequired() { + return cleanupRequired; + } + + /** + * + * @return the list of users associated with account + */ + public Set getUsers() { + return users; + } + + /** + * + * @return the total number of public ip addresses available for this account to acquire, or null + * if unlimited + */ + @Nullable + public Long getIPsAvailable() { + return IPsAvailable; + } + + /** + * + * @return the total number of public ip addresses this account can acquire, or null if unlimited + */ + @Nullable + public Long getIPLimit() { + return IPLimit; + } + + /** + * + * @return the total number of public ip addresses allocated for this account + */ + public long getIPs() { + return IPs; + } + + /** + * + * @return the total number of network traffic bytes received + */ + public long getReceivedBytes() { + return receivedBytes; + } + + /** + * + * @return the total number of network traffic bytes sent + */ + public long getSentBytes() { + return sentBytes; + } + + /** + * + * @return the total number of snapshots available for this account, or null if unlimited + */ + @Nullable + public Long getSnapshotsAvailable() { + return snapshotsAvailable; + } + + /** + * + * @return the total number of snapshots which can be stored by this account, or null if + * unlimited + */ + @Nullable + public Long getSnapshotLimit() { + return snapshotLimit; + } + + /** + * + * @return the total number of snapshots stored by this account + */ + public long getSnapshots() { + return snapshots; + } + + /** + * + * @return the state of the account + */ + public State getState() { + return state; + } + + /** + * + * @return the total number of templates available to be created by this account, or null if + * unlimited + */ + @Nullable + public Long getTemplatesAvailable() { + return templatesAvailable; + } + + /** + * + * @return the total number of templates which can be created by this account, or null if + * unlimited + */ + @Nullable + public Long getTemplateLimit() { + return templateLimit; + } + + /** + * + * @return the total number of templates which have been created by this account + */ + public long getTemplates() { + return templates; + } + + /** + * + * @return the total number of virtual machines available for this account to acquire, or null if + * unlimited + */ + @Nullable + public Long getVMsAvailable() { + return VMsAvailable; + } + + /** + * + * @return the total number of virtual machines that can be deployed by this account, or null if + * unlimited + */ + @Nullable + public Long getVMLimit() { + return VMLimit; + } + + /** + * + * @return the total number of virtual machines running for this account + */ + public long getVMsRunning() { + return VMsRunning; + } + + /** + * + * @return the total number of virtual machines stopped for this account + */ + public long getVMsStopped() { + return VMsStopped; + } + + /** + * + * @return the total number of virtual machines deployed by this account + */ + public long getVMs() { + return VMs; + } + + /** + * + * @return the total volume available for this account, or null if unlimited + */ + @Nullable + public Long getVolumesAvailable() { + return volumesAvailable; + } + + /** + * + * @return the total volume which can be used by this account, or null if unlimited + */ + @Nullable + public Long getVolumeLimit() { + return volumeLimit; + } + + /** + * + * @return the total volume being used by this account + */ + public long getVolumes() { + return volumes; + } + + @Override + public int compareTo(Account arg0) { + return new Long(id).compareTo(arg0.getId()); + } + + @Override + public String toString() { + return String + .format( + "[id=%s, name=%s, type=%s, state=%s, domain=%s, domainId=%s, cleanupRequired=%s, sentBytes=%s, receivedBytes=%s, IPs=%s, IPsAvailable=%s, IPLimit=%s, VMs=%s, VMsAvailable=%s, VMsRunning=%s, VMsStopped=%s, VMLimit=%s, snapshots=%s, snapshotLimit=%s, snapshotsAvailable=%s, templateLimit=%s, templates=%s, templatesAvailable=%s, volumes=%s, volumeLimit=%s, volumesAvailable=%s, users=%s]", + id, name, type, state, domain, domainId, cleanupRequired, sentBytes, receivedBytes, IPs, + IPsAvailable, IPLimit, VMs, VMsAvailable, VMsRunning, VMsStopped, VMLimit, snapshots, + snapshotLimit, snapshotsAvailable, templateLimit, templates, templatesAvailable, volumes, + volumeLimit, volumesAvailable, users); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + (int) (domainId ^ (domainId >>> 32)); + result = prime * result + (int) (id ^ (id >>> 32)); + result = prime * result + ((name == null) ? 0 : name.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; + Account other = (Account) obj; + if (domainId != other.domainId) + 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; + return true; + } + + @Override + protected Set delegate() { + return users; + } +} diff --git a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java index 834294f948..719052852a 100644 --- a/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java +++ b/sandbox-apis/cloudstack/src/main/java/org/jclouds/cloudstack/domain/Template.java @@ -37,24 +37,16 @@ public class Template implements Comparable