Issue 230: updated to support real version of IBM cloud api

This commit is contained in:
Adrian Cole 2010-07-21 01:47:41 -07:00
parent becf96d822
commit 76f75049f1
28 changed files with 1568 additions and 573 deletions

View File

@ -58,9 +58,9 @@
</repositories> </repositories>
<properties> <properties>
<jclouds.test.identity>${providerUser}</jclouds.test.identity> <jclouds.test.identity>${jclouds.ibmdev.user}</jclouds.test.identity>
<jclouds.test.credential>${providerPassword}</jclouds.test.credential> <jclouds.test.credential>${jclouds.ibmdev.password}</jclouds.test.credential>
<jclouds.test.endpoint>https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403</jclouds.test.endpoint> <jclouds.test.endpoint>https://www-147.ibm.com/computecloud/enterprise/api/rest</jclouds.test.endpoint>
</properties> </properties>
<dependencies> <dependencies>
<dependency> <dependency>

View File

@ -43,6 +43,8 @@ import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibmdev.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibmdev.domain.Location;
import org.jclouds.ibmdev.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibmdev.domain.Volume;
import org.jclouds.ibmdev.functions.GetFirstInstanceInList; import org.jclouds.ibmdev.functions.GetFirstInstanceInList;
import org.jclouds.ibmdev.functions.ParseAddressFromJson; import org.jclouds.ibmdev.functions.ParseAddressFromJson;
@ -67,6 +69,7 @@ import org.jclouds.rest.annotations.ParamParser;
import org.jclouds.rest.annotations.RequestFilters; import org.jclouds.rest.annotations.RequestFilters;
import org.jclouds.rest.annotations.ResponseParser; import org.jclouds.rest.annotations.ResponseParser;
import org.jclouds.rest.annotations.SkipEncoding; import org.jclouds.rest.annotations.SkipEncoding;
import org.jclouds.rest.annotations.Unwrap;
import org.jclouds.rest.annotations.XMLResponseParser; import org.jclouds.rest.annotations.XMLResponseParser;
import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404; import org.jclouds.rest.functions.ReturnEmptySetOnNotFoundOr404;
import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404; import org.jclouds.rest.functions.ReturnNullOnNotFoundOr404;
@ -85,13 +88,13 @@ import com.google.common.util.concurrent.ListenableFuture;
@RequestFilters(BasicAuthentication.class) @RequestFilters(BasicAuthentication.class)
@SkipEncoding( { '{', '}' }) @SkipEncoding( { '{', '}' })
public interface IBMDeveloperCloudAsyncClient { public interface IBMDeveloperCloudAsyncClient {
public static final String VERSION = "20090403"; public static final String VERSION = "20100331";
/** /**
* @see IBMDeveloperCloudClient#listImages() * @see IBMDeveloperCloudClient#listImages()
*/ */
@GET @GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImagesFromJson.class) @ResponseParser(ParseImagesFromJson.class)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class) @ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
@ -102,7 +105,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@GET @GET
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class) @ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> getImage(@PathParam("imageId") String id); ListenableFuture<Image> getImage(@PathParam("imageId") String id);
@ -111,7 +114,7 @@ public interface IBMDeveloperCloudAsyncClient {
* @see IBMDeveloperCloudClient#deleteImage * @see IBMDeveloperCloudClient#deleteImage
*/ */
@DELETE @DELETE
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteImage(@PathParam("imageId") String id); ListenableFuture<Void> deleteImage(@PathParam("imageId") String id);
@ -120,7 +123,7 @@ public interface IBMDeveloperCloudAsyncClient {
*/ */
@PUT @PUT
@ExceptionParser(ReturnNullOnNotFoundOr404.class) @ExceptionParser(ReturnNullOnNotFoundOr404.class)
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/images/{imageId}") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/image/{imageId}")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseImageFromJson.class) @ResponseParser(ParseImageFromJson.class)
ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id, ListenableFuture<Image> setImageVisibility(@PathParam("imageId") String id,
@ -262,6 +265,16 @@ public interface IBMDeveloperCloudAsyncClient {
@ExceptionParser(ReturnVoidOnNotFoundOr404.class) @ExceptionParser(ReturnVoidOnNotFoundOr404.class)
ListenableFuture<Void> deleteKey(@PathParam("keyName") String name); ListenableFuture<Void> deleteKey(@PathParam("keyName") String name);
/**
* @see IBMDeveloperCloudClient#listStorageOfferings()
*/
@GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/storage")
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends StorageOffering>> listStorageOfferings();
/** /**
* @see IBMDeveloperCloudClient#listVolumes() * @see IBMDeveloperCloudClient#listVolumes()
*/ */
@ -280,7 +293,8 @@ public interface IBMDeveloperCloudAsyncClient {
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseVolumeFromJson.class) @ResponseParser(ParseVolumeFromJson.class)
ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location, ListenableFuture<Volume> createVolumeInLocation(@FormParam("location") String location,
@FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size); @FormParam("name") String name, @FormParam("format") String format, @FormParam("size") String size,
@FormParam("offeringID") String offeringID);
/** /**
* @see IBMDeveloperCloudClient#getVolume(long) * @see IBMDeveloperCloudClient#getVolume(long)
@ -320,6 +334,16 @@ public interface IBMDeveloperCloudAsyncClient {
@XMLResponseParser(LocationHandler.class) @XMLResponseParser(LocationHandler.class)
ListenableFuture<Location> getLocation(@PathParam("locationId") String id); ListenableFuture<Location> getLocation(@PathParam("locationId") String id);
/**
* @see IBMDeveloperCloudClient#listAddressOfferings()
*/
@GET
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/offerings/address")
@Unwrap
@Consumes(MediaType.APPLICATION_JSON)
@ExceptionParser(ReturnEmptySetOnNotFoundOr404.class)
ListenableFuture<Set<? extends Offering>> listAddressOfferings();
/** /**
* @see IBMDeveloperCloudClient#listAddresses() * @see IBMDeveloperCloudClient#listAddresses()
*/ */
@ -337,7 +361,8 @@ public interface IBMDeveloperCloudAsyncClient {
@Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses") @Path(IBMDeveloperCloudAsyncClient.VERSION + "/addresses")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ResponseParser(ParseAddressFromJson.class) @ResponseParser(ParseAddressFromJson.class)
ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId); ListenableFuture<Address> allocateAddressInLocation(@FormParam("location") String locationId,
@FormParam("offeringID") String offeringID);
/** /**
* @see IBMDeveloperCloudClient#releaseAddress * @see IBMDeveloperCloudClient#releaseAddress

View File

@ -52,6 +52,8 @@ import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibmdev.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibmdev.domain.Location;
import org.jclouds.ibmdev.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibmdev.domain.Volume;
import org.jclouds.ibmdev.options.CreateInstanceOptions; import org.jclouds.ibmdev.options.CreateInstanceOptions;
import org.jclouds.ibmdev.options.RestartInstanceOptions; import org.jclouds.ibmdev.options.RestartInstanceOptions;
@ -70,7 +72,8 @@ import org.jclouds.rest.ResourceNotFoundException;
public interface IBMDeveloperCloudClient { public interface IBMDeveloperCloudClient {
/** /**
* *
* @return the list of Images available to be provisioned on the IBM DeveloperCloud. * @return the list of Images available to be provisioned on the IBM
* DeveloperCloud.
*/ */
Set<? extends Image> listImages(); Set<? extends Image> listImages();
@ -79,7 +82,8 @@ public interface IBMDeveloperCloudClient {
* *
* @return null if image is not found * @return null if image is not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to view this image to section * code 401 if the user is not authorized to view this image to
* section
*/ */
Image getImage(String id); Image getImage(String id);
@ -89,20 +93,24 @@ public interface IBMDeveloperCloudClient {
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to delete this image * code 401 if the user is not authorized to delete this image
* @throws IllegalStateException * @throws IllegalStateException
* code 412 if the image is in an invalid state to perform this operation * code 412 if the image is in an invalid state to perform this
* operation
*/ */
void deleteImage(String id); void deleteImage(String id);
/** /**
* If set to {@code Image.Visibility#PUBLIC}, makes the Image identified by the supplied Image ID * If set to {@code Image.Visibility#PUBLIC}, makes the Image identified by
* publicly available for all users to create Instances of. * the supplied Image ID publicly available for all users to create Instances
* of.
* *
* @return modified image or null, if image was not found. * @return modified image or null, if image was not found.
* *
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to change the visibility of this image * code 401 if the user is not authorized to change the visibility
* of this image
* @throws IllegalStateException * @throws IllegalStateException
* code 412 if the image is in an invalid state to perform this operation * code 412 if the image is in an invalid state to perform this
* operation
*/ */
Image setImageVisibility(String id, Image.Visibility visibility); Image setImageVisibility(String id, Image.Visibility visibility);
@ -110,27 +118,30 @@ public interface IBMDeveloperCloudClient {
* *
* @return the list of Instances that the authenticated user manages. * @return the list of Instances that the authenticated user manages.
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this * code 401 if the currently authenticated user is not authorized
* information * to view this information
*/ */
Set<? extends Instance> listInstances(); Set<? extends Instance> listInstances();
/** /**
* *
* @return the list of Instances that the authenticated user manages that were created as part of * @return the list of Instances that the authenticated user manages that
* the request specified by {@code requestId}, or null if the request was not found * were created as part of the request specified by {@code requestId}
* , or null if the request was not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this request * code 401 if the currently authenticated user is not authorized
* to view this request
*/ */
Set<? extends Instance> listInstancesFromRequest(String requestId); Set<? extends Instance> listInstancesFromRequest(String requestId);
/** /**
* Returns the Instance that the authenticated user manages with the specified {@code id} * Returns the Instance that the authenticated user manages with the
* specified {@code id}
* *
* @return null if instance is not found * @return null if instance is not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this * code 401 if the currently authenticated user is not authorized
* instance * to view this instance
*/ */
Instance getInstance(String id); Instance getInstance(String id);
@ -144,20 +155,26 @@ public interface IBMDeveloperCloudClient {
* @param imageID * @param imageID
* The ID of the image to create this instance from * The ID of the image to create this instance from
* @param instanceType * @param instanceType
* The instance type to use for this instance {SMALL, MEDIUM, LARGE} * The instance type to use for this instance {SMALL, MEDIUM,
* LARGE}
* @param options * @param options
* overrides default public key, mounts a volume, or attaches a static ip * overrides default public key, mounts a volume, or attaches a
* static ip
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the authenticated user is not authorized to create instances * code 401 if the authenticated user is not authorized to create
* instances
* <p/> * <p/>
* code 402 if payment is required before more instances may be created * code 402 if payment is required before more instances may be
* created
* @throws IllegalStateException * @throws IllegalStateException
* code 409 if there are not enough resources in the cloud to fulfill this request * code 409 if there are not enough resources in the cloud to
* fulfill this request
* <p/> * <p/>
* code 412 One or more of the supplied parameters are invalid for this request * code 412 One or more of the supplied parameters are invalid for
* this request
*/ */
Instance createInstanceInLocation(String location, String name, String imageID, Instance createInstanceInLocation(String location, String name, String imageID, String instanceType,
String instanceType, CreateInstanceOptions... options); CreateInstanceOptions... options);
/** /**
* Sets the expiration time of the instance to the value specified * Sets the expiration time of the instance to the value specified
@ -165,16 +182,19 @@ public interface IBMDeveloperCloudClient {
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
* code 404 The instance specified by {@code name} was not found * code 404 The instance specified by {@code name} was not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to extend the expiration time of this * code 401 if the user is not authorized to extend the expiration
* instance * time of this instance
* <p/> * <p/>
* code 402 if payment is required before more instances may be created * code 402 if payment is required before more instances may be
* created
* @throws IllegalStateException * @throws IllegalStateException
* <p> * <p>
* code 406 The provided expiration date is not valid code 409 if there are not enough * code 406 The provided expiration date is not valid code 409 if
* resources in the cloud to fulfill this request * there are not enough resources in the cloud to fulfill this
* request
* <p/> * <p/>
* code 412 The instance is in an invalid state to perform this operation * code 412 The instance is in an invalid state to perform this
* operation
*/ */
Date extendReservationForInstance(String id, Date expirationTime); Date extendReservationForInstance(String id, Date expirationTime);
@ -188,16 +208,19 @@ public interface IBMDeveloperCloudClient {
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
* code 404 The instance specified by {@code name} was not found * code 404 The instance specified by {@code name} was not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to extend the expiration time of this * code 401 if the user is not authorized to extend the expiration
* instance * time of this instance
* <p/> * <p/>
* code 402 if payment is required before more instances may be created * code 402 if payment is required before more instances may be
* created
* @throws IllegalStateException * @throws IllegalStateException
* <p> * <p>
* code 406 The provided expiration date is not valid code 409 if there are not enough * code 406 The provided expiration date is not valid code 409 if
* resources in the cloud to fulfill this request * there are not enough resources in the cloud to fulfill this
* request
* <p/> * <p/>
* code 412 The instance is in an invalid state to perform this operation * code 412 The instance is in an invalid state to perform this
* operation
*/ */
void restartInstance(String id, RestartInstanceOptions... options); void restartInstance(String id, RestartInstanceOptions... options);
@ -214,26 +237,31 @@ public interface IBMDeveloperCloudClient {
* @throws ResourceNotFoundException * @throws ResourceNotFoundException
* code 404 The instance specified by {@code name} was not found * code 404 The instance specified by {@code name} was not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to extend the expiration time of this * code 401 if the user is not authorized to extend the expiration
* instance * time of this instance
* <p/> * <p/>
* code 402 if payment is required before more instances may be created * code 402 if payment is required before more instances may be
* created
* @throws IllegalStateException * @throws IllegalStateException
* <p> * <p>
* code 406 The provided expiration date is not valid code 409 if there are not enough * code 406 The provided expiration date is not valid code 409 if
* resources in the cloud to fulfill this request * there are not enough resources in the cloud to fulfill this
* request
* <p/> * <p/>
* code 412 The instance is in an invalid state to perform this operation * code 412 The instance is in an invalid state to perform this
* operation
*/ */
Image saveInstanceToImage(String id, String toImageName, String toImageDescription); Image saveInstanceToImage(String id, String toImageName, String toImageDescription);
/** /**
* Deletes the Instance that the authenticated user manages with the specified {@code id} * Deletes the Instance that the authenticated user manages with the
* specified {@code id}
* *
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to delete this instance * code 401 if the user is not authorized to delete this instance
* @throws IllegalStateException * @throws IllegalStateException
* code 412 if the instance is in an invalid state to perform this operation * code 412 if the instance is in an invalid state to perform this
* operation
*/ */
void deleteInstance(String id); void deleteInstance(String id);
@ -244,8 +272,8 @@ public interface IBMDeveloperCloudClient {
Set<? extends Key> listKeys(); Set<? extends Key> listKeys();
/** /**
* Returns the key with the specified key name from the set of Public Keys stored for the * Returns the key with the specified key name from the set of Public Keys
* authenticated user. * stored for the authenticated user.
* *
* @return null if key is not found * @return null if key is not found
*/ */
@ -280,8 +308,8 @@ public interface IBMDeveloperCloudClient {
void addPublicKey(String name, String publicKey); void addPublicKey(String name, String publicKey);
/** /**
* Used to update the Public Key specified by the supplied key name stored for the authenticated * Used to update the Public Key specified by the supplied key name stored
* user. * for the authenticated user.
* *
* @param name * @param name
* The name to used to identify this key pair. * The name to used to identify this key pair.
@ -295,7 +323,8 @@ public interface IBMDeveloperCloudClient {
void updatePublicKey(String name, String publicKey); void updatePublicKey(String name, String publicKey);
/** /**
* Used to set the Public Key specified by the supplied key name as the default key. * Used to set the Public Key specified by the supplied key name as the
* default key.
* *
* @param name * @param name
* The name to used to identify this key pair. * The name to used to identify this key pair.
@ -314,12 +343,22 @@ public interface IBMDeveloperCloudClient {
*/ */
void deleteKey(String name); void deleteKey(String name);
/**
* Used to retrieve the offerings of storage for the authenticated user.
*
* @return offerings or empty set if none
* @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized
* to view this information
*/
Set<? extends StorageOffering> listStorageOfferings();
/** /**
* *
* @return the set of storage volumes for the authenticated user. * @return the set of storage volumes for the authenticated user.
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this * code 401 if the currently authenticated user is not authorized
* information * to view this information
*/ */
Set<? extends Volume> listVolumes(); Set<? extends Volume> listVolumes();
@ -331,29 +370,37 @@ public interface IBMDeveloperCloudClient {
* @param name * @param name
* The desired name of the newly created storage volume * The desired name of the newly created storage volume
* @param format * @param format
* The filesystem format for the new storage volume. Valid format is: EXT3 * The filesystem format for the new storage volume. Valid format
* is: EXT3
* @param size * @param size
* The size of the new storage volume. Valid values may include SMALL, MEDIUM, and * The size of the new storage volume. Valid values may include
* LARGE. Actual values may depend on the location used and may be discov- ered via the * SMALL, MEDIUM, and LARGE. Actual values may depend on the
* location service * location used and may be discov- ered via the location service
* @param offeringID
* The offeringID which can be obtained from
* {@link #listStorageOfferings}
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to create a volume * code 401 if the currently authenticated user is not authorized
* to create a volume
* <p/> * <p/>
* code 402 if payment is required before more storage volumes may be created * code 402 if payment is required before more storage volumes may
* be created
* @throws IllegalStateException * @throws IllegalStateException
* code 409 ifhere are not enough resources in the cloud to fulfill this request * code 409 ifhere are not enough resources in the cloud to
* fulfill this request
* <p/> * <p/>
* code 412 One or more of the supplied parameters are invalid for this request * code 412 One or more of the supplied parameters are invalid for
* this request
*/ */
Volume createVolumeInLocation(String location, String name, String format, String size); Volume createVolumeInLocation(String location, String name, String format, String size, String offeringID);
/** /**
* Used to retrieve the specified storage volume for the authenticated user. * Used to retrieve the specified storage volume for the authenticated user.
* *
* @return null if volume is not found * @return null if volume is not found
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this storage * code 401 if the currently authenticated user is not authorized
* volume * to view this storage volume
*/ */
Volume getVolume(String id); Volume getVolume(String id);
@ -361,17 +408,18 @@ public interface IBMDeveloperCloudClient {
* Remove the specified storage volume for the authenticated user. * Remove the specified storage volume for the authenticated user.
* *
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to remove this * code 401 if the currently authenticated user is not authorized
* storage volume * to remove this storage volume
* @throws IllegalStateException * @throws IllegalStateException
* code 412 if the storage volume is not in the correct state to be deleted * code 412 if the storage volume is not in the correct state to
* be deleted
*/ */
void deleteVolume(String id); void deleteVolume(String id);
/** /**
* *
* @return the list of Locations (Data Centers) that the user is entitled to and their * @return the list of Locations (Data Centers) that the user is entitled to
* capabilities * and their capabilities
*/ */
Set<? extends Location> listLocations(); Set<? extends Location> listLocations();
@ -389,8 +437,8 @@ public interface IBMDeveloperCloudClient {
* *
* @return the set of static IP addresses for the authenticated user. * @return the set of static IP addresses for the authenticated user.
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to view this * code 401 if the currently authenticated user is not authorized
* information * to view this information
*/ */
Set<? extends Address> listAddresses(); Set<? extends Address> listAddresses();
@ -400,23 +448,41 @@ public interface IBMDeveloperCloudClient {
* *
* @param locationId * @param locationId
* the id of the Location where this address will be allocated * the id of the Location where this address will be allocated
* @param offeringID
* The offeringID which can be obtained from
* {@link #listAddressOfferings}
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized to remove this IP * code 401 if the currently authenticated user is not authorized
* address * to remove this IP address
* <p/> * <p/>
* code 402 if payment is required before more addresses may be allocated * code 402 if payment is required before more addresses may be
* allocated
*
* @throws IllegalStateException * @throws IllegalStateException
* code 409 ifhere are not enough resources in the cloud to fulfill this request * code 409 ifhere are not enough resources in the cloud to
* fulfill this request
*/ */
Address allocateAddressInLocation(String locationId); Address allocateAddressInLocation(String locationId, String offeringID);
/** /**
* Used to release the specified static IP addresses for the authenticated user. * Used to retrieve the offerings of addresses for the authenticated user.
*
* @return offerings or empty set if none
* @throws AuthorizationException
* code 401 if the currently authenticated user is not authorized
* to view this information
*/
Set<? extends Offering> listAddressOfferings();
/**
* Used to release the specified static IP addresses for the authenticated
* user.
* *
* @throws AuthorizationException * @throws AuthorizationException
* code 401 if the user is not authorized to release this address * code 401 if the user is not authorized to release this address
* @throws IllegalStateException * @throws IllegalStateException
* code 412 address is in an invalid state to perform this operation * code 412 address is in an invalid state to perform this
* operation
*/ */
void releaseAddress(String id); void releaseAddress(String id);

View File

@ -42,8 +42,7 @@ public class IBMDeveloperCloudPropertiesBuilder extends PropertiesBuilder {
protected Properties defaultProperties() { protected Properties defaultProperties() {
Properties properties = super.defaultProperties(); Properties properties = super.defaultProperties();
properties.setProperty(PROPERTY_API_VERSION, IBMDeveloperCloudAsyncClient.VERSION); properties.setProperty(PROPERTY_API_VERSION, IBMDeveloperCloudAsyncClient.VERSION);
properties.setProperty(PROPERTY_ENDPOINT, properties.setProperty(PROPERTY_ENDPOINT, "https://www-147.ibm.com/computecloud/enterprise/api/rest");
"https://www-180.ibm.com/cloud/enterprise/beta/api/rest");
properties.setProperty(PROPERTY_IBMDEVELOPERCLOUD_LOCATION, "1"); properties.setProperty(PROPERTY_IBMDEVELOPERCLOUD_LOCATION, "1");
properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + ""); properties.setProperty(PROPERTY_TIMEOUT_NODE_RUNNING, (15 * 60 * 1000) + "");
return properties; return properties;

View File

@ -67,16 +67,37 @@ public class Image {
private int state; private int state;
private Visibility visibility; private Visibility visibility;
private String owner; private String owner;
private String architecture;
private String platform; private String platform;
private Date createdTime; private Date createdTime;
private String location; private String location;
private Set<String> supportedInstanceTypes = Sets.newLinkedHashSet(); private Set<InstanceType> supportedInstanceTypes = Sets.newLinkedHashSet();
private Set<String> productCodes = Sets.newLinkedHashSet(); private Set<String> productCodes = Sets.newLinkedHashSet();
private URI documentation; private URI documentation;
private String id; private String id;
private String description; private String description;
Image() {
}
public Image(String name, URI manifest, int state, Visibility visibility, String owner, String platform,
Date createdTime, String location, Set<InstanceType> supportedInstanceTypes, Set<String> productCodes,
URI documentation, String id, String description) {
this.name = name;
this.manifest = manifest;
this.state = state;
this.visibility = visibility;
this.owner = owner;
this.platform = platform;
this.createdTime = createdTime;
this.location = location;
this.supportedInstanceTypes = supportedInstanceTypes;
this.productCodes = productCodes;
this.documentation = documentation;
this.id = id;
this.description = description;
}
public String getName() { public String getName() {
return name; return name;
} }
@ -117,14 +138,6 @@ public class Image {
this.owner = owner; this.owner = owner;
} }
public String getArchitecture() {
return architecture;
}
public void setArchitecture(String architecture) {
this.architecture = architecture;
}
public String getPlatform() { public String getPlatform() {
return platform; return platform;
} }
@ -149,11 +162,11 @@ public class Image {
this.location = location; this.location = location;
} }
public Set<String> getSupportedInstanceTypes() { public Set<InstanceType> getSupportedInstanceTypes() {
return supportedInstanceTypes; return supportedInstanceTypes;
} }
public void setSupportedInstanceTypes(Set<String> supportedInstanceTypes) { public void setSupportedInstanceTypes(Set<InstanceType> supportedInstanceTypes) {
this.supportedInstanceTypes = supportedInstanceTypes; this.supportedInstanceTypes = supportedInstanceTypes;
} }
@ -193,7 +206,6 @@ public class Image {
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result + ((architecture == null) ? 0 : architecture.hashCode());
result = prime * result + ((createdTime == null) ? 0 : createdTime.hashCode()); result = prime * result + ((createdTime == null) ? 0 : createdTime.hashCode());
result = prime * result + ((description == null) ? 0 : description.hashCode()); result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((documentation == null) ? 0 : documentation.hashCode()); result = prime * result + ((documentation == null) ? 0 : documentation.hashCode());
@ -204,8 +216,7 @@ public class Image {
result = prime * result + ((owner == null) ? 0 : owner.hashCode()); result = prime * result + ((owner == null) ? 0 : owner.hashCode());
result = prime * result + ((platform == null) ? 0 : platform.hashCode()); result = prime * result + ((platform == null) ? 0 : platform.hashCode());
result = prime * result + ((productCodes == null) ? 0 : productCodes.hashCode()); result = prime * result + ((productCodes == null) ? 0 : productCodes.hashCode());
result = prime * result result = prime * result + ((supportedInstanceTypes == null) ? 0 : supportedInstanceTypes.hashCode());
+ ((supportedInstanceTypes == null) ? 0 : supportedInstanceTypes.hashCode());
result = prime * result + ((visibility == null) ? 0 : visibility.hashCode()); result = prime * result + ((visibility == null) ? 0 : visibility.hashCode());
return result; return result;
} }
@ -219,11 +230,6 @@ public class Image {
if (getClass() != obj.getClass()) if (getClass() != obj.getClass())
return false; return false;
Image other = (Image) obj; Image other = (Image) obj;
if (architecture == null) {
if (other.architecture != null)
return false;
} else if (!architecture.equals(other.architecture))
return false;
if (createdTime == null) { if (createdTime == null) {
if (other.createdTime != null) if (other.createdTime != null)
return false; return false;
@ -289,9 +295,8 @@ public class Image {
@Override @Override
public String toString() { public String toString() {
return "Image [id=" + id + ", name=" + name + ", location=" + location + ", manifest=" return "Image [id=" + id + ", name=" + name + ", location=" + location + ", manifest=" + manifest + ", platform="
+ manifest + ", platform=" + platform + ", state=" + getState() + platform + ", state=" + getState() + ", supportedInstanceTypes=" + supportedInstanceTypes
+ ", supportedInstanceTypes=" + supportedInstanceTypes + ", visibility=" + ", visibility=" + visibility + "]";
+ visibility + "]";
} }
} }

View File

@ -31,7 +31,7 @@ import com.google.common.collect.Sets;
*/ */
public class Instance { public class Instance {
public static enum Status { public static enum Status {
NEW, PROVISIONING, FAILED, REMOVED, REJECTED, ACTIVE, UNKNOWN, DEPROVISIONING, RESTARTING, STARTING, STOPPING, STOPPED; NEW, PROVISIONING, FAILED, REMOVED, REJECTED, ACTIVE, UNKNOWN, DEPROVISIONING, RESTARTING, STARTING, STOPPING, STOPPED, DEPROVISION_PENDING;
public static Status fromValue(int v) { public static Status fromValue(int v) {
switch (v) { switch (v) {
case 0: case 0:
@ -58,6 +58,8 @@ public class Instance {
return STOPPING; return STOPPING;
case 11: case 11:
return STOPPED; return STOPPED;
case 12:
return DEPROVISION_PENDING;
default: default:
throw new IllegalArgumentException("invalid state:" + v); throw new IllegalArgumentException("invalid state:" + v);
} }
@ -163,10 +165,9 @@ public class Instance {
private String id; private String id;
private Date expirationTime; private Date expirationTime;
public Instance(Date launchTime, Set<Software> software, String ip, String requestId, public Instance(Date launchTime, Set<Software> software, String ip, String requestId, String keyName, String name,
String keyName, String name, String instanceType, int status, String owner, String instanceType, int status, String owner, String hostname, String location, String imageId,
String hostname, String location, String imageId, Set<String> productCodes, Set<String> productCodes, String requestName, String id, Date expirationTime) {
String requestName, String id, Date expirationTime) {
this.launchTime = launchTime; this.launchTime = launchTime;
this.software = software; this.software = software;
this.ip = ip; this.ip = ip;
@ -421,11 +422,10 @@ public class Instance {
@Override @Override
public String toString() { public String toString() {
return "Instance [id=" + id + ", name=" + name + ", ip=" + ip + ", hostname=" + hostname return "Instance [id=" + id + ", name=" + name + ", ip=" + ip + ", hostname=" + hostname + ", status="
+ ", status=" + getStatus() + ", instanceType=" + instanceType + ", location=" + getStatus() + ", instanceType=" + instanceType + ", location=" + location + ", imageId=" + imageId
+ location + ", imageId=" + imageId + ", software=" + software + ", keyName=" + ", software=" + software + ", keyName=" + keyName + ", launchTime=" + launchTime + ", expirationTime="
+ keyName + ", launchTime=" + launchTime + ", expirationTime=" + expirationTime + expirationTime + ", owner=" + owner + ", productCodes=" + productCodes + ", requestId=" + requestId
+ ", owner=" + owner + ", productCodes=" + productCodes + ", requestId=" + requestId
+ ", requestName=" + requestName + "]"; + ", requestName=" + requestName + "]";
} }

View File

@ -0,0 +1,97 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the ;License;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ;AS IS; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.domain;
/**
*
*
* @author Adrian Cole
*/
public class InstanceType {
protected String label;
protected Price price;
protected String id;
public InstanceType(String label, Price price, String id) {
super();
this.label = label;
this.price = price;
this.id = id;
}
InstanceType() {
super();
}
public String getLabel() {
return label;
}
public Price getPrice() {
return price;
}
public String getId() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((label == null) ? 0 : label.hashCode());
result = prime * result + ((price == null) ? 0 : price.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;
InstanceType other = (InstanceType) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
return true;
}
@Override
public String toString() {
return "[id=" + id + ", label=" + label + ", price=" + price + "]";
}
}

View File

@ -40,8 +40,7 @@ public class Key {
private String name; private String name;
private Date lastModifiedTime; private Date lastModifiedTime;
public Key(boolean isDefault, Iterable<String> instanceIds, String keyMaterial, String name, public Key(boolean isDefault, Iterable<String> instanceIds, String keyMaterial, String name, Date lastModifiedTime) {
Date lastModifiedTime) {
this.isDefault = isDefault; this.isDefault = isDefault;
Iterables.addAll(this.instanceIds, instanceIds); Iterables.addAll(this.instanceIds, instanceIds);
this.keyMaterial = keyMaterial; this.keyMaterial = keyMaterial;
@ -133,8 +132,8 @@ public class Key {
@Override @Override
public String toString() { public String toString() {
return "Key [isDefault=" + isDefault + ", instanceIds=" + instanceIds + ", name=" + name return "Key [isDefault=" + isDefault + ", instanceIds=" + instanceIds + ", name=" + name + ", keyMaterial="
+ ", keyMaterial=" + keyMaterial + ", lastModifiedTime=" + lastModifiedTime + "]"; + keyMaterial + ", lastModifiedTime=" + lastModifiedTime + "]";
} }
public Set<String> getInstanceIds() { public Set<String> getInstanceIds() {

View File

@ -0,0 +1,90 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the ;License;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ;AS IS; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.domain;
/**
*
*
* @author Adrian Cole
*/
public class Offering {
protected String location;
protected Price price;
protected String id;
public Offering() {
super();
}
public String getLocation() {
return location;
}
public Price getPrice() {
return price;
}
public String getId() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((location == null) ? 0 : location.hashCode());
result = prime * result + ((price == null) ? 0 : price.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;
Offering other = (Offering) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (location == null) {
if (other.location != null)
return false;
} else if (!location.equals(other.location))
return false;
if (price == null) {
if (other.price != null)
return false;
} else if (!price.equals(other.price))
return false;
return true;
}
@Override
public String toString() {
return "[id=" + id + ", location=" + location + ", price=" + price + "]";
}
}

View File

@ -0,0 +1,132 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the ;License;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ;AS IS; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.domain;
import java.util.Date;
/**
*
*
* @author Adrian Cole
*/
public class Price {
private double rate;
private String unitOfMeasure;
private String countryCode;
private Date effectiveDate;
private String currencyCode;
private double pricePerQuantity;
Price() {
}
public Price(double rate, String unitOfMeasure, String countryCode, Date effectiveDate, String currencyCode,
double pricePerQuantity) {
this.rate = rate;
this.unitOfMeasure = unitOfMeasure;
this.countryCode = countryCode;
this.effectiveDate = effectiveDate;
this.currencyCode = currencyCode;
this.pricePerQuantity = pricePerQuantity;
}
public double getRate() {
return rate;
}
public String getUnitOfMeasure() {
return unitOfMeasure;
}
public String getCountryCode() {
return countryCode;
}
public Date getEffectiveDate() {
return effectiveDate;
}
public String getCurrencyCode() {
return currencyCode;
}
public double getPricePerQuantity() {
return pricePerQuantity;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((countryCode == null) ? 0 : countryCode.hashCode());
result = prime * result + ((currencyCode == null) ? 0 : currencyCode.hashCode());
result = prime * result + ((effectiveDate == null) ? 0 : effectiveDate.hashCode());
long temp;
temp = Double.doubleToLongBits(pricePerQuantity);
result = prime * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(rate);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((unitOfMeasure == null) ? 0 : unitOfMeasure.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;
Price other = (Price) obj;
if (countryCode == null) {
if (other.countryCode != null)
return false;
} else if (!countryCode.equals(other.countryCode))
return false;
if (currencyCode == null) {
if (other.currencyCode != null)
return false;
} else if (!currencyCode.equals(other.currencyCode))
return false;
if (effectiveDate == null) {
if (other.effectiveDate != null)
return false;
} else if (!effectiveDate.equals(other.effectiveDate))
return false;
if (Double.doubleToLongBits(pricePerQuantity) != Double.doubleToLongBits(other.pricePerQuantity))
return false;
if (Double.doubleToLongBits(rate) != Double.doubleToLongBits(other.rate))
return false;
if (unitOfMeasure == null) {
if (other.unitOfMeasure != null)
return false;
} else if (!unitOfMeasure.equals(other.unitOfMeasure))
return false;
return true;
}
@Override
public String toString() {
return "[countryCode=" + countryCode + ", currencyCode=" + currencyCode + ", effectiveDate=" + effectiveDate
+ ", pricePerQuantity=" + pricePerQuantity + ", rate=" + rate + ", unitOfMeasure=" + unitOfMeasure + "]";
}
}

View File

@ -0,0 +1,125 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the ;License;);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an ;AS IS; BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.domain;
import java.util.Set;
import com.google.common.collect.Sets;
/**
*
* An Offering for Storage
*
* @author Adrian Cole
*/
public class StorageOffering extends Offering {
public static class Format {
private String label;
private String id;
Format() {
}
public Format(String label, String id) {
this.label = label;
this.id = id;
}
public String getLabel() {
return label;
}
public String getId() {
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((label == null) ? 0 : label.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;
Format other = (Format) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (label == null) {
if (other.label != null)
return false;
} else if (!label.equals(other.label))
return false;
return true;
}
@Override
public String toString() {
return "[id=" + id + ", label=" + label + "]";
}
}
private long capacity;
private String name;
private Set<Format> formats = Sets.newLinkedHashSet();
StorageOffering() {
}
public StorageOffering(String location, Price price, long capacity, String name, String id, Set<Format> formats) {
this.location = location;
this.price = price;
this.capacity = capacity;
this.name = name;
this.id = id;
this.formats = formats;
}
public long getCapacity() {
return capacity;
}
public String getName() {
return name;
}
public Set<? extends Format> getFormats() {
return formats;
}
@Override
public String toString() {
return "[capacity=" + capacity + ", formats=" + formats + ", id=" + id + ", location=" + location + ", name="
+ name + ", price=" + price + "]";
}
}

View File

@ -35,8 +35,8 @@ public class GetFirstInstanceInList implements Function<HttpResponse, Instance>
private ParseInstancesFromJson listParser; private ParseInstancesFromJson listParser;
@Inject @Inject
public GetFirstInstanceInList(ParseInstancesFromJson gson) { public GetFirstInstanceInList(ParseInstancesFromJson mapper) {
this.listParser = gson; this.listParser = mapper;
} }
@Override @Override

View File

@ -16,29 +16,6 @@
* limitations under the License. * limitations under the License.
* ==================================================================== * ====================================================================
*/ */
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import java.util.Set; import java.util.Set;
@ -64,8 +41,10 @@ public class ParseUtils {
public boolean apply(Address input) { public boolean apply(Address input) {
if ("0".equals(input.getInstanceId())) if ("0".equals(input.getInstanceId()))
input.setInstanceId(null); input.setInstanceId(null);
if ("".equals(input.getIp())) if (input.getIp() != null && "".equals(input.getIp().trim()))
input.setIp(null); input.setIp(null);
else if (input.getIp() != null && input.getIp().endsWith(" "))
input.setIp(input.getIp().trim());
return true; return true;
} }
}; };
@ -102,8 +81,14 @@ public class ParseUtils {
public boolean apply(Instance input) { public boolean apply(Instance input) {
if (emptyString.equals(input.getProductCodes())) if (emptyString.equals(input.getProductCodes()))
input.getProductCodes().clear(); input.getProductCodes().clear();
if ("".equals(input.getIp())) if (input.getIp() != null && "".equals(input.getIp().trim()))
input.setIp(null); input.setIp(null);
else if (input.getIp() != null && input.getIp().endsWith(" "))
input.setIp(input.getIp().trim());
if (input.getHostname() != null && "".equals(input.getHostname().trim()))
input.setHostname(null);
else if (input.getHostname() != null && input.getHostname().endsWith(" "))
input.setHostname(input.getHostname().trim());
return true; return true;
} }
}; };

View File

@ -50,28 +50,31 @@ public class IBMDeveloperCloudErrorHandler implements HttpErrorHandler {
try { try {
// it is important to always read fully and close streams // it is important to always read fully and close streams
String message = parseMessage(response); String message = parseMessage(response);
exception = message != null ? new HttpResponseException(command, response, message) exception = message != null ? new HttpResponseException(command, response, message) : exception;
: exception; message = message != null ? message : String.format("%s -> %s", command.getRequest().getRequestLine(),
message = message != null ? message : String.format("%s -> %s", command.getRequest() response.getStatusLine());
.getRequestLine(), response.getStatusLine());
switch (response.getStatusCode()) { switch (response.getStatusCode()) {
case 401: case 401:
exception = new AuthorizationException(command.getRequest(), exception = new AuthorizationException(command.getRequest(), message != null ? message : response
message != null ? message : response.getStatusLine()); .getStatusLine());
break; break;
case 402: case 402:
case 403: case 403:
exception = new AuthorizationException(message, exception); exception = new AuthorizationException(message, exception);
break; break;
case 404:
if (!command.getRequest().getMethod().equals("DELETE")) {
exception = new ResourceNotFoundException(message, exception);
}
break;
case 406: case 406:
case 409: case 409:
case 412: case 412:
exception = new IllegalStateException(message, exception); exception = new IllegalStateException(message, exception);
break; break;
case 404: case 500:
if (!command.getRequest().getMethod().equals("DELETE")) { if (message != null && message.indexOf("There is already a BlockStorageDevice object with name") != 1)
exception = new ResourceNotFoundException(message, exception); exception = new IllegalStateException(message, exception);
}
break; break;
} }
} catch (IOException e) { } catch (IOException e) {

View File

@ -0,0 +1,58 @@
/**
*
* Copyright (C) 2009 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.predicates;
import javax.annotation.Resource;
import javax.inject.Singleton;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.logging.Logger;
import com.google.common.base.Predicate;
import com.google.inject.Inject;
/**
*
* @author Adrian Cole
*/
@Singleton
public class InstanceActiveOrFailed implements Predicate<Instance> {
private final IBMDeveloperCloudClient client;
@Resource
protected Logger logger = Logger.NULL;
@Inject
public InstanceActiveOrFailed(IBMDeveloperCloudClient client) {
this.client = client;
}
public boolean apply(Instance instance) {
logger.trace("looking for state on instance %s", instance);
instance = client.getInstance(instance.getId());
if (instance == null)
return false;
logger.trace("%s: looking for instance state %s: currently: %s", instance.getId(), String.format("%s or %s",
Instance.Status.ACTIVE, Instance.Status.FAILED), instance.getStatus());
return instance.getStatus() == Instance.Status.ACTIVE || instance.getStatus() == Instance.Status.FAILED;
}
}

View File

@ -51,8 +51,8 @@ public class InstanceRemovedOrNotFound implements Predicate<Instance> {
instance = client.getInstance(instance.getId()); instance = client.getInstance(instance.getId());
if (instance == null) if (instance == null)
return true; return true;
logger.trace("%s: looking for instance state %s: currently: %s", instance.getId(), logger.trace("%s: looking for instance state %s: currently: %s", instance.getId(), Instance.Status.REMOVED,
Instance.Status.REMOVED, instance.getStatus()); instance.getStatus());
return instance.getStatus() == Instance.Status.REMOVED; return instance.getStatus() == Instance.Status.REMOVED;
} }

View File

@ -35,6 +35,7 @@ import org.jclouds.http.filters.BasicAuthentication;
import org.jclouds.http.functions.ParseJson; import org.jclouds.http.functions.ParseJson;
import org.jclouds.http.functions.ParseSax; import org.jclouds.http.functions.ParseSax;
import org.jclouds.http.functions.ReleasePayloadAndReturn; import org.jclouds.http.functions.ReleasePayloadAndReturn;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.functions.GetFirstInstanceInList; import org.jclouds.ibmdev.functions.GetFirstInstanceInList;
import org.jclouds.ibmdev.functions.ParseAddressFromJson; import org.jclouds.ibmdev.functions.ParseAddressFromJson;
@ -78,7 +79,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -87,7 +88,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest); Iterables.getOnlyElement(httpRequest.getFilters()).filter(httpRequest);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image HTTP/1.1");
// for example, using basic authentication, we should get "only one" // for example, using basic authentication, we should get "only one"
// header // header
assertNonPayloadHeadersEqual(httpRequest, assertNonPayloadHeadersEqual(httpRequest,
@ -107,7 +108,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -124,7 +125,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -143,7 +144,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
Image.Visibility.PUBLIC); Image.Visibility.PUBLIC);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/images/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/image/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "visibility=PUBLIC", "application/x-www-form-urlencoded", false);
@ -160,7 +161,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -177,7 +178,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/requests/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/requests/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -194,7 +195,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -213,7 +214,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
123215235l)); 123215235l));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "expirationTime=123215235", "application/x-www-form-urlencoded", false);
@ -230,7 +231,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart", "application/x-www-form-urlencoded", false);
@ -248,7 +249,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
new RestartInstanceOptions().authorizePublicKey("keyName")); new RestartInstanceOptions().authorizePublicKey("keyName"));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "state=restart&keyName=keyName", "application/x-www-form-urlencoded", false);
@ -266,7 +267,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
"imageName", "imageDescription"); "imageName", "imageDescription");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName", assertPayloadEquals(httpRequest, "state=save&description=imageDescription&name=imageName",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -283,7 +284,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -300,7 +301,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -317,7 +318,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -334,7 +335,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key", "application/x-www-form-urlencoded", false);
@ -352,7 +353,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
"publicbits"); "publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "name=key&publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -370,7 +371,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
"publicbits"); "publicbits");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "publicKey=publicbits", "application/x-www-form-urlencoded", false);
@ -388,7 +389,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key", true); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "key", true);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"PUT https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/key HTTP/1.1"); "PUT https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/key HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "default=true", "application/x-www-form-urlencoded", false);
@ -405,7 +406,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/keys/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/keys/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -422,7 +423,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -439,7 +440,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -453,14 +454,14 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException { public void testCreateVolumeInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class, Method method = IBMDeveloperCloudAsyncClient.class.getMethod("createVolumeInLocation", String.class,
String.class, String.class, String.class); String.class, String.class, String.class, String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location", GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location",
"name", "format", "size"); "name", "format", "size", "offering");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size", assertPayloadEquals(httpRequest, "location=location&format=format&name=name&size=size&offeringID=offering",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseVolumeFromJson.class);
@ -478,7 +479,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
"22", "instanceType"); "22", "instanceType");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1&imageID=22&name=name&instanceType=instanceType", assertPayloadEquals(httpRequest, "location=1&imageID=22&name=name&instanceType=instanceType",
"application/x-www-form-urlencoded", false); "application/x-www-form-urlencoded", false);
@ -496,11 +497,11 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location", GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "location",
"name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO") "name", "22", "instanceType", new CreateInstanceOptions().attachIp("1").authorizePublicKey("MOO")
.mountVolume("2", "/mnt").configurationData( .mountVolume("2", "/mnt").configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", ImmutableMap.of("insight_admin_password", "myPassword1", "db2_admin_password", "myPassword2",
"myPassword2", "report_user_password", "myPassword3"))); "report_user_password", "myPassword3")));
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/instances HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/instances HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals( assertPayloadEquals(
httpRequest, httpRequest,
@ -520,7 +521,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/storage/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/storage/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -537,7 +538,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -554,7 +555,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/locations/1 HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/locations/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: text/xml\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -571,7 +572,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"GET https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1"); "GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -584,13 +585,14 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, IOException { public void testAllocateAddressInLocation() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("allocateAddressInLocation", String.class); Method method = IBMDeveloperCloudAsyncClient.class.getMethod("allocateAddressInLocation", String.class,
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); String.class);
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1", "offering");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"POST https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses HTTP/1.1"); "POST https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n"); assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, "location=1", "application/x-www-form-urlencoded", false); assertPayloadEquals(httpRequest, "location=1&offeringID=offering", "application/x-www-form-urlencoded", false);
assertResponseParserClassEquals(method, httpRequest, ParseAddressFromJson.class); assertResponseParserClassEquals(method, httpRequest, ParseAddressFromJson.class);
assertSaxResponseParserClassEquals(method, null); assertSaxResponseParserClassEquals(method, null);
@ -605,7 +607,7 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1"); GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method, "1");
assertRequestLineEquals(httpRequest, assertRequestLineEquals(httpRequest,
"DELETE https://www-180.ibm.com/cloud/enterprise/beta/api/rest/20090403/addresses/1 HTTP/1.1"); "DELETE https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/addresses/1 HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, ""); assertNonPayloadHeadersEqual(httpRequest, "");
assertPayloadEquals(httpRequest, null, null, false); assertPayloadEquals(httpRequest, null, null, false);
@ -617,6 +619,38 @@ public class IBMDeveloperCloudAsyncClientTest extends RestClientTest<IBMDevelope
} }
public void testListStorageOfferings() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listStorageOfferings");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/storage HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
}
public void testListAddressOfferings() throws SecurityException, NoSuchMethodException, IOException {
Method method = IBMDeveloperCloudAsyncClient.class.getMethod("listAddressOfferings");
GeneratedHttpRequest<IBMDeveloperCloudAsyncClient> httpRequest = processor.createRequest(method);
assertRequestLineEquals(httpRequest,
"GET https://www-147.ibm.com/computecloud/enterprise/api/rest/20100331/offerings/address HTTP/1.1");
assertNonPayloadHeadersEqual(httpRequest, "Accept: application/json\n");
assertPayloadEquals(httpRequest, null, null, false);
assertResponseParserClassEquals(method, httpRequest, UnwrapOnlyJsonValue.class);
assertSaxResponseParserClassEquals(method, null);
assertExceptionParserClassEquals(method, ReturnEmptySetOnNotFoundOr404.class);
checkFilters(httpRequest);
}
@Override @Override
protected void checkFilters(HttpRequest request) { protected void checkFilters(HttpRequest request) {
assertEquals(request.getFilters().size(), 1); assertEquals(request.getFilters().size(), 1);

View File

@ -24,11 +24,12 @@
package org.jclouds.ibmdev; package org.jclouds.ibmdev;
import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.filter;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.attachIp; import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.attachIp;
import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey; import static org.jclouds.ibmdev.options.CreateInstanceOptions.Builder.authorizePublicKey;
import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue;
import java.io.File; import java.io.File;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
@ -38,33 +39,49 @@ import java.util.Properties;
import java.util.Set; import java.util.Set;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.jclouds.domain.Credentials;
import org.jclouds.http.HttpResponseException; import org.jclouds.http.HttpResponseException;
import org.jclouds.http.handlers.BackoffLimitedRetryHandler;
import org.jclouds.ibmdev.domain.Address; import org.jclouds.ibmdev.domain.Address;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.domain.Instance; import org.jclouds.ibmdev.domain.Instance;
import org.jclouds.ibmdev.domain.InstanceType;
import org.jclouds.ibmdev.domain.Key; import org.jclouds.ibmdev.domain.Key;
import org.jclouds.ibmdev.domain.Location; import org.jclouds.ibmdev.domain.Location;
import org.jclouds.ibmdev.domain.Offering;
import org.jclouds.ibmdev.domain.StorageOffering;
import org.jclouds.ibmdev.domain.Volume; import org.jclouds.ibmdev.domain.Volume;
import org.jclouds.ibmdev.domain.Instance.Software; import org.jclouds.ibmdev.domain.Instance.Software;
import org.jclouds.ibmdev.domain.StorageOffering.Format;
import org.jclouds.ibmdev.predicates.AddressFree; import org.jclouds.ibmdev.predicates.AddressFree;
import org.jclouds.ibmdev.predicates.InstanceActive; import org.jclouds.ibmdev.predicates.InstanceActive;
import org.jclouds.ibmdev.predicates.InstanceActiveOrFailed;
import org.jclouds.ibmdev.predicates.InstanceRemovedOrNotFound; import org.jclouds.ibmdev.predicates.InstanceRemovedOrNotFound;
import org.jclouds.ibmdev.predicates.VolumeUnmounted; import org.jclouds.ibmdev.predicates.VolumeUnmounted;
import org.jclouds.logging.log4j.config.Log4JLoggingModule; import org.jclouds.logging.log4j.config.Log4JLoggingModule;
import org.jclouds.net.IPSocket;
import org.jclouds.predicates.RetryablePredicate; import org.jclouds.predicates.RetryablePredicate;
import org.jclouds.rest.RestContext; import org.jclouds.rest.RestContext;
import org.jclouds.rest.RestContextFactory; import org.jclouds.rest.RestContextFactory;
import org.jclouds.ssh.ExecResponse;
import org.jclouds.ssh.SshClient;
import org.jclouds.ssh.SshException;
import org.jclouds.ssh.jsch.JschSshClient;
import org.jclouds.ssh.jsch.predicates.InetSocketAddressConnect;
import org.testng.annotations.AfterTest; import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeGroups; import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.base.Charsets; import com.google.common.base.Charsets;
import com.google.common.base.Predicate; import com.google.common.base.Predicate;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables; import com.google.common.collect.Iterables;
import com.google.common.collect.Ordering;
import com.google.common.io.Files; import com.google.common.io.Files;
import com.google.inject.Module; import com.google.inject.Module;
import com.google.inject.internal.Sets;
/** /**
* Tests behavior of {@code IBMDeveloperCloudClient} * Tests behavior of {@code IBMDeveloperCloudClient}
@ -73,10 +90,15 @@ import com.google.inject.Module;
*/ */
@Test(groups = "live", testName = "ibmdevelopercloud.IBMDeveloperCloudClientLiveTest") @Test(groups = "live", testName = "ibmdevelopercloud.IBMDeveloperCloudClientLiveTest")
public class IBMDeveloperCloudClientLiveTest { public class IBMDeveloperCloudClientLiveTest {
private static final String OS = "Red Hat Enterprise Linux";
private static final String VERSION = "5.4";
private static final String PLATFORM = OS + "/" + VERSION;
private static final ImmutableSet<Software> SOFTWARE = ImmutableSet.<Software> of(new Software(OS, "OS", VERSION));
private static String FORMAT = "EXT3";
private static final ImmutableSet<Software> SOFTWARE = ImmutableSet.<Software> of(new Software(
"SUSE Linux Enterprise", "OS", "10 SP2"));
private static final String SIZE = "LARGE";
private IBMDeveloperCloudClient connection; private IBMDeveloperCloudClient connection;
private Location location; private Location location;
private Address ip; private Address ip;
@ -87,6 +109,10 @@ public class IBMDeveloperCloudClientLiveTest {
private Instance instance2; private Instance instance2;
private Instance instance; private Instance instance;
private RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> context; private RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> context;
private InstanceType instanceType;
private Image image;
private StorageOffering cheapestStorage;
private static final String TAG = System.getProperty("user.name"); private static final String TAG = System.getProperty("user.name");
@ -95,8 +121,7 @@ public class IBMDeveloperCloudClientLiveTest {
String endpoint = System.getProperty("jclouds.test.endpoint"); String endpoint = System.getProperty("jclouds.test.endpoint");
identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity"); identity = checkNotNull(System.getProperty("jclouds.test.identity"), "jclouds.test.identity");
String credential = checkNotNull(System.getProperty("jclouds.test.credential"), String credential = checkNotNull(System.getProperty("jclouds.test.credential"), "jclouds.test.credential");
"jclouds.test.credential");
Properties props = new Properties(); Properties props = new Properties();
if (endpoint != null) if (endpoint != null)
@ -137,9 +162,9 @@ public class IBMDeveloperCloudClientLiveTest {
} }
@Test @Test
public void testListInstancesFromRequestReturnsNull() throws Exception { public void testListInstancesFromRequestReturnsEmptySet() throws Exception {
Set<? extends Instance> response = connection.listInstancesFromRequest(Long.MAX_VALUE + ""); Set<? extends Instance> response = connection.listInstancesFromRequest(Long.MAX_VALUE + "");
assertNull(response); assertEquals(response.size(), 0);
} }
@Test @Test
@ -223,12 +248,8 @@ public class IBMDeveloperCloudClientLiveTest {
key = connection.getKey(TAG); key = connection.getKey(TAG);
for (String instanceId : key.getInstanceIds()) { for (String instanceId : key.getInstanceIds()) {
Instance instance = connection.getInstance(instanceId); Instance instance = connection.getInstance(instanceId);
System.out.println("deleting instance: " + instance); if (instance.getStatus() == Instance.Status.FAILED || instance.getStatus() == Instance.Status.ACTIVE) {
if (instance.getStatus() == Instance.Status.FAILED killInstance(instance.getId());
|| instance.getStatus() == Instance.Status.ACTIVE) {
connection.deleteInstance(instanceId);
assert new RetryablePredicate<Instance>(new InstanceRemovedOrNotFound(connection),
30, 2, TimeUnit.SECONDS).apply(instance) : instance;
} }
} }
} }
@ -237,15 +258,23 @@ public class IBMDeveloperCloudClientLiveTest {
assertNotNull(key.getLastModifiedTime()); assertNotNull(key.getLastModifiedTime());
} }
@Test(dependsOnMethods = "testGetLocation") @Test(dependsOnMethods = "resolveImageAndInstanceType")
public void testAllocateIpAddress() throws Exception { public void testAllocateIpAddress() throws Exception {
Offering offering = Iterables.find(connection.listAddressOfferings(), new Predicate<Offering>() {
@Override
public boolean apply(Offering arg0) {
return arg0.getLocation().equals(location.getId());
}
});
try { try {
ip = connection.allocateAddressInLocation(location.getId()); ip = connection.allocateAddressInLocation(location.getId(), offering.getId());
System.out.println(ip); System.out.println(ip);
assertEquals(ip.getIp(), null); assertEquals(ip.getIp(), null);
// wait up to 30 seconds for this to become "free" // wait up to 30 seconds for this to become "free"
new RetryablePredicate<Address>(new AddressFree(connection), 30, 2, TimeUnit.SECONDS) new RetryablePredicate<Address>(new AddressFree(connection), 30, 2, TimeUnit.SECONDS).apply(ip);
.apply(ip);
refreshIpAndReturnAllAddresses(); refreshIpAndReturnAllAddresses();
assertEquals(ip.getInstanceId(), null); assertEquals(ip.getInstanceId(), null);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
@ -271,14 +300,44 @@ public class IBMDeveloperCloudClientLiveTest {
} }
@Test(dependsOnMethods = "testGetLocation") @Test(dependsOnMethods = "testGetLocation")
public void testResolveVolumeOffering() throws Exception {
Ordering<StorageOffering> cheapestOrdering = new Ordering<StorageOffering>() {
public int compare(StorageOffering left, StorageOffering right) {
return ComparisonChain.start().compare(left.getPrice().getRate(), right.getPrice().getRate()).result();
}
}.reverse();
Iterable<? extends StorageOffering> storageOfferingsThatAreInOurLocationAndCorrectFormat = filter(connection
.listStorageOfferings(), new Predicate<StorageOffering>() {
@Override
public boolean apply(StorageOffering arg0) {
return arg0.getLocation().equals(location.getId())
&& Iterables.any(arg0.getFormats(), new Predicate<StorageOffering.Format>() {
@Override
public boolean apply(Format arg0) {
return arg0.getId().equals(FORMAT);
}
});
}
});
cheapestStorage = cheapestOrdering.max(storageOfferingsThatAreInOurLocationAndCorrectFormat);
System.out.println(cheapestStorage);
}
@Test(dependsOnMethods = "testResolveVolumeOffering")
public void testCreateVolume() throws Exception { public void testCreateVolume() throws Exception {
try { try {
volume = connection.createVolumeInLocation(location.getId(), TAG, "EXT3", "SMALL"); volume = connection.createVolumeInLocation(location.getId(), TAG, FORMAT, cheapestStorage.getName(),
cheapestStorage.getId());
// wait up to 5 minutes for this to become "unmounted" // wait up to 5 minutes for this to become "unmounted"
assert new RetryablePredicate<Volume>(new VolumeUnmounted(connection), 300, 5, assert new RetryablePredicate<Volume>(new VolumeUnmounted(connection), 300, 5, TimeUnit.SECONDS).apply(volume);
TimeUnit.SECONDS).apply(volume);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
if (HttpResponseException.class.cast(e.getCause()).getResponse().getStatusCode() == 409) { int code = HttpResponseException.class.cast(e.getCause()).getResponse().getStatusCode();
if (code == 409 || code == 500) {
Set<? extends Volume> volumes = connection.listVolumes(); Set<? extends Volume> volumes = connection.listVolumes();
try { try {
volume = Iterables.find(volumes, new Predicate<Volume>() { volume = Iterables.find(volumes, new Predicate<Volume>() {
@ -290,7 +349,7 @@ public class IBMDeveloperCloudClientLiveTest {
}); });
} catch (NoSuchElementException ex) { } catch (NoSuchElementException ex) {
throw new RuntimeException("no unmounted volumes in: " + volumes, e); killInstance(TAG + 1);
} }
} else { } else {
throw e; throw e;
@ -315,32 +374,64 @@ public class IBMDeveloperCloudClientLiveTest {
assert (allVolumes.contains(volume)) : String.format("volume %s not in %s", volume, volume); assert (allVolumes.contains(volume)) : String.format("volume %s not in %s", volume, volume);
} }
private static final String IMAGE_ID = "11";// Rational Insight @Test(dependsOnMethods = "testGetLocation")
public void resolveImageAndInstanceType() throws Exception {
Iterable<? extends Image> imagesThatAreInOurLocationAndNotBYOL = filter(connection.listImages(),
new Predicate<Image>() {
@Override
public boolean apply(Image arg0) {
return arg0.getLocation().equals(location.getId()) && arg0.getPlatform().equals(PLATFORM)
&& !arg0.getName().contains("BYOL") && !arg0.getName().contains("PAYG");
}
});
@Test(dependsOnMethods = { "testAddPublicKey" }) Ordering<InstanceType> cheapestOrdering = new Ordering<InstanceType>() {
public int compare(InstanceType left, InstanceType right) {
return ComparisonChain.start().compare(left.getPrice().getRate(), right.getPrice().getRate()).result();
}
}.reverse();
Set<InstanceType> instanceTypes = Sets.newLinkedHashSet();
for (Image image : imagesThatAreInOurLocationAndNotBYOL)
Iterables.addAll(instanceTypes, image.getSupportedInstanceTypes());
instanceType = cheapestOrdering.max(instanceTypes);
final InstanceType cheapestInstanceType = instanceType;
System.err.println(cheapestInstanceType);
image = Iterables.find(imagesThatAreInOurLocationAndNotBYOL, new Predicate<Image>() {
@Override
public boolean apply(Image arg0) {
return arg0.getSupportedInstanceTypes().contains(cheapestInstanceType);
}
});
System.err.println(image);
connection.getManifest(connection.getImage(image.getId()).getManifest());
connection.getManifest(connection.getImage(image.getId()).getDocumentation());
}
@Test(dependsOnMethods = { "testAddPublicKey", "resolveImageAndInstanceType" })
public void testCreateInstance() throws Exception { public void testCreateInstance() throws Exception {
killInstance(TAG); killInstance(TAG);
System.err.println(connection.getManifest(connection.getImage(IMAGE_ID).getManifest())); instance = connection.createInstanceInLocation(location.getId(), TAG, image.getId(), instanceType.getId(),
System.err.println(connection.getManifest(connection.getImage(IMAGE_ID).getDocumentation())); authorizePublicKey(key.getName()));
instance = connection.createInstanceInLocation(location.getId(), TAG, IMAGE_ID, SIZE,
authorizePublicKey(key.getName()).configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1",
"db2_admin_password", "myPassword2", "report_user_password",
"myPassword3")));
assertBeginState(instance, TAG); assertBeginState(instance, TAG);
assertIpHostNullAndStatusNEW(instance);
blockUntilRunning(instance); blockUntilRunning(instance);
assertRunning(instance, TAG); instance = assertRunning(instance, TAG);
sshAndDf(new IPSocket(instance.getIp(), 22), new Credentials("idcuser", key.getKeyMaterial()));
} }
private void killInstance(final String nameToKill) { private void killInstance(final String nameToKill) {
Set<? extends Instance> instances = connection.listInstances(); Set<? extends Instance> instances = connection.listInstances();
try { try {
instance = Iterables.find(instances, new Predicate<Instance>() { Instance instance = Iterables.find(instances, new Predicate<Instance>() {
@Override @Override
public boolean apply(Instance input) { public boolean apply(Instance input) {
@ -348,12 +439,22 @@ public class IBMDeveloperCloudClientLiveTest {
} }
}); });
if (instance.getStatus() != Instance.Status.DEPROVISIONING
&& instance.getStatus() != Instance.Status.DEPROVISION_PENDING) {
System.out.println("deleting instance: " + instance);
int timeout = (instance.getStatus() == Instance.Status.NEW || instance.getStatus() == Instance.Status.PROVISIONING) ? 300
: 30;
assert new RetryablePredicate<Instance>(new InstanceActiveOrFailed(connection), timeout, 2,
TimeUnit.SECONDS).apply(instance) : instance;
connection.deleteInstance(instance.getId()); connection.deleteInstance(instance.getId());
}
assert new RetryablePredicate<Instance>(new InstanceRemovedOrNotFound(connection), 120, 2, TimeUnit.SECONDS)
.apply(instance) : instance;
} catch (NoSuchElementException ex) { } catch (NoSuchElementException ex) {
} }
} }
private void assertRunning(Instance instance, String name) throws AssertionError { private Instance assertRunning(Instance instance, String name) throws AssertionError {
instance = connection.getInstance(instance.getId()); instance = connection.getInstance(instance.getId());
try { try {
@ -366,25 +467,26 @@ public class IBMDeveloperCloudClientLiveTest {
System.err.println(instance); System.err.println(instance);
throw e; throw e;
} }
System.err.println("RUNNING: " + instance);
return instance;
} }
private void blockUntilRunning(Instance instance) { private void blockUntilRunning(Instance instance) {
long start = System.currentTimeMillis(); long start = System.currentTimeMillis();
assert new RetryablePredicate<Instance>(new InstanceActive(connection), 15 * 60 * 1000) assert new RetryablePredicate<Instance>(new InstanceActive(connection), 15 * 60 * 1000).apply(instance) : connection
.apply(instance) : connection.getInstance(instance.getId()); .getInstance(instance.getId());
System.out.println(((System.currentTimeMillis() - start) / 1000) + " seconds"); System.out.println(((System.currentTimeMillis() - start) / 1000) + " seconds");
} }
private void assertBeginState(Instance instance, String name) throws AssertionError { private void assertBeginState(Instance instance, String name) throws AssertionError {
try { try {
assertIpHostAndStatusNEW(instance);
assertConsistent(instance, name); assertConsistent(instance, name);
} catch (NullPointerException e) { } catch (NullPointerException e) {
System.err.println(instance); System.err.println(instance);
throw e; throw e;
} catch (AssertionError e) { } catch (AssertionError e) {
System.err.println(instance); killInstance(instance.getId());
throw e; throw e;
} }
} }
@ -392,9 +494,9 @@ public class IBMDeveloperCloudClientLiveTest {
private void assertConsistent(Instance instance, String name) { private void assertConsistent(Instance instance, String name) {
assertNotNull(instance.getId()); assertNotNull(instance.getId());
assertEquals(instance.getName(), name); assertEquals(instance.getName(), name);
assertEquals(instance.getInstanceType(), SIZE); assertEquals(instance.getInstanceType(), instanceType.getId());
assertEquals(instance.getLocation(), location.getId()); assertEquals(instance.getLocation(), location.getId());
assertEquals(instance.getImageId(), IMAGE_ID); assertEquals(instance.getImageId(), image.getId());
assertEquals(instance.getSoftware(), SOFTWARE); assertEquals(instance.getSoftware(), SOFTWARE);
assertEquals(instance.getKeyName(), key.getName()); assertEquals(instance.getKeyName(), key.getName());
assertNotNull(instance.getLaunchTime()); assertNotNull(instance.getLaunchTime());
@ -405,39 +507,37 @@ public class IBMDeveloperCloudClientLiveTest {
assertNotNull(instance.getRequestId()); assertNotNull(instance.getRequestId());
} }
private void assertIpHostAndStatusNEW(Instance instance) { private void assertIpHostNullAndStatusNEW(Instance instance) {
assertEquals(instance.getIp(), null); assertEquals(instance.getIp(), null);
assertEquals(instance.getHostname(), null); assertEquals(instance.getHostname(), null);
assertEquals(instance.getStatus(), Instance.Status.NEW); assertEquals(instance.getStatus(), Instance.Status.NEW);
} }
private void assertIpHostAndStatusNEW(Instance instance) {
assertNotNull(instance.getIp());
assertNotNull(instance.getHostname());
assertEquals(instance.getStatus(), Instance.Status.NEW);
}
private void assertIpHostAndStatusACTIVE(Instance instance) { private void assertIpHostAndStatusACTIVE(Instance instance) {
assertNotNull(instance.getIp()); assertNotNull(instance.getIp());
assertNotNull(instance.getHostname()); assertNotNull(instance.getHostname());
assertEquals(instance.getStatus(), Instance.Status.ACTIVE); assertEquals(instance.getStatus(), Instance.Status.ACTIVE);
} }
/** @Test(dependsOnMethods = { "testAddPublicKey", "testAllocateIpAddress", "testCreateVolume",
* cannot run an instance due to 500 errors: "resolveImageAndInstanceType" })
* public void testCreateInstanceWithIpAndVolume() throws Exception {
* http://www-180.ibm.com/cloud/enterprise/beta/ram/community/discussionTopic .faces?guid={
* DA689AEE-783C-6FE7-6F9F-DFEE9763F806}&v=1&fid=1068&tid=1523#topic
*/
@Test(dependsOnMethods = { "testAddPublicKey", "testAllocateIpAddress", "testCreateVolume" })
public void testCreateInstanceWithVolume() throws Exception {
String name = TAG + "1"; String name = TAG + "1";
killInstance(name); killInstance(name);
instance2 = connection.createInstanceInLocation(location.getId(), name, IMAGE_ID, SIZE, instance2 = connection.createInstanceInLocation(location.getId(), name, image.getId(), instanceType.getId(),
attachIp(ip.getId()).authorizePublicKey(key.getName()).mountVolume(volume.getId(), attachIp(ip.getId()).authorizePublicKey(key.getName()).mountVolume(volume.getId(), "/mnt"));
"/mnt").configurationData(
ImmutableMap.of("insight_admin_password", "myPassword1",
"db2_admin_password", "myPassword2", "report_user_password",
"myPassword3")));
assertBeginState(instance2, name); assertBeginState(instance2, name);
assertIpHostAndStatusNEW(instance2);
blockUntilRunning(instance2); blockUntilRunning(instance2);
assertRunning(instance2, name); instance2 = assertRunning(instance2, name);
volume = connection.getVolume(volume.getId()); volume = connection.getVolume(volume.getId());
assertEquals(volume.getInstanceId(), instance2.getId()); assertEquals(volume.getInstanceId(), instance2.getId());
@ -445,7 +545,7 @@ public class IBMDeveloperCloudClientLiveTest {
refreshIpAndReturnAllAddresses(); refreshIpAndReturnAllAddresses();
assertEquals(ip.getInstanceId(), instance2.getId()); assertEquals(ip.getInstanceId(), instance2.getId());
assertEquals(ip.getIp(), instance2.getIp()); assertEquals(ip.getIp(), instance2.getIp());
sshAndDf(new IPSocket(instance2.getIp(), 22), new Credentials("idcuser", keyPair.get("private")));
} }
private Set<? extends Address> refreshIpAndReturnAllAddresses() { private Set<? extends Address> refreshIpAndReturnAllAddresses() {
@ -497,18 +597,53 @@ public class IBMDeveloperCloudClientLiveTest {
} }
} }
private void sshAndDf(IPSocket socket, Credentials credentials) throws IOException {
for (int i = 0; i < 5; i++) {// retry loop TODO replace with predicate.
try {
_sshAndDf(socket, credentials);
return;
} catch (SshException e) {
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e1) {
}
continue;
}
}
}
private void _sshAndDf(IPSocket socket, Credentials credentials) {
RetryablePredicate<IPSocket> socketOpen = new RetryablePredicate<IPSocket>(new InetSocketAddressConnect(), 180,
5, TimeUnit.SECONDS);
socketOpen.apply(socket);
SshClient ssh = new JschSshClient(new BackoffLimitedRetryHandler(), socket, 60000, credentials.identity, null,
credentials.credential.getBytes());
try {
ssh.connect();
ExecResponse hello = ssh.exec("echo hello");
assertEquals(hello.getOutput().trim(), "hello");
ExecResponse exec = ssh.exec("df");
assertTrue(exec.getOutput().contains("Filesystem"),
"The output should've contained filesystem information, but it didn't. Output: " + exec);
} finally {
if (ssh != null)
ssh.disconnect();
}
}
@BeforeGroups(groups = { "live" }) @BeforeGroups(groups = { "live" })
protected void setupKeyPair() throws FileNotFoundException, IOException { protected void setupKeyPair() throws FileNotFoundException, IOException {
String secretKeyFile; String secretKeyFile;
try { try {
secretKeyFile = checkNotNull(System.getProperty("jclouds.test.ssh.keyfile"), secretKeyFile = checkNotNull(System.getProperty("jclouds.test.ssh.keyfile"), "jclouds.test.ssh.keyfile");
"jclouds.test.ssh.keyfile");
} catch (NullPointerException e) { } catch (NullPointerException e) {
secretKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa"; secretKeyFile = System.getProperty("user.home") + "/.ssh/id_rsa";
} }
String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8); String secret = Files.toString(new File(secretKeyFile), Charsets.UTF_8);
assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret; assert secret.startsWith("-----BEGIN RSA PRIVATE KEY-----") : "invalid key:\n" + secret;
keyPair = ImmutableMap.<String, String> of("private", secret, "public", Files.toString( keyPair = ImmutableMap.<String, String> of("private", secret, "public", Files.toString(new File(secretKeyFile
new File(secretKeyFile + ".pub"), Charsets.UTF_8)); + ".pub"), Charsets.UTF_8));
} }
} }

View File

@ -0,0 +1,78 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.compute;
import static org.testng.Assert.assertEquals;
import org.jclouds.compute.BaseComputeServiceLiveTest;
import org.jclouds.compute.ComputeServiceContextFactory;
import org.jclouds.compute.domain.Architecture;
import org.jclouds.compute.domain.ComputeMetadata;
import org.jclouds.compute.domain.ComputeType;
import org.jclouds.compute.domain.OsFamily;
import org.jclouds.compute.domain.Template;
import org.jclouds.ibmdev.IBMDeveloperCloudAsyncClient;
import org.jclouds.ibmdev.IBMDeveloperCloudClient;
import org.jclouds.rest.RestContext;
import org.jclouds.ssh.jsch.config.JschSshClientModule;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* @author Adrian Cole
*/
@Test(groups = "live", enabled = false, sequential = true, testName = "ibmdevelopercloud.IBMDeveloperCloudComputeServiceLiveTest")
public class IBMDeveloperCloudComputeServiceLiveTestDisabled extends BaseComputeServiceLiveTest {
@BeforeClass
@Override
public void setServiceDefaults() {
provider = "ibmdev";
}
@Test
public void testTemplateBuilder() {
Template defaultTemplate = client.templateBuilder().build();
assertEquals(defaultTemplate.getImage().getArchitecture(), Architecture.X86_32);
assertEquals(defaultTemplate.getImage().getOsFamily(), OsFamily.RHEL);
assertEquals(defaultTemplate.getLocation().getId(), "1");
assertEquals(defaultTemplate.getSize().getCores(), 2.0d);
}
@Override
public void testListNodes() throws Exception {
for (ComputeMetadata node : client.listNodes()) {
assert node.getProviderId() != null;
// assert node.getLocation() != null;
assertEquals(node.getType(), ComputeType.NODE);
}
}
@Override
protected JschSshClientModule getSshModule() {
return new JschSshClientModule();
}
public void testAssignability() throws Exception {
@SuppressWarnings("unused")
RestContext<IBMDeveloperCloudClient, IBMDeveloperCloudAsyncClient> tmContext = new ComputeServiceContextFactory()
.createContext(provider, identity, credential).getProviderSpecificContext();
}
}

View File

@ -29,6 +29,8 @@ import org.jclouds.http.HttpUtils;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule; import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.domain.InstanceType;
import org.jclouds.ibmdev.domain.Price;
import org.jclouds.ibmdev.domain.Image.Visibility; import org.jclouds.ibmdev.domain.Image.Visibility;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
@ -50,37 +52,33 @@ public class ParseImageFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule(), Injector injector = Guice.createInjector(new ParserModule(), new IBMDeveloperCloudParserModule());
new IBMDeveloperCloudParserModule());
handler = injector.getInstance(ParseImageFromJson.class); handler = injector.getInstance(ParseImageFromJson.class);
} }
public void test() { public void test() {
Image image = new Image(); Image image = new Image(
image.setName("Rational Requirements Composer"); "SUSE Linux Enterprise Server 11 for x86",
image HttpUtils
.setManifest(HttpUtils .createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml"),
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/parameters.xml")); 1,
image.setState(1); Visibility.PUBLIC,
image.setVisibility(Visibility.PUBLIC); "SYSTEM",
image.setOwner("mutdosch@us.ibm.com"); "SUSE Linux Enterprise Server/11",
image.setArchitecture("i386"); new Date(1216944000000l),
image.setPlatform("Redhat Enterprise Linux (32-bit)/5.4"); "41",
image.setCreatedTime(new Date(1265647398000l)); ImmutableSet.<InstanceType> of(new InstanceType("Bronze 32 bit", new Price(0.17, "UHR ", "897", null,
image.setLocation("1"); "USD", 1), "BRZ32.1/2048/175"), new InstanceType("Gold 32 bit", new Price(0.41, "UHR ", "897", null,
image.setSupportedInstanceTypes(ImmutableSet.of("LARGE", "MEDIUM")); "USD", 1), "GLD32.4/4096/350"), new InstanceType("Silver 32 bit", new Price(0.265, "UHR ", "897",
// image.setProductCodes(); null, "USD", 1), "SLV32.2/4096/350")),
image ImmutableSet.<String> of("ifeE7VOzRG6SGvoDlRPTQw"),
.setDocumentation(HttpUtils HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/GettingStarted.html")); .createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html"),
image.setId("10005598"); "20001150", "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing");
image
.setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle.");
Image compare = handler.apply(new HttpResponse(200, "ok", Payloads Image compare = handler.apply(new HttpResponse(200, "ok", Payloads
.newInputStreamPayload(ParseImageFromJsonTest.class .newInputStreamPayload(ParseImageFromJsonTest.class.getResourceAsStream("/image.json"))));
.getResourceAsStream("/image.json"))));
assertEquals(compare, image); assertEquals(compare, image);
} }
} }

View File

@ -28,6 +28,9 @@ import org.jclouds.http.HttpUtils;
import org.jclouds.http.functions.config.ParserModule; import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule; import org.jclouds.ibmdev.config.IBMDeveloperCloudParserModule;
import org.jclouds.ibmdev.domain.Image; import org.jclouds.ibmdev.domain.Image;
import org.jclouds.ibmdev.domain.InstanceType;
import org.jclouds.ibmdev.domain.Price;
import org.jclouds.ibmdev.domain.Image.Visibility;
import org.jclouds.io.Payloads; import org.jclouds.io.Payloads;
import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
@ -48,61 +51,32 @@ public class ParseImagesFromJsonTest {
@BeforeTest @BeforeTest
protected void setUpInjector() throws IOException { protected void setUpInjector() throws IOException {
Injector injector = Guice.createInjector(new ParserModule(), Injector injector = Guice.createInjector(new ParserModule(), new IBMDeveloperCloudParserModule());
new IBMDeveloperCloudParserModule());
handler = injector.getInstance(ParseImagesFromJson.class); handler = injector.getInstance(ParseImagesFromJson.class);
} }
public void test() { public void test() {
Image image1 = new Image(); Image image1 = new Image(
"SUSE Linux Enterprise Server 11 for x86",
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml"),
1,
Visibility.PUBLIC,
"SYSTEM",
"SUSE Linux Enterprise Server/11",
new Date(1216944000000l),
"41",
ImmutableSet.<InstanceType> of(new InstanceType("Bronze 32 bit", new Price(0.17, "UHR ", "897", null,
"USD", 1), "BRZ32.1/2048/175"), new InstanceType("Gold 32 bit", new Price(0.41, "UHR ", "897", null,
"USD", 1), "GLD32.4/4096/350"), new InstanceType("Silver 32 bit", new Price(0.265, "UHR ", "897",
null, "USD", 1), "SLV32.2/4096/350")),
ImmutableSet.<String> of("ifeE7VOzRG6SGvoDlRPTQw"),
HttpUtils
.createUri("https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html"),
"20001150", "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing");
image1.setName("Rational Build Forge Agent"); Set<? extends Image> compare = handler.apply(new HttpResponse(200, "ok", Payloads
image1 .newInputStreamPayload(ParseImagesFromJsonTest.class.getResourceAsStream("/images.json"))));
.setManifest(HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/parameters.xml"));
image1.setState(1);
image1.setVisibility(Image.Visibility.PUBLIC);
image1.setOwner("SYSTEM");
image1.setArchitecture("i386");
image1.setPlatform("SUSE Linux Enterprise/10 SP2");
image1.setCreatedTime(new Date(1240632000000l));
image1.setLocation("1");
image1.setSupportedInstanceTypes(ImmutableSet.of("SMALL", "MEDIUM",
"LARGE"));
image1.setProductCodes(ImmutableSet
.of("fd2d0478b132490897526b9b4433a334"));
image1
.setDocumentation(HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/GettingStarted.html"));
image1.setId("2");
image1
.setDescription("Rational Build Forge provides an adaptive process execution framework that automates, orchestrates, manages, and tracks all the processes between each handoff within the assembly line of software development, creating an automated software factory.");
Image image2 = new Image();
image2.setName("Rational Requirements Composer");
image2
.setManifest(HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/parameters.xml"));
image2.setState(1);
image2.setVisibility(Image.Visibility.PUBLIC);
image2.setOwner("mutdosch@us.ibm.com");
image2.setArchitecture("i386");
image2.setPlatform("Redhat Enterprise Linux (32-bit)/5.4");
image2.setCreatedTime(new Date(1265647398869l));
image2.setLocation("1");
image2.setSupportedInstanceTypes(ImmutableSet.of("LARGE", "MEDIUM"));
// image.setProductCodes();
image2
.setDocumentation(HttpUtils
.createUri("https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/GettingStarted.html"));
image2.setId("10005598");
image2
.setDescription("Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle.");
Set<? extends Image> compare = handler.apply(new HttpResponse(200, "ok",
Payloads.newInputStreamPayload(ParseImagesFromJsonTest.class
.getResourceAsStream("/images.json"))));
assert (compare.contains(image1)); assert (compare.contains(image1));
assert (compare.contains(image2));
} }
} }

View File

@ -19,6 +19,8 @@
package org.jclouds.ibmdev.functions; package org.jclouds.ibmdev.functions;
import static org.testng.Assert.assertEquals;
import java.io.IOException; import java.io.IOException;
import java.util.Date; import java.util.Date;
import java.util.Set; import java.util.Set;
@ -32,6 +34,7 @@ import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet; import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.inject.Guice; import com.google.inject.Guice;
import com.google.inject.Injector; import com.google.inject.Injector;
@ -58,23 +61,17 @@ public class ParseInstancesFromJsonTest {
} }
public void test() { public void test() {
Instance instance1 = new Instance(new Date(1260472231726l), ImmutableSet Instance instance1 = new Instance(new Date(1260472231726l), ImmutableSet.of(new Software("SUSE Linux Enterprise",
.of(new Software("SUSE Linux Enterprise", "OS", "10 SP2")), "OS", "10 SP2")), "129.33.197.78", "7430", "DEFAULT", "ABC", "MEDIUM", 5, "aadelucc@us.ibm.com",
"129.33.197.78", "7430", "DEFAULT", "ABC", "MEDIUM", 5, "vm723.developer.ihost.com", "1", "3", ImmutableSet.<String> of(), "ABC", "7430", new Date(1263064240837l));
"aadelucc@us.ibm.com", "vm723.developer.ihost.com", "1", "3",
ImmutableSet.<String> of(), "ABC", "7430", new Date(1263064240837l));
Instance instance2 = new Instance(new Date(1260472231727l), ImmutableSet Instance instance2 = new Instance(new Date(1260472231727l), ImmutableSet.of(new Software("SUSE Linux Enterprise",
.of(new Software("SUSE Linux Enterprise", "OS", "10 SP3")), "OS", "10 SP3")), null, "7431", "DEFAULT", "ABC", "MEDIUM", 1, "aadelucc@us.ibm.com", null, "2", "4",
"129.33.197.79", "7431", "DEFAULT", "ABC", "MEDIUM", 6,
"aadelucc@us.ibm.com", "vm723.developer.ihost.com", "2", "4",
ImmutableSet.<String> of(), "ABC", "7431", new Date(1263064240838l)); ImmutableSet.<String> of(), "ABC", "7431", new Date(1263064240838l));
Set<? extends Instance> compare = handler.apply(new HttpResponse(200, Set<? extends Instance> compare = handler.apply(new HttpResponse(200, "ok", Payloads
"ok", Payloads .newInputStreamPayload(ParseInstancesFromJsonTest.class.getResourceAsStream("/instances.json"))));
.newInputStreamPayload(ParseInstancesFromJsonTest.class assertEquals(Iterables.get(compare, 1), instance1);
.getResourceAsStream("/instances.json")))); assertEquals(Iterables.get(compare, 0), instance2);
assert (compare.contains(instance1));
assert (compare.contains(instance2));
} }
} }

View File

@ -0,0 +1,84 @@
/**
*
* Copyright (C) 2010 Cloud Conscious, LLC. <info@cloudconscious.com>
*
* ====================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ====================================================================
*/
package org.jclouds.ibmdev.functions;
import static org.testng.Assert.assertEquals;
import java.io.IOException;
import java.util.Date;
import java.util.Set;
import org.jclouds.http.HttpResponse;
import org.jclouds.http.functions.UnwrapOnlyJsonValue;
import org.jclouds.http.functions.config.ParserModule;
import org.jclouds.ibmdev.domain.Price;
import org.jclouds.ibmdev.domain.StorageOffering;
import org.jclouds.ibmdev.domain.StorageOffering.Format;
import org.jclouds.io.Payloads;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.TypeLiteral;
/**
* Tests behavior of {@code ParseStorageOfferingsFromJson}
*
* @author Adrian Cole
*/
@Test(groups = "unit", sequential = true, testName = "ibmdev.ParseStorageOfferingsFromJsonTest")
public class ParseStorageOfferingsFromJsonTest {
private UnwrapOnlyJsonValue<Set<StorageOffering>> handler;
private Injector injector;
@BeforeTest
protected void setUpInjector() throws IOException {
injector = Guice.createInjector(new ParserModule() {
@Override
protected void configure() {
bind(DateAdapter.class).to(LongDateAdapter.class);
super.configure();
}
});
handler = injector.getInstance(Key.get(new TypeLiteral<UnwrapOnlyJsonValue<Set<StorageOffering>>>() {
}));
}
@Test
public void testDeserialize() throws IOException {
Set<StorageOffering> compare = ImmutableSet.of(//
new StorageOffering("41", new Price(0.039, "UHR", "897", new Date(1279497600000l), "USD", 1), 256, "Small",
"20001208", ImmutableSet.of(new Format("ext3", "EXT3"))),//
new StorageOffering("41", new Price(0.312, "UHR", "897", new Date(1279497600000l), "USD", 1), 2048,
"Large", "20001210", ImmutableSet.of(new Format("ext3", "EXT3"))),//
new StorageOffering("41", new Price(0.078, "UHR", "897", new Date(1279497600000l), "USD", 1), 512,
"Medium", "20001209", ImmutableSet.of(new Format("ext3", "EXT3")))//
);
Set<StorageOffering> expected = handler.apply(new HttpResponse(200, "ok", Payloads
.newPayload(ParseStorageOfferingsFromJsonTest.class.getResourceAsStream("/storage-offerings.json"))));
assertEquals(compare, expected);
}
}

View File

@ -1,15 +1,50 @@
{"name":"Rational Requirements Composer", {
"manifest":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/parameters.xml", "name": "SUSE Linux Enterprise Server 11 for x86",
"manifest": "https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml",
"state": 1, "state": 1,
"visibility": "PUBLIC", "visibility": "PUBLIC",
"owner":"mutdosch@us.ibm.com", "owner": "SYSTEM",
"architecture":"i386", "platform": "SUSE Linux Enterprise Server/11",
"platform":"Redhat Enterprise Linux (32-bit)/5.4", "createdTime": 1216944000000,
"createdTime":1265647398000, "location": "41",
"location":"1", "supportedInstanceTypes": [{
"supportedInstanceTypes":["MEDIUM","LARGE"], "label": "Bronze 32 bit",
"productCodes":[""], "price": {
"documentation":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/GettingStarted.html", "rate": 0.17,
"id":"10005598", "unitOfMeasure": "UHR ",
"description":"Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle." "countryCode": "897",
"effectiveDate": -1,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"id": "BRZ32.1/2048/175"
},
{
"label": "Gold 32 bit",
"price": {
"rate": 0.41,
"unitOfMeasure": "UHR ",
"countryCode": "897",
"effectiveDate": -1,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"id": "GLD32.4/4096/350"
},
{
"label": "Silver 32 bit",
"price": {
"rate": 0.265,
"unitOfMeasure": "UHR ",
"countryCode": "897",
"effectiveDate": -1,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"id": "SLV32.2/4096/350"
}],
"productCodes": ["ifeE7VOzRG6SGvoDlRPTQw"],
"documentation": "https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html",
"id": "20001150",
"description": "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing"
} }

View File

@ -1,34 +1,54 @@
{"images": {"images":
[ [{
{ "name": "Rational Build Forge Agent",
"manifest":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/parameters.xml", "name": "SUSE Linux Enterprise Server 11 for x86",
"manifest": "https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/parameters.xml",
"state": 1, "state": 1,
"visibility": "PUBLIC", "visibility": "PUBLIC",
"owner": "SYSTEM", "owner": "SYSTEM",
"architecture":"i386", "platform": "SUSE Linux Enterprise Server/11",
"platform":"SUSE Linux Enterprise/10 SP2", "createdTime": 1216944000000,
"createdTime":1240632000000, "location": "41",
"location":"1", "supportedInstanceTypes": [{
"supportedInstanceTypes":["SMALL","MEDIUM","LARGE"], "label": "Bronze 32 bit",
"productCodes":["fd2d0478b132490897526b9b4433a334"], "price": {
"documentation":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{A233F5A0-05A5-F21D-3E92-3793B722DFBD}/1.0/GettingStarted.html", "rate": 0.17,
"id":"2", "unitOfMeasure": "UHR ",
"description":"Rational Build Forge provides an adaptive process execution framework that automates, orchestrates, manages, and tracks all the processes between each handoff within the assembly line of software development, creating an automated software factory." "countryCode": "897",
"effectiveDate": -1,
"currencyCode": "USD",
"pricePerQuantity": 1
}, },
{ "name":"Rational Requirements Composer", "id": "BRZ32.1/2048/175"
"manifest":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/parameters.xml", },
"state":1, {
"visibility":"PUBLIC", "label": "Gold 32 bit",
"owner":"mutdosch@us.ibm.com", "price": {
"architecture":"i386", "rate": 0.41,
"platform":"Redhat Enterprise Linux (32-bit)/5.4", "unitOfMeasure": "UHR ",
"createdTime":1265647398869, "countryCode": "897",
"location":"1", "effectiveDate": -1,
"supportedInstanceTypes":["MEDIUM","LARGE"], "currencyCode": "USD",
"productCodes":[""], "pricePerQuantity": 1
"documentation":"https://www-180.ibm.com/cloud/enterprise/beta/ram.ws/RAMSecure/artifact/{28C7B870-2C0A-003F-F886-B89F5B413B77}/1.0/GettingStarted.html", },
"id":"10005598", "id": "GLD32.4/4096/350"
"description":"Rational Requirements Composer helps teams define and use requirements effectively across the project lifecycle." },
{
"label": "Silver 32 bit",
"price": {
"rate": 0.265,
"unitOfMeasure": "UHR ",
"countryCode": "897",
"effectiveDate": -1,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"id": "SLV32.2/4096/350"
}],
"productCodes": ["ifeE7VOzRG6SGvoDlRPTQw"],
"documentation": "https://www-147.ibm.com/cloud/enterprise/ram.ws/RAMSecure/artifact/{F006D027-02CC-9D08-D389-6C729D939D44}/1.0/GettingStarted.html",
"id": "20001150",
"description": "SUSE Linux Enterprise Server 11 for x86 Base OS 32-bit with pay for use licensing"
} }
] ]
} }

View File

@ -27,14 +27,14 @@
[ [
{ "version":"10 SP3", "type":"OS", "name":"SUSE Linux Enterprise" } { "version":"10 SP3", "type":"OS", "name":"SUSE Linux Enterprise" }
], ],
"ip":"129.33.197.79", "ip":" ",
"requestId":"7431", "requestId":"7431",
"keyName":"DEFAULT", "keyName":"DEFAULT",
"name":"ABC", "name":"ABC",
"instanceType":"MEDIUM", "instanceType":"MEDIUM",
"status":6, "status":1,
"owner":"aadelucc@us.ibm.com", "owner":"aadelucc@us.ibm.com",
"hostname":"vm723.developer.ihost.com", "hostname":" ",
"location":"2", "location":"2",
"imageId":"4", "imageId":"4",
"productCodes":[], "productCodes":[],

View File

@ -0,0 +1,56 @@
{
"addresses": [{
"location": "41",
"price": {
"rate": 0.039,
"unitOfMeasure": "UHR",
"countryCode": "897",
"effectiveDate": 1279497600000,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"capacity": 256,
"name": "Small",
"id": "20001208",
"formats": [{
"label": "ext3",
"id": "EXT3"
}]
},
{
"location": "41",
"price": {
"rate": 0.078,
"unitOfMeasure": "UHR",
"countryCode": "897",
"effectiveDate": 1279497600000,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"capacity": 512,
"name": "Medium",
"id": "20001209",
"formats": [{
"label": "ext3",
"id": "EXT3"
}]
},
{
"location": "41",
"price": {
"rate": 0.312,
"unitOfMeasure": "UHR",
"countryCode": "897",
"effectiveDate": 1279497600000,
"currencyCode": "USD",
"pricePerQuantity": 1
},
"capacity": 2048,
"name": "Large",
"id": "20001210",
"formats": [{
"label": "ext3",
"id": "EXT3"
}]
}]
}